feat(ai-report): 新增委托单位管理和报告审批功能

- 新增委托单位管理模块,支持增删改查、导入导出功能
- 实现委托单位 Excel 模板下载和数据导入功能
- 添加报告审批抽象处理器,支持审批流程日志记录
- 统一文件存储路径配置,将各模块独立路径改为统一根目录
- 新增 PQDIF 文件名存储字段,完善文件管理功能
- 修复代码中的乱码问题和错误提示信息
- 优化系统常量定义和字典配置管理
This commit is contained in:
2026-07-01 13:15:57 +08:00
parent 0ea686d3cb
commit c1ad7feec2
99 changed files with 6511 additions and 24 deletions

View File

@@ -11,6 +11,7 @@
</parent>
<artifactId>test-device</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
@@ -30,5 +31,33 @@
<artifactId>spingboot2.3.12</artifactId>
<version>2.3.12</version>
</dependency>
<dependency>
<groupId>com.njcn.gather</groupId>
<artifactId>system</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,149 @@
package com.njcn.gather.aireport.testdevice.component;
import cn.hutool.core.util.StrUtil;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;
@Component
public class TestDeviceReportStorageService {
private static final String DEFAULT_STORAGE_DIR = "data/test-device-report";
private static final String TEST_DEVICE_REPORT_STORAGE_DIR = "test-device-report";
private static final DateTimeFormatter DATE_DIR_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");
private static final long MAX_REPORT_SIZE = 10L * 1024L * 1024L;
private static final int MAX_ORIGINAL_NAME_LENGTH = 80;
@Value("${files.path:}")
private String filesPath;
public String save(MultipartFile reportFile) {
if (reportFile == null || reportFile.isEmpty()) {
throw new BusinessException(CommonResponseEnum.FAIL, "校准报告不能为空");
}
validatePdf(reportFile.getOriginalFilename(), reportFile.getSize());
try (InputStream inputStream = reportFile.getInputStream()) {
return savePdf(reportFile.getOriginalFilename(), inputStream, reportFile.getSize());
} catch (IOException exception) {
throw new BusinessException(CommonResponseEnum.FAIL, "保存校准报告失败");
}
}
public String savePdf(String originalFilename, InputStream inputStream, long size) {
validatePdf(originalFilename, size);
try {
Path storageRoot = resolveStorageRoot();
String dateDir = LocalDate.now().format(DATE_DIR_FORMATTER);
Path storageDir = storageRoot.resolve(dateDir).normalize();
ensurePathInRoot(storageRoot, storageDir);
Files.createDirectories(storageDir);
String fileName = UUID.randomUUID().toString().replace("-", "") + "-" + sanitizeFileName(originalFilename);
Path target = storageDir.resolve(fileName).normalize();
ensurePathInRoot(storageRoot, target);
copyWithSizeLimit(inputStream, target);
return storageRoot.relativize(target).toString().replace('\\', '/');
} catch (BusinessException exception) {
throw exception;
} catch (Exception exception) {
throw new BusinessException(CommonResponseEnum.FAIL, "保存校准报告失败");
}
}
public Path resolveDownloadPath(String storedPath) {
if (StrUtil.isBlank(storedPath)) {
throw new BusinessException(CommonResponseEnum.FAIL, "校准报告路径不能为空");
}
Path storageRoot = resolveStorageRoot();
Path target = storageRoot.resolve(storedPath).normalize();
ensurePathInRoot(storageRoot, target);
return target;
}
public String resolveDownloadFileName(String storedPath) {
Path fileName = Paths.get(storedPath).getFileName();
if (fileName == null) {
return "校准报告.pdf";
}
String name = fileName.toString();
int separatorIndex = name.indexOf('-');
return separatorIndex >= 0 && separatorIndex + 1 < name.length() ? name.substring(separatorIndex + 1) : name;
}
public void deleteQuietly(String storedPath) {
try {
if (StrUtil.isNotBlank(storedPath)) {
Files.deleteIfExists(resolveDownloadPath(storedPath));
}
} catch (Exception ignored) {
// 文件清理失败不能覆盖原始业务结果。
}
}
private void validatePdf(String originalFilename, long size) {
if (StrUtil.isBlank(originalFilename) || !originalFilename.toLowerCase().endsWith(".pdf")) {
throw new BusinessException(CommonResponseEnum.FAIL, "校准报告仅支持PDF文件");
}
if (size > MAX_REPORT_SIZE) {
throw new BusinessException(CommonResponseEnum.FAIL, "校准报告不能超过10MB");
}
}
private void copyWithSizeLimit(InputStream inputStream, Path target) throws IOException {
Path tempFile = Files.createTempFile(target.getParent(), "upload-", ".tmp");
long bytes = 0L;
byte[] buffer = new byte[8192];
try {
int length;
try (InputStream source = inputStream;
OutputStream targetStream = Files.newOutputStream(tempFile)) {
while ((length = source.read(buffer)) != -1) {
bytes += length;
if (bytes > MAX_REPORT_SIZE) {
throw new BusinessException(CommonResponseEnum.FAIL, "校准报告不能超过10MB");
}
targetStream.write(buffer, 0, length);
}
}
Files.move(tempFile, target, StandardCopyOption.REPLACE_EXISTING);
} finally {
Files.deleteIfExists(tempFile);
}
}
private Path resolveStorageRoot() {
String configuredPath = StrUtil.isBlank(filesPath) ? null : filesPath.trim();
Path path = configuredPath == null ? Paths.get(DEFAULT_STORAGE_DIR) : Paths.get(configuredPath, TEST_DEVICE_REPORT_STORAGE_DIR);
return path.toAbsolutePath().normalize();
}
private void ensurePathInRoot(Path storageRoot, Path target) {
if (!target.startsWith(storageRoot)) {
throw new BusinessException(CommonResponseEnum.FAIL, "校准报告路径不合法");
}
}
private String sanitizeFileName(String originalFilename) {
String fileName = Paths.get(originalFilename).getFileName().toString();
String sanitized = fileName.replaceAll("[\\\\/:*?\"<>|]", "_");
if (sanitized.length() > MAX_ORIGINAL_NAME_LENGTH) {
String suffix = sanitized.toLowerCase().endsWith(".pdf") ? ".pdf" : "";
int keepLength = MAX_ORIGINAL_NAME_LENGTH - suffix.length();
sanitized = sanitized.substring(0, keepLength) + suffix;
}
return StrUtil.isBlank(sanitized) ? "report.pdf" : sanitized;
}
}

View File

@@ -0,0 +1,165 @@
package com.njcn.gather.aireport.testdevice.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.constant.OperateType;
import com.njcn.common.pojo.enums.common.LogEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.gather.aireport.testdevice.component.TestDeviceReportStorageService;
import com.njcn.gather.aireport.testdevice.pojo.param.TestDeviceParam;
import com.njcn.gather.aireport.testdevice.pojo.po.TestDevicePO;
import com.njcn.gather.aireport.testdevice.pojo.vo.TestDeviceImportResultVO;
import com.njcn.gather.aireport.testdevice.pojo.vo.TestDeviceVO;
import com.njcn.gather.aireport.testdevice.service.TestDeviceService;
import com.njcn.web.controller.BaseController;
import com.njcn.web.utils.HttpResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
@Api(tags = "检测设备管理")
@RestController
@RequestMapping("/api/test-device")
@RequiredArgsConstructor
public class TestDeviceController extends BaseController {
private final TestDeviceService testDeviceService;
private final TestDeviceReportStorageService reportStorageService;
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@ApiOperation("查询检测设备列表")
@PostMapping("/list")
public HttpResult<Page<TestDeviceVO>> list(@RequestBody(required = false) TestDeviceParam.QueryParam param) {
String methodDescribe = getMethodDescribe("list");
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS,
testDeviceService.listTestDevices(param), methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.ADD)
@ApiOperation("新增检测设备")
@PostMapping(value = "/add", consumes = {"multipart/form-data"})
public HttpResult<Boolean> add(@RequestPart("request") @Validated TestDeviceParam.AddParam param,
@RequestPart("reportFile") MultipartFile reportFile) {
String methodDescribe = getMethodDescribe("add");
boolean result = testDeviceService.addTestDevice(param, reportFile);
return HttpResultUtil.assembleCommonResponseResult(result ? CommonResponseEnum.SUCCESS : CommonResponseEnum.FAIL,
result, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.UPDATE)
@ApiOperation("编辑检测设备")
@PostMapping(value = "/update", consumes = {"multipart/form-data"})
public HttpResult<Boolean> update(@RequestPart("request") @Validated TestDeviceParam.UpdateParam param,
@RequestPart(value = "reportFile", required = false) MultipartFile reportFile) {
String methodDescribe = getMethodDescribe("update");
boolean result = testDeviceService.updateTestDevice(param, reportFile);
return HttpResultUtil.assembleCommonResponseResult(result ? CommonResponseEnum.SUCCESS : CommonResponseEnum.FAIL,
result, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.DELETE)
@ApiOperation("删除检测设备")
@PostMapping("/delete")
public HttpResult<Boolean> delete(@RequestBody List<String> ids) {
String methodDescribe = getMethodDescribe("delete");
boolean result = testDeviceService.deleteTestDevices(ids);
return HttpResultUtil.assembleCommonResponseResult(result ? CommonResponseEnum.SUCCESS : CommonResponseEnum.FAIL,
result, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@ApiOperation("查询检测设备详情")
@ApiImplicitParam(name = "id", value = "检测设备ID", required = true)
@GetMapping("/{id}")
public HttpResult<TestDeviceVO> detail(@PathVariable("id") String id) {
String methodDescribe = getMethodDescribe("detail");
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS,
testDeviceService.getTestDevice(id), methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@ApiOperation("下载检测设备导入模板")
@GetMapping("/template")
public void template() {
testDeviceService.downloadTemplate();
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.ADD)
@ApiOperation("导入检测设备")
@PostMapping(value = "/import", consumes = {"multipart/form-data"})
public HttpResult<TestDeviceImportResultVO> importExcel(@RequestPart("file") MultipartFile file,
@RequestPart("reportZip") MultipartFile reportZip) {
String methodDescribe = getMethodDescribe("importExcel");
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS,
testDeviceService.importTestDevices(file, reportZip), methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@ApiOperation("导出检测设备")
@GetMapping("/export")
public void export(@ModelAttribute TestDeviceParam.QueryParam param) {
testDeviceService.exportTestDevices(param);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@ApiOperation("下载检测设备校准报告")
@ApiImplicitParam(name = "id", value = "检测设备ID", required = true)
@GetMapping("/{id}/report")
public ResponseEntity<InputStreamResource> report(@PathVariable("id") String id) {
return buildReportResponse(id, false);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@ApiOperation("预览检测设备校准报告")
@ApiImplicitParam(name = "id", value = "检测设备ID", required = true)
@GetMapping("/{id}/report/preview")
public ResponseEntity<InputStreamResource> previewReport(@PathVariable("id") String id) {
return buildReportResponse(id, true);
}
private ResponseEntity<InputStreamResource> buildReportResponse(String id, boolean preview) {
TestDevicePO device = testDeviceService.requireNormal(id);
if (device == null || device.getValidityReport() == null || device.getValidityReport().trim().isEmpty()) {
throw new BusinessException(CommonResponseEnum.FAIL, "校准报告文件不存在");
}
Path filePath = reportStorageService.resolveDownloadPath(device.getValidityReport());
if (!Files.exists(filePath) || !Files.isRegularFile(filePath)) {
throw new BusinessException(CommonResponseEnum.FAIL, "校准报告文件不存在");
}
try {
String fileName = reportStorageService.resolveDownloadFileName(device.getValidityReport());
String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");
InputStream inputStream = Files.newInputStream(filePath);
return ResponseEntity.ok()
.contentType(preview ? MediaType.APPLICATION_PDF : MediaType.APPLICATION_OCTET_STREAM)
.header(HttpHeaders.CONTENT_DISPOSITION,
(preview ? "inline" : "attachment") + "; filename*=UTF-8''" + encodedFileName)
.body(new InputStreamResource(inputStream));
} catch (Exception exception) {
throw new BusinessException(CommonResponseEnum.FAIL, "读取校准报告失败");
}
}
}

View File

@@ -0,0 +1,61 @@
package com.njcn.gather.aireport.testdevice.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.gather.aireport.testdevice.pojo.param.TestDeviceParam;
import com.njcn.gather.aireport.testdevice.pojo.po.TestDevicePO;
import com.njcn.gather.aireport.testdevice.pojo.vo.TestDeviceTypeNameVO;
import com.njcn.gather.aireport.testdevice.pojo.vo.TestDeviceVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface TestDeviceMapper extends BaseMapper<TestDevicePO> {
@Select({
"<script>",
"select d.id, d.type, dt.name as typeName, d.no, d.validity_period as validityPeriod,",
"d.validity_report as validityReport, d.state, d.status, d.create_by as createBy,",
"creator.name as createByName, d.create_time as createTime, d.update_by as updateBy,",
"updater.name as updateByName, d.update_time as updateTime",
"from ai_testdevice d",
"left join cs_dev_type dt on d.type = dt.id",
"left join sys_user creator on d.create_by = creator.id",
"left join sys_user updater on d.update_by = updater.id",
"where d.status = 1",
"<if test='param.keyword != null and param.keyword != \"\"'>",
"and (d.no like concat('%', #{param.keyword}, '%') or dt.name like concat('%', #{param.keyword}, '%'))",
"</if>",
"<if test='param.searchBeginTime != null and param.searchBeginTime != \"\"'>",
"and d.create_time &gt;= #{param.searchBeginTime}",
"</if>",
"<if test='param.searchEndTime != null and param.searchEndTime != \"\"'>",
"and d.create_time &lt;= #{param.searchEndTime}",
"</if>",
"order by d.create_time desc",
"</script>"
})
Page<TestDeviceVO> selectDevicePage(Page<TestDeviceVO> page, @Param("param") TestDeviceParam.QueryParam param);
@Select({
"select d.id, d.type, dt.name as typeName, d.no, d.validity_period as validityPeriod,",
"d.validity_report as validityReport, d.state, d.status, d.create_by as createBy,",
"creator.name as createByName, d.create_time as createTime, d.update_by as updateBy,",
"updater.name as updateByName, d.update_time as updateTime",
"from ai_testdevice d",
"left join cs_dev_type dt on d.type = dt.id",
"left join sys_user creator on d.create_by = creator.id",
"left join sys_user updater on d.update_by = updater.id",
"where d.id = #{id} and d.status = 1"
})
TestDeviceVO selectDeviceDetail(@Param("id") String id);
@Select("select count(1) from cs_dev_type where id = #{typeId} and State = 1")
int countNormalDeviceType(@Param("typeId") String typeId);
@Select("select id, name from cs_dev_type where State = 1")
List<TestDeviceTypeNameVO> selectNormalDeviceTypes();
}

View File

@@ -0,0 +1,12 @@
package com.njcn.gather.aireport.testdevice.pojo.constant;
public final class TestDeviceConst {
public static final String STATE_RUNNING = "01";
public static final String STATE_RETIRED = "02";
public static final Integer STATUS_NORMAL = 1;
public static final Integer STATUS_DELETED = 0;
private TestDeviceConst() {
}
}

View File

@@ -0,0 +1,49 @@
package com.njcn.gather.aireport.testdevice.pojo.param;
import com.njcn.web.pojo.param.BaseParam;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.validation.constraints.NotBlank;
public class TestDeviceParam {
@Data
@EqualsAndHashCode(callSuper = true)
public static class QueryParam extends BaseParam {
@ApiModelProperty("关键字,匹配设备型号名称或设备编号")
private String keyword;
@ApiModelProperty("创建开始时间yyyy-MM-dd HH:mm:ss")
private String searchBeginTime;
@ApiModelProperty("创建结束时间yyyy-MM-dd HH:mm:ss")
private String searchEndTime;
}
@Data
public static class AddParam {
@ApiModelProperty("设备型号ID")
@NotBlank(message = "设备型号不能为空")
private String type;
@ApiModelProperty("设备编号")
@NotBlank(message = "设备编号不能为空")
private String no;
@ApiModelProperty("校准有效期yyyy-MM-dd")
@NotBlank(message = "校准有效期不能为空")
private String validityPeriod;
@ApiModelProperty("设备状态01-在运02-退运")
private String state;
}
@Data
public static class UpdateParam extends AddParam {
@ApiModelProperty("检测设备ID")
@NotBlank(message = "检测设备ID不能为空")
private String id;
}
}

View File

@@ -0,0 +1,39 @@
package com.njcn.gather.aireport.testdevice.pojo.po;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Data
@TableName("ai_testdevice")
public class TestDevicePO implements Serializable {
private static final long serialVersionUID = 4153967564253668210L;
@TableId("id")
private String id;
@TableField("type")
private String type;
@TableField("no")
private String no;
@TableField("validity_period")
private LocalDate validityPeriod;
@TableField("validity_report")
private String validityReport;
@TableField("state")
private String state;
@TableField("status")
private Integer status;
@TableField("create_by")
private String createBy;
@TableField("create_time")
private LocalDateTime createTime;
@TableField("update_by")
private String updateBy;
@TableField("update_time")
private LocalDateTime updateTime;
}

View File

@@ -0,0 +1,32 @@
package com.njcn.gather.aireport.testdevice.pojo.vo;
import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;
import java.io.Serializable;
@Data
public class TestDeviceExcelVO implements Serializable {
private static final long serialVersionUID = 8111740807955262764L;
@Excel(name = "设备型号", width = 25)
private String typeName;
@Excel(name = "设备编号", width = 25)
private String no;
@Excel(name = "校准有效期", width = 20)
private String validityPeriod;
@Excel(name = "设备状态", width = 15)
private String stateName;
@Excel(name = "校准报告文件名", width = 35)
private String validityReportName;
@Excel(name = "创建时间", width = 25)
private String createTime;
@Excel(name = "创建人", width = 20)
private String createByName;
}

View File

@@ -0,0 +1,13 @@
package com.njcn.gather.aireport.testdevice.pojo.vo;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
public class TestDeviceImportResultVO {
private int successCount;
private int failCount;
private List<String> failReasons = new ArrayList<String>();
}

View File

@@ -0,0 +1,9 @@
package com.njcn.gather.aireport.testdevice.pojo.vo;
import lombok.Data;
@Data
public class TestDeviceTypeNameVO {
private String id;
private String name;
}

View File

@@ -0,0 +1,59 @@
package com.njcn.gather.aireport.testdevice.pojo.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Data
public class TestDeviceVO {
@ApiModelProperty("检测设备ID")
private String id;
@ApiModelProperty("设备型号ID")
private String type;
@ApiModelProperty("设备型号名称")
private String typeName;
@ApiModelProperty("设备编号")
private String no;
@ApiModelProperty("校准有效期")
@JsonFormat(pattern = "yyyy-MM-dd")
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate validityPeriod;
@ApiModelProperty("校准报告存储路径")
private String validityReport;
@ApiModelProperty("校准报告文件名")
private String validityReportName;
@ApiModelProperty("校准报告下载地址")
private String validityReportUrl;
@ApiModelProperty("设备状态01-在运02-退役")
private String state;
@ApiModelProperty("逻辑状态")
private Integer status;
@ApiModelProperty("创建人ID")
private String createBy;
@ApiModelProperty("创建人显示名")
private String createByName;
@ApiModelProperty("创建时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
private LocalDateTime createTime;
@ApiModelProperty("更新人ID")
private String updateBy;
@ApiModelProperty("更新人显示名")
private String updateByName;
@ApiModelProperty("更新时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
private LocalDateTime updateTime;
}

View File

@@ -0,0 +1,32 @@
package com.njcn.gather.aireport.testdevice.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.njcn.gather.aireport.testdevice.pojo.param.TestDeviceParam;
import com.njcn.gather.aireport.testdevice.pojo.po.TestDevicePO;
import com.njcn.gather.aireport.testdevice.pojo.vo.TestDeviceImportResultVO;
import com.njcn.gather.aireport.testdevice.pojo.vo.TestDeviceVO;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
public interface TestDeviceService extends IService<TestDevicePO> {
Page<TestDeviceVO> listTestDevices(TestDeviceParam.QueryParam param);
boolean addTestDevice(TestDeviceParam.AddParam param, MultipartFile reportFile);
boolean updateTestDevice(TestDeviceParam.UpdateParam param, MultipartFile reportFile);
boolean deleteTestDevices(List<String> ids);
TestDeviceVO getTestDevice(String id);
TestDevicePO requireNormal(String id);
void downloadTemplate();
TestDeviceImportResultVO importTestDevices(MultipartFile file, MultipartFile reportZip);
void exportTestDevices(TestDeviceParam.QueryParam param);
}

View File

@@ -0,0 +1,666 @@
package com.njcn.gather.aireport.testdevice.service.impl;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.gather.aireport.testdevice.component.TestDeviceReportStorageService;
import com.njcn.gather.aireport.testdevice.mapper.TestDeviceMapper;
import com.njcn.gather.aireport.testdevice.pojo.constant.TestDeviceConst;
import com.njcn.gather.aireport.testdevice.pojo.param.TestDeviceParam;
import com.njcn.gather.aireport.testdevice.pojo.po.TestDevicePO;
import com.njcn.gather.aireport.testdevice.pojo.vo.TestDeviceExcelVO;
import com.njcn.gather.aireport.testdevice.pojo.vo.TestDeviceImportResultVO;
import com.njcn.gather.aireport.testdevice.pojo.vo.TestDeviceTypeNameVO;
import com.njcn.gather.aireport.testdevice.pojo.vo.TestDeviceVO;
import com.njcn.gather.aireport.testdevice.service.TestDeviceService;
import com.njcn.gather.system.util.ExportFileNameUtil;
import com.njcn.web.factory.PageFactory;
import com.njcn.web.utils.ExcelUtil;
import com.njcn.web.utils.HttpServletUtil;
import com.njcn.web.utils.RequestUtil;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
@Slf4j
@Service
@RequiredArgsConstructor
public class TestDeviceServiceImpl extends ServiceImpl<TestDeviceMapper, TestDevicePO> implements TestDeviceService {
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private static final String[] TEMPLATE_HEADERS = new String[]{"设备型号", "设备编号", "校准有效期", "设备状态", "校准报告文件名"};
private static final long MAX_IMPORT_REPORT_SIZE = 10L * 1024L * 1024L;
private final TestDeviceReportStorageService reportStorageService;
@Override
public Page<TestDeviceVO> listTestDevices(TestDeviceParam.QueryParam param) {
TestDeviceParam.QueryParam query = normalizeQueryParam(param);
Page<TestDeviceVO> page = this.baseMapper.selectDevicePage(
new Page<TestDeviceVO>(PageFactory.getPageNum(query), PageFactory.getPageSize(query)), query);
page.getRecords().forEach(this::fillReportDisplayFields);
return page;
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean addTestDevice(TestDeviceParam.AddParam param, MultipartFile reportFile) {
NormalizedDevice data = normalizeParam(param);
checkDeviceType(data.getType());
checkNoUnique(data.getNo(), null);
String storedPath = reportStorageService.save(reportFile);
try {
LocalDateTime now = LocalDateTime.now();
String userId = resolveCurrentUserId();
TestDevicePO device = new TestDevicePO();
device.setId(UUID.randomUUID().toString());
device.setType(data.getType());
device.setNo(data.getNo());
device.setValidityPeriod(data.getValidityPeriod());
device.setValidityReport(storedPath);
device.setState(data.getState());
device.setStatus(TestDeviceConst.STATUS_NORMAL);
device.setCreateBy(userId);
device.setCreateTime(now);
device.setUpdateBy(userId);
device.setUpdateTime(now);
boolean saved = this.save(device);
if (!saved) {
reportStorageService.deleteQuietly(storedPath);
}
return saved;
} catch (RuntimeException exception) {
reportStorageService.deleteQuietly(storedPath);
throw exception;
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean updateTestDevice(TestDeviceParam.UpdateParam param, MultipartFile reportFile) {
if (param == null || StrUtil.isBlank(param.getId())) {
throw new BusinessException(CommonResponseEnum.FAIL, "检测设备ID不能为空");
}
TestDevicePO device = requireNormal(param.getId());
NormalizedDevice data = normalizeParam(param);
checkDeviceType(data.getType());
checkNoUnique(data.getNo(), device.getId());
String oldReport = device.getValidityReport();
String newReport = null;
if (reportFile != null && !reportFile.isEmpty()) {
newReport = reportStorageService.save(reportFile);
device.setValidityReport(newReport);
} else if (StrUtil.isBlank(oldReport)) {
throw new BusinessException(CommonResponseEnum.FAIL, "校准报告不能为空");
}
try {
device.setType(data.getType());
device.setNo(data.getNo());
device.setValidityPeriod(data.getValidityPeriod());
device.setState(data.getState());
device.setUpdateBy(resolveCurrentUserId());
device.setUpdateTime(LocalDateTime.now());
boolean updated = this.updateById(device);
if (!updated) {
reportStorageService.deleteQuietly(newReport);
return false;
}
if (StrUtil.isNotBlank(newReport)) {
reportStorageService.deleteQuietly(oldReport);
}
return true;
} catch (RuntimeException exception) {
reportStorageService.deleteQuietly(newReport);
throw exception;
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean deleteTestDevices(List<String> ids) {
List<String> validIds = normalizeIds(ids);
if (validIds.isEmpty()) {
throw new BusinessException(CommonResponseEnum.FAIL, "检测设备ID不能为空");
}
return this.lambdaUpdate()
.set(TestDevicePO::getStatus, TestDeviceConst.STATUS_DELETED)
.set(TestDevicePO::getUpdateBy, resolveCurrentUserId())
.set(TestDevicePO::getUpdateTime, LocalDateTime.now())
.in(TestDevicePO::getId, validIds)
.eq(TestDevicePO::getStatus, TestDeviceConst.STATUS_NORMAL)
.update();
}
@Override
public TestDeviceVO getTestDevice(String id) {
TestDeviceVO vo = this.baseMapper.selectDeviceDetail(requireText(id, "检测设备ID不能为空"));
if (vo == null) {
throw new BusinessException(CommonResponseEnum.FAIL, "检测设备不存在或已删除");
}
fillReportDisplayFields(vo);
return vo;
}
@Override
public TestDevicePO requireNormal(String id) {
String normalizedId = requireText(id, "检测设备ID不能为空");
TestDevicePO device = this.lambdaQuery()
.eq(TestDevicePO::getId, normalizedId)
.eq(TestDevicePO::getStatus, TestDeviceConst.STATUS_NORMAL)
.one();
if (device == null) {
throw new BusinessException(CommonResponseEnum.FAIL, "检测设备不存在或已删除");
}
return device;
}
@Override
public void downloadTemplate() {
HttpServletResponse response = HttpServletUtil.getResponse();
try (XSSFWorkbook workbook = new XSSFWorkbook()) {
XSSFSheet sheet = workbook.createSheet("检测设备导入模板");
writeTemplateHeader(workbook, sheet);
String fileName = URLEncoder.encode(ExportFileNameUtil.appendToday("检测设备导入模板.xlsx"), "UTF-8");
response.reset();
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
try (ServletOutputStream outputStream = response.getOutputStream()) {
workbook.write(outputStream);
outputStream.flush();
}
} catch (IOException exception) {
log.error("下载检测设备导入模板失败", exception);
throw new BusinessException(CommonResponseEnum.FAIL, "下载检测设备导入模板失败");
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public TestDeviceImportResultVO importTestDevices(MultipartFile file, MultipartFile reportZip) {
if (file == null || file.isEmpty()) {
throw new BusinessException(CommonResponseEnum.FAIL, "导入文件不能为空");
}
if (reportZip == null || reportZip.isEmpty()) {
throw new BusinessException(CommonResponseEnum.FAIL, "校准报告压缩包不能为空");
}
List<TestDeviceExcelVO> rows = readImportRows(file);
TestDeviceImportResultVO result = new TestDeviceImportResultVO();
if (rows.isEmpty()) {
return result;
}
ImportArchive archive = readReportZip(reportZip);
try {
Map<String, String> typeNameIdMap = loadTypeNameIdMap();
List<NormalizedImportDevice> devices = validateImportRows(rows, archive, typeNameIdMap, result);
if (result.getFailCount() > 0) {
return result;
}
List<String> savedReports = new ArrayList<String>();
try {
LocalDateTime now = LocalDateTime.now();
String userId = resolveCurrentUserId();
List<TestDevicePO> saveRows = new ArrayList<TestDevicePO>();
for (NormalizedImportDevice data : devices) {
String storedPath;
try (InputStream inputStream = Files.newInputStream(data.getReportPath())) {
storedPath = reportStorageService.savePdf(data.getReportName(), inputStream, Files.size(data.getReportPath()));
} catch (IOException exception) {
throw new BusinessException(CommonResponseEnum.FAIL, "读取校准报告压缩包失败");
}
savedReports.add(storedPath);
TestDevicePO device = new TestDevicePO();
device.setId(UUID.randomUUID().toString());
device.setType(data.getType());
device.setNo(data.getNo());
device.setValidityPeriod(data.getValidityPeriod());
device.setValidityReport(storedPath);
device.setState(data.getState());
device.setStatus(TestDeviceConst.STATUS_NORMAL);
device.setCreateBy(userId);
device.setCreateTime(now);
device.setUpdateBy(userId);
device.setUpdateTime(now);
saveRows.add(device);
}
boolean saved = saveRows.isEmpty() || this.saveBatch(saveRows);
if (!saved) {
savedReports.forEach(reportStorageService::deleteQuietly);
return result;
}
result.setSuccessCount(saveRows.size());
return result;
} catch (RuntimeException exception) {
savedReports.forEach(reportStorageService::deleteQuietly);
throw exception;
}
} finally {
archive.cleanup();
}
}
@Override
public void exportTestDevices(TestDeviceParam.QueryParam param) {
TestDeviceParam.QueryParam query = normalizeQueryParam(param);
Page<TestDeviceVO> page = this.baseMapper.selectDevicePage(new Page<TestDeviceVO>(1, Integer.MAX_VALUE), query);
List<TestDeviceExcelVO> exportRows = page.getRecords().stream()
.peek(this::fillReportDisplayFields)
.map(this::toExcelVO)
.collect(Collectors.toList());
ExcelUtil.exportExcel(ExportFileNameUtil.appendToday("检测设备列表.xlsx"), "检测设备列表",
TestDeviceExcelVO.class, exportRows);
}
private TestDeviceParam.QueryParam normalizeQueryParam(TestDeviceParam.QueryParam param) {
TestDeviceParam.QueryParam query = param == null ? new TestDeviceParam.QueryParam() : param;
query.setKeyword(trimToNull(query.getKeyword()));
if (StrUtil.isNotBlank(query.getSearchBeginTime())) {
query.setSearchBeginTime(formatDateTime(parseDateTime(query.getSearchBeginTime(), "开始时间格式不正确")));
}
if (StrUtil.isNotBlank(query.getSearchEndTime())) {
query.setSearchEndTime(formatDateTime(parseDateTime(query.getSearchEndTime(), "结束时间格式不正确")));
}
return query;
}
private NormalizedDevice normalizeParam(TestDeviceParam.AddParam param) {
if (param == null) {
throw new BusinessException(CommonResponseEnum.FAIL, "检测设备参数不能为空");
}
NormalizedDevice data = new NormalizedDevice();
data.setType(requireText(param.getType(), "设备型号不能为空"));
data.setNo(requireText(param.getNo(), "设备编号不能为空", 64, "设备编号不能超过64个字符"));
data.setValidityPeriod(parseDate(requireText(param.getValidityPeriod(), "校准有效期不能为空")));
data.setState(normalizeState(param.getState()));
return data;
}
private List<NormalizedImportDevice> validateImportRows(List<TestDeviceExcelVO> rows, ImportArchive archive,
Map<String, String> typeNameIdMap, TestDeviceImportResultVO result) {
Set<String> fileNos = new HashSet<String>();
List<NormalizedImportDevice> devices = new ArrayList<NormalizedImportDevice>();
for (int i = 0; i < rows.size(); i++) {
int rowNumber = i + 2;
try {
TestDeviceExcelVO row = rows.get(i);
NormalizedImportDevice device = new NormalizedImportDevice();
String typeName = requireText(row.getTypeName(), "设备型号不能为空");
String typeId = typeNameIdMap.get(typeName);
if (StrUtil.isBlank(typeId)) {
throw new BusinessException(CommonResponseEnum.FAIL, "设备型号不存在或已删除");
}
device.setType(typeId);
device.setNo(requireText(row.getNo(), "设备编号不能为空", 64, "设备编号不能超过64个字符"));
if (!fileNos.add(device.getNo())) {
throw new BusinessException(CommonResponseEnum.FAIL, "文件内存在重复设备编号");
}
checkNoUnique(device.getNo(), null);
device.setValidityPeriod(parseDate(requireText(row.getValidityPeriod(), "校准有效期不能为空")));
device.setState(normalizeState(row.getStateName()));
device.setReportName(requireText(row.getValidityReportName(), "校准报告文件名不能为空"));
Path reportPath = archive.getReportPath(device.getReportName());
if (reportPath == null) {
throw new BusinessException(CommonResponseEnum.FAIL, "校准报告压缩包中未找到对应PDF");
}
device.setReportPath(reportPath);
devices.add(device);
} catch (BusinessException exception) {
result.setFailCount(result.getFailCount() + 1);
result.getFailReasons().add("" + rowNumber + "行:" + exception.getMessage());
}
}
return devices;
}
private List<TestDeviceExcelVO> readImportRows(MultipartFile file) {
try (InputStream inputStream = file.getInputStream();
XSSFWorkbook workbook = new XSSFWorkbook(inputStream)) {
XSSFSheet sheet = workbook.getNumberOfSheets() == 0 ? null : workbook.getSheetAt(0);
if (sheet == null || sheet.getLastRowNum() < 1) {
return Collections.emptyList();
}
List<TestDeviceExcelVO> rows = new ArrayList<TestDeviceExcelVO>();
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
if (isEmptyRow(row)) {
continue;
}
TestDeviceExcelVO excelVO = new TestDeviceExcelVO();
excelVO.setTypeName(readCell(row, 0));
excelVO.setNo(readCell(row, 1));
excelVO.setValidityPeriod(readCell(row, 2));
excelVO.setStateName(readCell(row, 3));
excelVO.setValidityReportName(readCell(row, 4));
rows.add(excelVO);
}
return rows;
} catch (IOException exception) {
log.error("读取检测设备导入文件失败", exception);
throw new BusinessException(CommonResponseEnum.FAIL, "读取导入文件失败");
}
}
ImportArchive readReportZip(MultipartFile reportZip) {
Path tempDir;
try {
tempDir = Files.createTempDirectory("test-device-import-");
} catch (IOException exception) {
throw new BusinessException(CommonResponseEnum.FAIL, "读取校准报告压缩包失败");
}
Map<String, Path> files = new HashMap<String, Path>();
try (ZipInputStream zipInputStream = new ZipInputStream(reportZip.getInputStream())) {
ZipEntry entry;
while ((entry = zipInputStream.getNextEntry()) != null) {
if (entry.isDirectory()) {
continue;
}
String fileName = Paths.get(entry.getName()).getFileName().toString();
if (!fileName.toLowerCase().endsWith(".pdf")) {
throw new BusinessException(CommonResponseEnum.FAIL, "校准报告压缩包仅允许包含PDF文件");
}
if (files.containsKey(fileName)) {
throw new BusinessException(CommonResponseEnum.FAIL, "校准报告压缩包中存在重复文件名");
}
files.put(fileName, readZipEntryToFile(tempDir, fileName, zipInputStream));
}
return new ImportArchive(tempDir, files);
} catch (BusinessException exception) {
deleteDirectoryQuietly(tempDir);
throw exception;
} catch (IOException exception) {
deleteDirectoryQuietly(tempDir);
log.error("读取校准报告压缩包失败", exception);
throw new BusinessException(CommonResponseEnum.FAIL, "读取校准报告压缩包失败");
}
}
private Path readZipEntryToFile(Path tempDir, String fileName, ZipInputStream zipInputStream) throws IOException {
Path tempFile = tempDir.resolve(UUID.randomUUID().toString().replace("-", "") + "-" + fileName).normalize();
long bytes = 0L;
byte[] buffer = new byte[8192];
try (OutputStream outputStream = Files.newOutputStream(tempFile)) {
int length;
while ((length = zipInputStream.read(buffer)) != -1) {
bytes += length;
if (bytes > MAX_IMPORT_REPORT_SIZE) {
throw new BusinessException(CommonResponseEnum.FAIL, "校准报告不能超过10MB");
}
outputStream.write(buffer, 0, length);
}
} catch (BusinessException exception) {
Files.deleteIfExists(tempFile);
throw exception;
} catch (IOException exception) {
Files.deleteIfExists(tempFile);
throw exception;
}
return tempFile;
}
private void deleteDirectoryQuietly(Path directory) {
if (directory == null || !Files.exists(directory)) {
return;
}
try (Stream<Path> pathStream = Files.walk(directory)) {
pathStream.sorted(Comparator.reverseOrder()).forEach(path -> {
try {
Files.deleteIfExists(path);
} catch (IOException ignored) {
// 导入临时目录清理失败不影响主流程返回。
}
});
} catch (IOException ignored) {
// 导入临时目录清理失败不影响主流程返回。
}
}
private void writeTemplateHeader(XSSFWorkbook workbook, XSSFSheet sheet) {
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
font.setBold(true);
style.setFont(font);
Row row = sheet.createRow(0);
for (int i = 0; i < TEMPLATE_HEADERS.length; i++) {
Cell cell = row.createCell(i);
cell.setCellValue(TEMPLATE_HEADERS[i]);
cell.setCellStyle(style);
sheet.setColumnWidth(i, 25 * 256);
}
}
private boolean isEmptyRow(Row row) {
if (row == null) {
return true;
}
for (int i = 0; i < TEMPLATE_HEADERS.length; i++) {
if (StrUtil.isNotBlank(readCell(row, i))) {
return false;
}
}
return true;
}
private String readCell(Row row, int index) {
Cell cell = row.getCell(index);
return cell == null ? null : trimToNull(new DataFormatter().formatCellValue(cell));
}
private void fillReportDisplayFields(TestDeviceVO vo) {
if (vo == null || StrUtil.isBlank(vo.getValidityReport())) {
return;
}
vo.setValidityReportName(reportStorageService.resolveDownloadFileName(vo.getValidityReport()));
vo.setValidityReportUrl("/api/test-device/" + vo.getId() + "/report");
}
private TestDeviceExcelVO toExcelVO(TestDeviceVO vo) {
TestDeviceExcelVO excelVO = new TestDeviceExcelVO();
excelVO.setTypeName(vo.getTypeName());
excelVO.setNo(vo.getNo());
excelVO.setValidityPeriod(vo.getValidityPeriod() == null ? null : DATE_FORMATTER.format(vo.getValidityPeriod()));
excelVO.setStateName(resolveStateName(vo.getState()));
excelVO.setValidityReportName(vo.getValidityReportName());
excelVO.setCreateByName(StrUtil.isNotBlank(vo.getCreateByName()) ? vo.getCreateByName() : vo.getCreateBy());
excelVO.setCreateTime(vo.getCreateTime() == null ? null : DATE_TIME_FORMATTER.format(vo.getCreateTime()));
return excelVO;
}
private Map<String, String> loadTypeNameIdMap() {
List<TestDeviceTypeNameVO> types = this.baseMapper.selectNormalDeviceTypes();
if (types == null || types.isEmpty()) {
return Collections.emptyMap();
}
return types.stream()
.filter(type -> type != null && StrUtil.isNotBlank(type.getName()) && StrUtil.isNotBlank(type.getId()))
.collect(Collectors.toMap(TestDeviceTypeNameVO::getName, TestDeviceTypeNameVO::getId, (first, second) -> first));
}
private void checkDeviceType(String type) {
if (this.baseMapper.countNormalDeviceType(type) <= 0) {
throw new BusinessException(CommonResponseEnum.FAIL, "设备型号不存在或已删除");
}
}
private void checkNoUnique(String no, String excludeId) {
LambdaQueryWrapper<TestDevicePO> wrapper = new LambdaQueryWrapper<TestDevicePO>();
wrapper.eq(TestDevicePO::getNo, no)
.ne(StrUtil.isNotBlank(excludeId), TestDevicePO::getId, excludeId);
if (this.count(wrapper) > 0) {
throw new BusinessException(CommonResponseEnum.FAIL, "设备编号已存在");
}
}
private List<String> normalizeIds(List<String> ids) {
if (ids == null || ids.isEmpty()) {
return Collections.emptyList();
}
List<String> result = new ArrayList<String>();
for (String id : ids) {
String normalizedId = trimToNull(id);
if (normalizedId != null && !result.contains(normalizedId)) {
result.add(normalizedId);
}
}
return result;
}
private LocalDate parseDate(String value) {
try {
return LocalDate.parse(value.trim(), DATE_FORMATTER);
} catch (DateTimeParseException exception) {
throw new BusinessException(CommonResponseEnum.FAIL, "校准有效期格式不正确");
}
}
private LocalDateTime parseDateTime(String value, String errorMessage) {
try {
return LocalDateTime.parse(value.trim(), DATE_TIME_FORMATTER);
} catch (DateTimeParseException exception) {
throw new BusinessException(CommonResponseEnum.FAIL, errorMessage);
}
}
private String formatDateTime(LocalDateTime value) {
return DATE_TIME_FORMATTER.format(value);
}
private String normalizeState(String state) {
String text = trimToNull(state);
if (text == null || "在运".equals(text) || TestDeviceConst.STATE_RUNNING.equals(text)) {
return TestDeviceConst.STATE_RUNNING;
}
if ("退运".equals(text) || TestDeviceConst.STATE_RETIRED.equals(text)) {
return TestDeviceConst.STATE_RETIRED;
}
throw new BusinessException(CommonResponseEnum.FAIL, "设备状态不正确");
}
private String resolveStateName(String state) {
if (TestDeviceConst.STATE_RUNNING.equals(state)) {
return "在运";
}
if (TestDeviceConst.STATE_RETIRED.equals(state)) {
return "退运";
}
return state;
}
private String requireText(String value, String blankMessage) {
String text = trimToNull(value);
if (text == null) {
throw new BusinessException(CommonResponseEnum.FAIL, blankMessage);
}
return text;
}
private String requireText(String value, String blankMessage, int maxLength, String lengthMessage) {
String text = requireText(value, blankMessage);
if (text.length() > maxLength) {
throw new BusinessException(CommonResponseEnum.FAIL, lengthMessage);
}
return text;
}
private String resolveCurrentUserId() {
String userId = RequestUtil.getUserId();
return StrUtil.isBlank(userId) ? null : userId;
}
private String trimToNull(String value) {
if (value == null) {
return null;
}
String text = value.trim();
return text.isEmpty() ? null : text;
}
@Data
private static class NormalizedDevice {
private String type;
private String no;
private LocalDate validityPeriod;
private String state;
}
@Data
private static class NormalizedImportDevice extends NormalizedDevice {
private String reportName;
private Path reportPath;
}
static class ImportArchive {
private final Path tempDir;
private final Map<String, Path> reportFiles;
ImportArchive(Path tempDir, Map<String, Path> reportFiles) {
this.tempDir = tempDir;
this.reportFiles = reportFiles;
}
Path getReportPath(String fileName) {
return reportFiles.get(fileName);
}
void cleanup() {
if (tempDir == null || !Files.exists(tempDir)) {
return;
}
try (Stream<Path> pathStream = Files.walk(tempDir)) {
pathStream.sorted(Comparator.reverseOrder()).forEach(path -> {
try {
Files.deleteIfExists(path);
} catch (IOException ignored) {
// 导入临时文件清理失败不影响主流程返回。
}
});
} catch (IOException ignored) {
// 导入临时目录清理失败不影响主流程返回。
}
}
}
}

View File

@@ -0,0 +1,28 @@
package com.njcn.gather.aireport.testdevice.component;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.util.ReflectionTestUtils;
import java.nio.file.Files;
import java.nio.file.Path;
public class TestDeviceReportStorageServiceTest {
@Test
public void saveUsesTestDeviceReportDirectoryUnderFilesRoot() throws Exception {
Path filesRoot = Files.createTempDirectory("files-root");
TestDeviceReportStorageService service = new TestDeviceReportStorageService();
ReflectionTestUtils.setField(service, "filesPath", filesRoot.toString());
String storedPath = service.save(new MockMultipartFile("reportFile", "../report.pdf",
"application/pdf", "%PDF-1.4".getBytes("UTF-8")));
Path expectedRoot = filesRoot.resolve("test-device-report").toAbsolutePath().normalize();
Path actualPath = service.resolveDownloadPath(storedPath);
Assert.assertTrue(actualPath.startsWith(expectedRoot));
Assert.assertTrue(storedPath.endsWith("-report.pdf"));
Assert.assertTrue(Files.exists(actualPath));
}
}

View File

@@ -0,0 +1,45 @@
package com.njcn.gather.aireport.testdevice.controller;
import com.njcn.gather.aireport.testdevice.component.TestDeviceReportStorageService;
import com.njcn.gather.aireport.testdevice.pojo.po.TestDevicePO;
import com.njcn.gather.aireport.testdevice.service.TestDeviceService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.util.ReflectionTestUtils;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
class TestDeviceControllerTest {
private final TestDeviceService testDeviceService = Mockito.mock(TestDeviceService.class);
private final TestDeviceReportStorageService reportStorageService = Mockito.mock(TestDeviceReportStorageService.class);
@Test
void previewReportShouldReturnInlinePdfResponse() throws Exception {
TestDeviceController controller = new TestDeviceController(testDeviceService, reportStorageService);
TestDevicePO device = new TestDevicePO();
device.setId("device-1");
device.setValidityReport("20260626/report.pdf");
Path tempFile = Files.createTempFile("test-device-preview-", ".pdf");
Files.write(tempFile, "%PDF-1.4".getBytes(StandardCharsets.UTF_8));
Mockito.when(testDeviceService.requireNormal("device-1")).thenReturn(device);
Mockito.when(reportStorageService.resolveDownloadPath("20260626/report.pdf")).thenReturn(tempFile);
Mockito.when(reportStorageService.resolveDownloadFileName("20260626/report.pdf")).thenReturn("report.pdf");
@SuppressWarnings("unchecked")
ResponseEntity<InputStreamResource> response = (ResponseEntity<InputStreamResource>)
ReflectionTestUtils.invokeMethod(controller, "buildReportResponse", "device-1", true);
Assertions.assertNotNull(response);
Assertions.assertEquals(MediaType.APPLICATION_PDF, response.getHeaders().getContentType());
Assertions.assertEquals("inline; filename*=UTF-8''report.pdf",
response.getHeaders().getFirst(HttpHeaders.CONTENT_DISPOSITION));
}
}

View File

@@ -0,0 +1,31 @@
package com.njcn.gather.aireport.testdevice.mapper;
import org.apache.ibatis.annotations.Select;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Method;
import java.util.Arrays;
class TestDeviceMapperTest {
@Test
void selectQueriesShouldContainUpdateUserNameMapping() throws Exception {
assertSelectContainsUpdateUserName("selectDevicePage");
assertSelectContainsUpdateUserName("selectDeviceDetail");
}
private void assertSelectContainsUpdateUserName(String methodName) throws Exception {
Method method = Arrays.stream(TestDeviceMapper.class.getMethods())
.filter(item -> item.getName().equals(methodName))
.findFirst()
.orElseThrow(NoSuchMethodException::new);
Select select = method.getAnnotation(Select.class);
Assertions.assertNotNull(select);
String sql = String.join(" ", select.value());
Assertions.assertTrue(sql.contains("updateByName"),
methodName + " should select updateByName");
Assertions.assertTrue(sql.contains("d.update_by = updater.id"),
methodName + " should join update user");
}
}

View File

@@ -0,0 +1,161 @@
package com.njcn.gather.aireport.testdevice.service.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.gather.aireport.testdevice.component.TestDeviceReportStorageService;
import com.njcn.gather.aireport.testdevice.mapper.TestDeviceMapper;
import com.njcn.gather.aireport.testdevice.pojo.param.TestDeviceParam;
import com.njcn.gather.aireport.testdevice.pojo.po.TestDevicePO;
import com.njcn.gather.aireport.testdevice.pojo.vo.TestDeviceTypeNameVO;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.util.ReflectionTestUtils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.util.Collections;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
class TestDeviceServiceImplTest {
private final TestDeviceMapper testDeviceMapper = Mockito.mock(TestDeviceMapper.class);
private final TestDeviceReportStorageService reportStorageService = Mockito.mock(TestDeviceReportStorageService.class);
@Test
void addTestDeviceShouldRejectExistingDeletedNumber() {
TestableService service = buildService();
service.countResult = 1;
Mockito.when(testDeviceMapper.countNormalDeviceType("type-1")).thenReturn(1);
TestDeviceParam.AddParam param = new TestDeviceParam.AddParam();
param.setType("type-1");
param.setNo("TD-001");
param.setValidityPeriod("2026-06-25");
BusinessException exception = Assertions.assertThrows(BusinessException.class,
() -> service.addTestDevice(param, new MockMultipartFile("reportFile", "report.pdf",
"application/pdf", "%PDF-1.4".getBytes())));
Assertions.assertEquals("设备编号已存在", exception.getMessage());
Mockito.verifyNoInteractions(reportStorageService);
}
@Test
void updateTestDeviceShouldDeleteNewReportWhenUpdateReturnsFalse() {
TestableService service = buildService();
service.countResult = 0;
service.updateResult = false;
service.requiredDevice = buildDevice("device-1", "old/report.pdf");
Mockito.when(testDeviceMapper.countNormalDeviceType("type-1")).thenReturn(1);
Mockito.when(reportStorageService.save(Mockito.any())).thenReturn("new/report.pdf");
TestDeviceParam.UpdateParam param = new TestDeviceParam.UpdateParam();
param.setId("device-1");
param.setType("type-1");
param.setNo("TD-001");
param.setValidityPeriod("2026-06-25");
boolean result = service.updateTestDevice(param,
new MockMultipartFile("reportFile", "report.pdf", "application/pdf", "%PDF-1.4".getBytes()));
Assertions.assertFalse(result);
Mockito.verify(reportStorageService).deleteQuietly("new/report.pdf");
Mockito.verify(reportStorageService, Mockito.never()).deleteQuietly("old/report.pdf");
}
@Test
void importTestDevicesShouldRejectOversizedPdfInZip() throws Exception {
TestableService service = buildService();
Mockito.when(testDeviceMapper.selectNormalDeviceTypes()).thenReturn(Collections.singletonList(buildType("type-1", "示波器")));
BusinessException exception = Assertions.assertThrows(BusinessException.class,
() -> service.importTestDevices(buildExcelFile(), buildZipFile(10 * 1024 * 1024 + 1)));
Assertions.assertEquals("校准报告不能超过10MB", exception.getMessage());
}
private TestableService buildService() {
TestableService service = new TestableService(reportStorageService);
ReflectionTestUtils.setField(service, "baseMapper", testDeviceMapper);
return service;
}
private TestDevicePO buildDevice(String id, String reportPath) {
TestDevicePO device = new TestDevicePO();
device.setId(id);
device.setType("type-1");
device.setNo("TD-001");
device.setValidityPeriod(LocalDate.of(2026, 6, 25));
device.setValidityReport(reportPath);
return device;
}
private TestDeviceTypeNameVO buildType(String id, String name) {
TestDeviceTypeNameVO type = new TestDeviceTypeNameVO();
type.setId(id);
type.setName(name);
return type;
}
private MockMultipartFile buildExcelFile() throws IOException {
try (XSSFWorkbook workbook = new XSSFWorkbook();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
XSSFSheet sheet = workbook.createSheet("导入");
sheet.createRow(0).createCell(0).setCellValue("设备型号");
sheet.getRow(0).createCell(1).setCellValue("设备编号");
sheet.getRow(0).createCell(2).setCellValue("校准有效期");
sheet.getRow(0).createCell(3).setCellValue("设备状态");
sheet.getRow(0).createCell(4).setCellValue("校准报告文件名");
sheet.createRow(1).createCell(0).setCellValue("示波器");
sheet.getRow(1).createCell(1).setCellValue("TD-001");
sheet.getRow(1).createCell(2).setCellValue("2026-06-25");
sheet.getRow(1).createCell(3).setCellValue("在运");
sheet.getRow(1).createCell(4).setCellValue("report.pdf");
workbook.write(outputStream);
return new MockMultipartFile("file", "test-device.xlsx",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", outputStream.toByteArray());
}
}
private MockMultipartFile buildZipFile(int pdfSize) throws IOException {
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream)) {
zipOutputStream.putNextEntry(new ZipEntry("report.pdf"));
zipOutputStream.write(new byte[pdfSize]);
zipOutputStream.closeEntry();
zipOutputStream.finish();
return new MockMultipartFile("reportZip", "report.zip", "application/zip", outputStream.toByteArray());
}
}
private static class TestableService extends TestDeviceServiceImpl {
private int countResult;
private boolean updateResult = true;
private TestDevicePO requiredDevice;
private TestableService(TestDeviceReportStorageService reportStorageService) {
super(reportStorageService);
}
@Override
public int count(Wrapper<TestDevicePO> queryWrapper) {
return countResult;
}
@Override
public boolean updateById(TestDevicePO entity) {
return updateResult;
}
@Override
public TestDevicePO requireNormal(String id) {
return requiredDevice;
}
}
}