Commit 9be30d29 by 章家宝

feat:检测报告代码提交

1 parent 28179408
......@@ -2,9 +2,11 @@ package com.glsx.usedcar.web.rest.inspect;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.glsx.usedcar.enums.inspect.InspectionPlatTypeEnum;
import com.glsx.usedcar.module.inspect.entity.InspectionReport;
import com.glsx.usedcar.module.inspect.service.InspectionReportService;
import com.glsx.usedcar.module.inspect.vo.*;
import com.glsx.usedcar.module.security.entity.User;
import com.glsx.usedcar.resp.BaseResp;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
......@@ -13,114 +15,132 @@ import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.summerframework.core.exception.BusinessCodeException;
import org.summerframework.orm.paging.Pagination;
@Slf4j
@Tag(name = "检测报告接口", description = "检测报告的增删改查操作")
@Tag(name = "检测报告接口", description = "检测报告的增删改查、绑定解绑操作")
@RestController
@RequiredArgsConstructor
@RequestMapping("/rest/inspect/report")
public class InspectionReportController {
private final InspectionReportService inspectionReportService;
@Operation(summary = "编辑检测报告", description = "编辑检测报告信息")
@Operation(summary = "编辑检测报告", description = "编辑检测报告基础信息(评分、报告编号等,绑定状态需走绑定接口)")
@PostMapping("/update")
public BaseResp<Void> update(@Valid @RequestBody InspectionReportUpdateVO vo) {
log.info("编辑检测报告请求: {}", JSON.toJSONString(vo));
public BaseResp<Void> update(@Valid @RequestBody InspectionReportUpdateVO vo, Authentication authentication) {
log.info("【接口请求】编辑检测报告,操作人={},参数={}", getUserName(authentication), JSON.toJSONString(vo));
try {
inspectionReportService.updateInspectionReport(vo);
User user = (User) authentication.getPrincipal();
inspectionReportService.updateInspectionReport(vo, (long)user.getUserId(), user.getUserName(), InspectionPlatTypeEnum.BACKEND.getCode());
return BaseResp.success();
} catch (BusinessCodeException be) {
log.error("编辑检测报告失败!业务异常!", be);
return BaseResp.fail(StrUtil.toString(be.getCode()), StrUtil.toString(be.getMessage()));
log.error("【接口响应】编辑检测报告失败!操作人={},业务异常!", getUserName(authentication), be);
return BaseResp.fail(StrUtil.toString(be.getCode()), be.getMessage());
} catch (Exception e) {
log.error("编辑检测报告失败!系统异常!", e);
log.error("【接口响应】编辑检测报告失败!操作人={},系统异常!", getUserName(authentication), e);
return BaseResp.fail("系统异常: " + e.getMessage());
}
return BaseResp.success();
}
@Operation(summary = "删除检测报告", description = "逻辑删除检测报告")
@PostMapping("/delete/{id}")
@Operation(summary = "删除检测报告", description = "逻辑删除检测报告(已绑定的报告不允许删除)")
@GetMapping("/delete/{id}")
public BaseResp<Void> delete(
@Parameter(description = "检测报告ID", required = true)
@PathVariable("id") Long id) {
log.info("删除检测报告请求: ID={}", id);
@Parameter(description = "检测报告ID", required = true) @PathVariable("id") Long id,
Authentication authentication) {
log.info("【接口请求】删除检测报告,操作人={},报告ID={}", getUserName(authentication), id);
try {
inspectionReportService.deleteInspectionReport(id);
User user = (User) authentication.getPrincipal();
inspectionReportService.deleteInspectionReport(id, (long)user.getUserId(), user.getUserName(), InspectionPlatTypeEnum.BACKEND.getCode());
return BaseResp.success();
} catch (BusinessCodeException be) {
log.error("删除检测报告失败!业务异常!", be);
return BaseResp.fail(StrUtil.toString(be.getCode()), StrUtil.toString(be.getMessage()));
log.error("【接口响应】删除检测报告失败!操作人={},业务异常!", getUserName(authentication), be);
return BaseResp.fail(StrUtil.toString(be.getCode()), be.getMessage());
} catch (Exception e) {
log.error("删除检测报告失败!系统异常!", e);
log.error("【接口响应】删除检测报告失败!操作人={},系统异常!", getUserName(authentication), e);
return BaseResp.fail("系统异常: " + e.getMessage());
}
return BaseResp.success();
}
@Operation(summary = "分页查询检测报告", description = "分页查询检测报告列表")
@Operation(summary = "分页查询检测报告", description = "支持关键词模糊查询(报告编号、工单号、VIN等)")
@PostMapping("/page")
public BaseResp<Page<InspectionReportRespVO>> pageList(@Valid @RequestBody Pagination<InspectionReport> pagination) {
log.info("分页查询检测报告请求: offset={}, limit={}", pagination.getOffset(), pagination.getLimit());
public Page<InspectionReportRespVO> pageList(@Valid @RequestBody Pagination<InspectionReport> pagination, Authentication authentication) {
log.info("【接口请求】分页查询检测报告,操作人={},页码={},条数={}", getUserName(authentication), pagination.getOffset(), pagination.getLimit());
try {
Page<InspectionReportRespVO> result = inspectionReportService.pageList(pagination);
return BaseResp.success(result);
return result;
} catch (Exception e) {
log.error("分页查询检测报告失败!系统异常!", e);
return BaseResp.fail("系统异常: " + e.getMessage());
log.error("【接口响应】分页查询检测报告失败!操作人={},系统异常!", getUserName(authentication), e);
return null;
}
}
@Operation(summary = "获取检测报告详情", description = "根据ID获取检测报告完整信息")
@PostMapping("/detail/{id}")
@Operation(summary = "获取检测报告详情", description = "根据ID获取检测报告完整信息(含关联工单、车辆信息)")
@GetMapping("/detail/{id}")
public BaseResp<InspectionReportDetailRespVO> detail(
@Parameter(description = "检测报告ID", required = true)
@PathVariable("id") Long id) {
log.info("获取检测报告详情请求: ID={}", id);
@Parameter(description = "检测报告ID", required = true) @PathVariable("id") Long id,
Authentication authentication) {
log.info("【接口请求】获取检测报告详情,操作人={},报告ID={}", getUserName(authentication), id);
try {
InspectionReportDetailRespVO result = inspectionReportService.detail(id);
return BaseResp.success(result);
} catch (BusinessCodeException be) {
log.error("获取检测报告详情失败!业务异常!", be);
return BaseResp.fail(StrUtil.toString(be.getCode()), StrUtil.toString(be.getMessage()));
log.error("【接口响应】获取检测报告详情失败!操作人={},业务异常!", getUserName(authentication), be);
return BaseResp.fail(StrUtil.toString(be.getCode()), be.getMessage());
} catch (Exception e) {
log.error("获取检测报告详情失败!系统异常!", e);
log.error("【接口响应】获取检测报告详情失败!操作人={},系统异常!", getUserName(authentication), e);
return BaseResp.fail("系统异常: " + e.getMessage());
}
}
@Operation(summary = "检测报告绑定", description = "检测报告绑定检测工单/车辆/检测项")
@PostMapping("/bind/{id}")
public BaseResp<Void> bind(@Parameter(description = "检测报告ID", required = true)
@PathVariable("id") Long id) {
log.info("检测报告绑定请求: {}", id);
@Operation(summary = "检测报告绑定", description = "绑定报告到车辆(同一车辆仅允许绑定一个报告)")
@GetMapping("/bind/{id}")
public BaseResp<Void> bind(
@Parameter(description = "检测报告ID", required = true) @PathVariable("id") Long id,
Authentication authentication) {
log.info("【接口请求】检测报告绑定,操作人={},报告ID={}", getUserName(authentication), id);
try {
inspectionReportService.bindInspectionReport(id);
User user = (User) authentication.getPrincipal();
inspectionReportService.bindInspectionReport(id, (long)user.getUserId(), user.getUserName(), InspectionPlatTypeEnum.BACKEND.getCode());
return BaseResp.success();
} catch (BusinessCodeException be) {
log.error("检测报告绑定失败!业务异常!", be);
return BaseResp.fail(StrUtil.toString(be.getCode()), StrUtil.toString(be.getMessage()));
log.error("【接口响应】检测报告绑定失败!操作人={},业务异常!", getUserName(authentication), be);
return BaseResp.fail(StrUtil.toString(be.getCode()), be.getMessage());
} catch (Exception e) {
log.error("检测报告绑定失败!系统异常!", e);
log.error("【接口响应】检测报告绑定失败!操作人={},系统异常!", getUserName(authentication), e);
return BaseResp.fail("系统异常: " + e.getMessage());
}
return BaseResp.success();
}
@Operation(summary = "检测报告解绑", description = "检测报告解绑检测工单/车辆/检测项")
@PostMapping("/unbind/{id}")
public BaseResp<Void> unbind(@Parameter(description = "检测报告ID", required = true)
@PathVariable("id") Long id) {
log.info("检测报告解绑请求: {}", id);
@Operation(summary = "检测报告解绑", description = "解除报告与车辆的绑定关系")
@GetMapping("/unbind/{id}")
public BaseResp<Void> unbind(
@Parameter(description = "检测报告ID", required = true) @PathVariable("id") Long id,
Authentication authentication) {
log.info("【接口请求】检测报告解绑,操作人={},报告ID={}", getUserName(authentication), id);
try {
inspectionReportService.unbindInspectionReport(id);
User user = (User) authentication.getPrincipal();
inspectionReportService.unbindInspectionReport(id, (long)user.getUserId(), user.getUserName(), InspectionPlatTypeEnum.BACKEND.getCode());
return BaseResp.success();
} catch (BusinessCodeException be) {
log.error("检测报告解绑失败!业务异常!", be);
return BaseResp.fail(StrUtil.toString(be.getCode()), StrUtil.toString(be.getMessage()));
log.error("【接口响应】检测报告解绑失败!操作人={},业务异常!", getUserName(authentication), be);
return BaseResp.fail(StrUtil.toString(be.getCode()), be.getMessage());
} catch (Exception e) {
log.error("检测报告解绑失败!系统异常!", e);
log.error("【接口响应】检测报告解绑失败!操作人={},系统异常!", getUserName(authentication), e);
return BaseResp.fail("系统异常: " + e.getMessage());
}
return BaseResp.success();
}
/**
* 安全获取操作人姓名(避免空指针)
*/
private String getUserName(Authentication authentication) {
try {
return authentication != null ? ((User) authentication.getPrincipal()).getUserName() : "未知用户";
} catch (Exception e) {
return "未知用户";
}
}
}
\ No newline at end of file
......@@ -97,14 +97,14 @@ public class InspectionWorkOrderController {
@Operation(summary = "分页检测工单", description = "分页查询检测工单列表")
@PostMapping("/page")
public BaseResp<Page<InspectionWORespVO>> pageList(@Valid @RequestBody Pagination<InspectionWorkOrder> pagination) {
public Page<InspectionWORespVO> pageList(@Valid @RequestBody Pagination<InspectionWorkOrder> pagination) {
log.info("分页查询检测工单请求: offset={}, limit={}", pagination.getOffset(), pagination.getLimit());
try {
Page<InspectionWORespVO> result = inspectionWorkOrderService.pageList(pagination);
return BaseResp.success(result);
return result;
} catch (Exception e) {
log.error("分页查询检测工单失败!系统异常!", e);
return BaseResp.fail("系统异常: " + e.getMessage());
return null;
}
}
......
package com.glsx.usedcar.converts;
import com.glsx.usedcar.module.inspect.entity.InspectionReportOpLog;
import com.glsx.usedcar.module.inspect.vo.InspectionReportOpLogRespVO;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import java.util.List;
/**
* 检测报告日志实体转VO转换器
*/
@Mapper(componentModel = "spring")
public interface InspectionReportOpLogConverter {
InspectionReportOpLogConverter INSTANCE = Mappers.getMapper(InspectionReportOpLogConverter.class);
/**
* 单条日志实体转VO
*/
InspectionReportOpLogRespVO inspectionReportOpLogMapRespVO(InspectionReportOpLog opLog);
/**
* 日志列表实体转VO列表
*/
List<InspectionReportOpLogRespVO> inspectionReportOpLogMapRespVO(List<InspectionReportOpLog> opLogList);
}
\ No newline at end of file
......@@ -74,4 +74,10 @@ public interface InspectionReportRepository extends BaseRepository<InspectionRep
@Override
@EntityGraph(attributePaths = {"vehicle", "workOrder"})
Page<InspectionReport> findAll(Specification<InspectionReport> spec, Pageable pageable);
List<InspectionReport> findByVehicleAndBindStatusAndDeleteFlag(Vehicle vehicle, int status, String deleteFlag);
@EntityGraph(attributePaths = {"vehicle", "workOrder"})
Optional<InspectionReport> findByIdAndDeleteFlag(Long id, String deleteFlag);
}
\ No newline at end of file
......@@ -2,9 +2,7 @@ package com.glsx.usedcar.module.inspect.entity;
import com.fasterxml.jackson.annotation.JsonView;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import jakarta.validation.constraints.*;
import lombok.*;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
......@@ -77,6 +75,15 @@ public class InspectionReportOpLog extends AuditingEntity implements Serializabl
@Column(name = "operator_id", nullable = false)
private Long operatorId;
/**
* 平台标识:0 检测师 1 后台(修正:原注释错误标注为操作类型)
*/
@JsonView(value = InspectionWorkOrderOpLog.Summary.class)
@NotNull(groups = {CreateValidGroup.class, UpdateValidGroup.class})
@Column(name = "plate_type", nullable = false, columnDefinition = "tinyint(2)") // 对齐MySQL的tinyint(2)类型
private Integer plateType;
/**
* 操作人姓名
*/
......
......@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.glsx.usedcar.consts.common.SymbolConsts;
import com.glsx.usedcar.consts.inspect.JpaQueryConstants;
import com.glsx.usedcar.converts.InspectionReportConverter;
import com.glsx.usedcar.converts.InspectionReportOpLogConverter;
import com.glsx.usedcar.enums.common.DeleteFlag;
import com.glsx.usedcar.enums.inspect.InspectionReportOperationTypeEnum;
import com.glsx.usedcar.module.inspect.dao.InspectionReportOpLogRepository;
......@@ -17,7 +18,6 @@ import com.glsx.usedcar.module.vehicle.entity.*;
import com.glsx.usedcar.util.RedisCacheUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
......@@ -35,10 +35,11 @@ import java.util.concurrent.TimeUnit;
/**
* 检测报告服务(含操作日志保存)
* 核心功能:增删改查、绑定/解绑、日志记录
*/
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class InspectionReportService {
private final InspectionReportRepository inspectionReportRepository;
......@@ -46,179 +47,203 @@ public class InspectionReportService {
private final ObjectMapper objectMapper = new ObjectMapper();
private final RedisCacheUtil redisCacheUtil;
private final InspectionReportConverter inspectionReportConverter;
private final InspectionReportOpLogConverter inspectionReportOpLogConverter;
private final VehicleDao vehicleDao;
/**
* 获取当前操作人ID(示例:需替换为项目真实的用户上下文,如UserContext.getUserId())
*/
private Long getCurrentOperatorId() {
return 10001L;
}
// ======================== 日志保存方法(核心,接收真实操作人) ========================
/**
* 获取当前操作人姓名(示例:需替换为项目真实的用户上下文)
* 保存检测报告操作日志
* 注:createBy/createTime等审计字段继承自AuditingEntity,无法通过Builder赋值,需手动set
*
* @param report 关联的检测报告
* @param operationType 操作类型(枚举值)
* @param originalData 操作前数据(JSON/文本格式)
* @param targetData 操作后数据(JSON/文本格式)
* @param operationContent 操作内容描述
* @param operatorId 真实操作人ID(从登录信息获取)
* @param operatorName 真实操作人姓名(从登录信息获取)
* @param platType 平台标识(0=检测师/1=后台)
*/
private String getCurrentOperatorName() {
return "系统管理员";
}
@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
private void saveReportOpLog(InspectionReport report,
Integer operationType,
String originalData,
String targetData,
String operationContent) {
String operationContent,
Long operatorId,
String operatorName,
Integer platType) {
try {
// 1. 核心参数校验
if (operatorId == null || StrUtil.isBlank(operatorName) || platType == null) {
log.warn("【报告日志】保存失败:操作人信息/平台标识为空!报告编号={}", report.getReportNo());
return;
}
if (report == null || StrUtil.isBlank(report.getReportNo())) {
log.warn("【报告日志】保存失败:检测报告信息为空!");
return;
}
// 2. 统一时间变量
LocalDateTime now = LocalDateTime.now();
// 3. 构建日志实体(空值处理)
InspectionReportOpLog opLog = InspectionReportOpLog.builder()
.reportInnerId(report.getId())
.reportNo(report.getReportNo())
.operatorId(getCurrentOperatorId())
.operatorName(getCurrentOperatorName())
.operatorId(operatorId) // 真实操作人ID
.operatorName(operatorName) // 真实操作人姓名
.plateType(platType)
.operationType(operationType)
.originalData(originalData)
.targetData(targetData)
.operationContent(operationContent)
.operationTime(LocalDateTime.now())
.originalData(StrUtil.isBlank(originalData) ? "" : originalData)
.targetData(StrUtil.isBlank(targetData) ? "" : targetData)
.operationContent(StrUtil.isBlank(operationContent) ? "" : operationContent)
.operationTime(now)
.deleteFlag(DeleteFlag.NOT_DELETED.getCode())
.build();
// 4. 手动设置审计字段(记录真实操作人)
opLog.setCreateBy(operatorName);
opLog.setCreateTime(now);
opLog.setUpdateBy(operatorName);
opLog.setUpdateTime(now);
// 5. 保存日志
inspectionReportOpLogRepository.save(opLog);
log.info("检测报告操作日志保存成功: 报告编号={}, 操作类型={}", report.getReportNo(), operationType);
log.info("【报告日志】保存成功: 报告编号={}, 操作人={}, 操作类型={}, 平台标识={}",
report.getReportNo(), operatorName, operationType, platType);
} catch (Exception e) {
log.error("检测报告操作日志保存失败: 报告编号={}", report.getReportNo(), e);
log.error("【报告日志】保存失败: 报告编号={}, 操作人={}", report.getReportNo(), operatorName, e);
}
}
// ======================== 核心业务方法(接收操作人参数) ========================
/**
* 新增检测报告(关联工单+车辆)
*
* @param wo 检测工单
* @param vehicle 车辆
* @param operatorId 操作人ID
* @param operatorName 操作人姓名
* @param platType 平台标识
*/
@Transactional(rollbackFor = Exception.class)
public void addInspectionReport(InspectionWorkOrder wo, Vehicle vehicle) {
public void addInspectionReport(InspectionWorkOrder wo, Vehicle vehicle, Long operatorId, String operatorName, Integer platType) {
// 1. 生成唯一报告编号
String reportNo = genReportNo();
log.info("【报告新增】操作人={},开始生成报告,编号={},关联工单号={}", operatorName, reportNo, wo.getWoId());
// 2. 构建报告实体
InspectionReport report = InspectionReport.builder()
.reportNo(reportNo)
.woId(wo.getWoId())
.vehicle(vehicle)
.workOrder(wo)
.score(BigDecimal.ZERO)
.scoreLevel(" ")
.bindStatus(2)
.h5Url(" ")
.scoreLevel("")
.bindStatus(2) // 初始未绑定
.h5Url("")
.deleteFlag(DeleteFlag.NOT_DELETED.getCode())
.build();
inspectionReportRepository.save(report);
// 3. 保存新增日志(originalData为空,targetData为新增的报告数据)
// 3. 保存新增日志(记录真实操作人)
String targetData = "";
try {
targetData = objectMapper.writeValueAsString(report);
} catch (JsonProcessingException e) {
log.error("报告数据转JSON失败", e);
log.error("【报告新增】操作人={},数据转JSON失败", operatorName, e);
}
String operationContent = String.format("新增检测报告,报告编号:%s,关联工单号:%s", report.getReportNo(), report.getWoId());
saveReportOpLog(report, InspectionReportOperationTypeEnum.CREATE_REPORT.getCode(), "", targetData, operationContent);
String operationContent = String.format("新增检测报告,报告编号:%s,关联工单号:%s,关联车辆VIN:%s",
report.getReportNo(), report.getWoId(), vehicle.getBaseInfo().getVin());
saveReportOpLog(report, InspectionReportOperationTypeEnum.CREATE_REPORT.getCode(),
"", targetData, operationContent, operatorId, operatorName, platType);
log.info("检测报告新增成功: ID={}, 报告编号={}, 关联工单号={}", report.getId(), report.getReportNo(), report.getWoId());
log.info("【报告新增】操作人={},成功: ID={}, 报告编号={}, 关联工单号={}",
operatorName, report.getId(), report.getReportNo(), report.getWoId());
}
private String genReportNo() {
try {
// 1. 按天生成Redis Key(yyyyMMdd),2天过期(合理过期,避免堆积)
String dateStr = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
String redisKey = "inspection:report:seq:" + dateStr;
// 2. Redis原子自增(不存在则初始化为1,设置2天过期)
Long seqNum;
if (redisCacheUtil.existsKey(redisKey)) {
seqNum = redisCacheUtil.increment(redisKey);
} else {
redisCacheUtil.setCacheWithExpire(redisKey, 1L, 2, TimeUnit.DAYS);
seqNum = 1L;
}
// 3. 4位流水号上限校验
if (seqNum > 9999) {
throw new RuntimeException("当日工单单号流水号已达上限(9999),请次日再试");
}
// 4. 按要求拼接单号:BG + 日期 + 4位流水号
return String.format("BG%s%s", dateStr, String.format("%04d", seqNum));
} catch (Exception e) {
log.error("生成工单单号失败", e);
throw new RuntimeException("生成工单单号失败", e);
}
}
/**
* 编辑检测报告(接收操作人参数)
*/
@Transactional(rollbackFor = Exception.class)
public void updateInspectionReport(InspectionReportUpdateVO updateVO) {
public void updateInspectionReport(InspectionReportUpdateVO updateVO, Long operatorId, String operatorName, Integer platType) {
Long id = updateVO.getId();
log.info("【报告编辑】操作人={},开始处理,报告ID={}", operatorName, id);
// 1. 查找报告并校验
InspectionReport report = inspectionReportRepository.findById(id)
.orElseThrow(() -> new BusinessCodeException(ErrorCodeEnum.DATA_NOT_EXIST, "检测报告不存在"));
.orElseThrow(() -> new BusinessCodeException(ErrorCodeEnum.DATA_NOT_EXIST, "检测报告不存在,ID:" + id));
// 2. 保存修改前的原始数据(用于日志)
// 2. 保存修改前的原始数据
String originalData = "";
try {
originalData = objectMapper.writeValueAsString(report);
} catch (JsonProcessingException e) {
log.error("报告原始数据转JSON失败", e);
log.error("【报告编辑】操作人={},原始数据转JSON失败", operatorName, e);
}
// 3. 校验并更新报告信息
Integer operationType = InspectionReportOperationTypeEnum.OTHER_UPDATE.getCode(); // 默认其他修改
Integer operationType = InspectionReportOperationTypeEnum.OTHER_UPDATE.getCode();
StringBuilder operationContent = new StringBuilder("修改检测报告:");
// 逐个字段更新,并记录修改内容
if (updateVO.getReportNo() != null && !Objects.equals(report.getReportNo(), updateVO.getReportNo())) {
Optional<InspectionReport> existReport = inspectionReportRepository.findByReportNo(updateVO.getReportNo());
if (existReport.isPresent() && !Objects.equals(existReport.get().getId(), id)) {
throw new BusinessCodeException(ErrorCodeEnum.DATA_ALREADY_EXISTS, "报告编号已存在:" + updateVO.getReportNo());
}
operationContent.append(String.format("报告编号从%s改为%s;", report.getReportNo(), updateVO.getReportNo()));
report.setReportNo(updateVO.getReportNo());
// 评分+评分级别更新
boolean isScoreUpdate = false;
if (updateVO.getScore() != null && !Objects.equals(report.getScore(), updateVO.getScore())) {
operationContent.append(String.format("评分从[%s]改为[%s];", report.getScore(), updateVO.getScore()));
report.setScore(updateVO.getScore());
isScoreUpdate = true;
}
if (updateVO.getScore() != null || updateVO.getScoreLevel() != null) {
if (updateVO.getScore() != null && !Objects.equals(report.getScore(), updateVO.getScore())) {
operationContent.append(String.format("评分从%s改为%s;", report.getScore(), updateVO.getScore()));
}
if (updateVO.getScoreLevel() != null && !Objects.equals(report.getScoreLevel(), updateVO.getScoreLevel())) {
operationContent.append(String.format("评分级别从%s改为%s;", report.getScoreLevel(), updateVO.getScoreLevel()));
}
operationType = InspectionReportOperationTypeEnum.UPDATE_SCORE_LEVEL.getCode();
report.setScore(updateVO.getScore() != null ? updateVO.getScore() : report.getScore());
report.setScoreLevel(updateVO.getScoreLevel() != null ? updateVO.getScoreLevel() : report.getScoreLevel());
if (updateVO.getScoreLevel() != null && !Objects.equals(report.getScoreLevel(), updateVO.getScoreLevel())) {
operationContent.append(String.format("评分级别从[%s]改为[%s];", report.getScoreLevel(), updateVO.getScoreLevel()));
report.setScoreLevel(updateVO.getScoreLevel());
isScoreUpdate = true;
}
if (updateVO.getBindStatus() != null && !Objects.equals(report.getBindStatus(), updateVO.getBindStatus())) {
operationContent.append(String.format("绑定状态从%s改为%s;", report.getBindStatus(), updateVO.getBindStatus()));
if (updateVO.getBindStatus() != 1 && updateVO.getBindStatus() != 2) {
throw new BusinessCodeException(ErrorCodeEnum.PARAM_ERROR, "无效的绑定状态:" + updateVO.getBindStatus());
}
report.setBindStatus(updateVO.getBindStatus());
operationType = InspectionReportOperationTypeEnum.UPDATE_BIND_STATUS.getCode();
if (isScoreUpdate) {
operationType = InspectionReportOperationTypeEnum.UPDATE_SCORE_LEVEL.getCode();
}
// 其他字段更新逻辑(省略,可按需补充)
if (updateVO.getWoId() != null) {
// 其他字段更新
if (updateVO.getWoId() != null && !Objects.equals(report.getWoId(), updateVO.getWoId())) {
operationContent.append(String.format("关联工单号从[%s]改为[%s];", report.getWoId(), updateVO.getWoId()));
report.setWoId(updateVO.getWoId());
}
if (updateVO.getH5Url() != null) {
if (updateVO.getH5Url() != null && !Objects.equals(report.getH5Url(), updateVO.getH5Url())) {
operationContent.append(String.format("H5链接从[%s]改为[%s];", report.getH5Url(), updateVO.getH5Url()));
report.setH5Url(updateVO.getH5Url());
}
// 4. 保存修改后的报告
inspectionReportRepository.save(report);
// 5. 保存修改日志
// 5. 保存修改日志(记录真实操作人)
String targetData = "";
try {
targetData = objectMapper.writeValueAsString(report);
} catch (JsonProcessingException e) {
log.error("报告修改后数据转JSON失败", e);
log.error("【报告编辑】操作人={},修改后数据转JSON失败", operatorName, e);
}
saveReportOpLog(report, operationType, originalData, targetData, operationContent.toString());
saveReportOpLog(report, operationType, originalData, targetData, operationContent.toString(),
operatorId, operatorName, platType);
log.info("检测报告修改成功: ID={}, 报告编号={}", report.getId(), report.getReportNo());
log.info("【报告编辑】操作人={},成功: ID={}, 报告编号={}", operatorName, report.getId(), report.getReportNo());
}
/**
* 逻辑删除检测报告(接收操作人参数)
*/
@Transactional(rollbackFor = Exception.class)
public void deleteInspectionReport(Long id) {
public void deleteInspectionReport(Long id, Long operatorId, String operatorName, Integer platType) {
log.info("【报告删除】操作人={},开始处理,报告ID={}", operatorName, id);
// 1. 查找报告并校验
InspectionReport report = inspectionReportRepository.findById(id)
.orElseThrow(() -> new BusinessCodeException(ErrorCodeEnum.DATA_NOT_EXIST, "检测报告不存在"));
.orElseThrow(() -> new BusinessCodeException(ErrorCodeEnum.DATA_NOT_EXIST, "检测报告不存在,ID:" + id));
// 已绑定的报告不允许删除
if (Objects.equals(report.getBindStatus(), 1)) {
throw new BusinessCodeException(ErrorCodeEnum.OPERATION_ERROR, "已绑定的检测报告不允许删除");
throw new BusinessCodeException(ErrorCodeEnum.OPERATION_ERROR, "已绑定的检测报告不允许删除,报告编号:" + report.getReportNo());
}
// 2. 保存删除前的原始数据
......@@ -226,41 +251,180 @@ public class InspectionReportService {
try {
originalData = objectMapper.writeValueAsString(report);
} catch (JsonProcessingException e) {
log.error("报告删除前数据转JSON失败", e);
log.error("【报告删除】操作人={},数据转JSON失败", operatorName, e);
}
// 3. 逻辑删除报告
report.setDeleteFlag(DeleteFlag.DELETED.getCode());
inspectionReportRepository.save(report);
// 4. 保存删除日志(targetData为空,originalData为删除前数据)
// 4. 保存删除日志(记录真实操作人)
String operationContent = String.format("逻辑删除检测报告,报告编号:%s,删除原因:业务删除", report.getReportNo());
saveReportOpLog(report, InspectionReportOperationTypeEnum.DELETE_REPORT.getCode(), originalData, "", operationContent);
saveReportOpLog(report, InspectionReportOperationTypeEnum.DELETE_REPORT.getCode(),
originalData, "", operationContent, operatorId, operatorName, platType);
log.info("检测报告删除成功: ID={}, 报告编号={}", report.getId(), report.getReportNo());
log.info("【报告删除】操作人={},成功: ID={}, 报告编号={}", operatorName, report.getId(), report.getReportNo());
}
/**
* 绑定检测报告(接收操作人参数,核心规则:同一车辆仅绑定一个报告)
*/
@Transactional(rollbackFor = Exception.class)
public void bindInspectionReport(Long id, Long operatorId, String operatorName, Integer platType) {
log.info("【报告绑定】操作人={},开始处理,报告ID={}", operatorName, id);
// 1. 查找报告并校验
InspectionReport report = inspectionReportRepository.findById(id)
.orElseThrow(() -> new BusinessCodeException(ErrorCodeEnum.DATA_NOT_EXIST, "检测报告不存在,ID:" + id));
// 已绑定则直接返回
if (Objects.equals(report.getBindStatus(), 1)) {
log.info("【报告绑定】操作人={},报告已绑定,无需重复操作,报告编号={}", operatorName, report.getReportNo());
return;
}
// 2. 检查该车辆是否已绑定其他报告
Vehicle vehicle = report.getVehicle();
List<InspectionReport> bindedReports = inspectionReportRepository.findByVehicleAndBindStatusAndDeleteFlag(
vehicle, 1, DeleteFlag.NOT_DELETED.getCode()
);
if (!bindedReports.isEmpty()) {
String bindedReportNos = bindedReports.stream().map(InspectionReport::getReportNo).reduce((a, b) -> a + "," + b).get();
throw new BusinessCodeException(ErrorCodeEnum.OPERATION_ERROR,
String.format("该车辆已绑定其他检测报告(报告编号:%s),不允许重复绑定", bindedReportNos));
}
// 3. 保存绑定前的原始数据
String originalData = "";
try {
originalData = objectMapper.writeValueAsString(report);
} catch (JsonProcessingException e) {
log.error("【报告绑定】操作人={},数据转JSON失败", operatorName, e);
}
// 4. 修改绑定状态为已绑定
report.setBindStatus(1);
inspectionReportRepository.save(report);
// 5. 保存绑定日志(记录真实操作人)
String targetData = "";
try {
targetData = objectMapper.writeValueAsString(report);
} catch (JsonProcessingException e) {
log.error("【报告绑定】操作人={},修改后数据转JSON失败", operatorName, e);
}
String operationContent = String.format("绑定检测报告,报告编号:%s,关联车辆VIN:%s",
report.getReportNo(), vehicle.getBaseInfo().getVin());
saveReportOpLog(report, InspectionReportOperationTypeEnum.UPDATE_BIND_STATUS.getCode(),
originalData, targetData, operationContent, operatorId, operatorName, platType);
log.info("【报告绑定】操作人={},成功: ID={}, 报告编号={}, 车辆VIN={}",
operatorName, report.getId(), report.getReportNo(), vehicle.getBaseInfo().getVin());
}
/**
* 解绑检测报告(接收操作人参数)
*/
@Transactional(rollbackFor = Exception.class)
public void unbindInspectionReport(Long id, Long operatorId, String operatorName, Integer platType) {
log.info("【报告解绑】操作人={},开始处理,报告ID={}", operatorName, id);
// 1. 查找报告并校验
InspectionReport report = inspectionReportRepository.findById(id)
.orElseThrow(() -> new BusinessCodeException(ErrorCodeEnum.DATA_NOT_EXIST, "检测报告不存在,ID:" + id));
// 未绑定则直接返回
if (Objects.equals(report.getBindStatus(), 2)) {
log.info("【报告解绑】操作人={},报告已解绑,无需重复操作,报告编号={}", operatorName, report.getReportNo());
return;
}
// 2. 保存解绑前的原始数据
String originalData = "";
try {
originalData = objectMapper.writeValueAsString(report);
} catch (JsonProcessingException e) {
log.error("【报告解绑】操作人={},数据转JSON失败", operatorName, e);
}
// 3. 修改绑定状态为未绑定
report.setBindStatus(2);
inspectionReportRepository.save(report);
// 4. 保存解绑日志(记录真实操作人)
String targetData = "";
try {
targetData = objectMapper.writeValueAsString(report);
} catch (JsonProcessingException e) {
log.error("【报告解绑】操作人={},修改后数据转JSON失败", operatorName, e);
}
String operationContent = String.format("解绑检测报告,报告编号:%s,关联车辆VIN:%s",
report.getReportNo(), report.getVehicle().getBaseInfo().getVin());
saveReportOpLog(report, InspectionReportOperationTypeEnum.UPDATE_BIND_STATUS.getCode(),
originalData, targetData, operationContent, operatorId, operatorName, platType);
log.info("【报告解绑】操作人={},成功: ID={}, 报告编号={}", operatorName, report.getId(), report.getReportNo());
}
// ======================== 其他方法(无修改) ========================
/**
* 生成唯一报告编号(BG + 日期 + 4位流水号)
*/
private String genReportNo() {
try {
String dateStr = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
String redisKey = "inspection:report:seq:" + dateStr;
Long seqNum = redisCacheUtil.increment(redisKey);
if (seqNum == null) {
redisCacheUtil.setCacheWithExpire(redisKey, 1L, 2, TimeUnit.DAYS);
seqNum = 1L;
}
if (seqNum > 9999) {
throw new BusinessCodeException(ErrorCodeEnum.SYSTEM_ERROR, "当日报告编号流水号已达上限(9999),请次日再试");
}
return String.format("BG%s%04d", dateStr, seqNum);
} catch (BusinessCodeException e) {
throw e;
} catch (Exception e) {
log.error("【报告编号】生成失败", e);
throw new BusinessCodeException(ErrorCodeEnum.SYSTEM_ERROR, "生成检测报告编号失败");
}
}
public InspectionReport getByReportNo(String reportNo) {
log.info("【报告查询】按编号查询,报告编号={}", reportNo);
return inspectionReportRepository.findByReportNo(reportNo)
.orElseThrow(() -> new BusinessCodeException(ErrorCodeEnum.DATA_NOT_EXIST, "检测报告不存在:" + reportNo));
}
public List<InspectionReport> listByVehicleId(Integer vehicleId) {
Vehicle vehicle = vehicleDao.findById(vehicleId).orElseThrow();
log.info("【报告查询】按车辆ID查询,车辆ID={}", vehicleId);
Vehicle vehicle = vehicleDao.findById(vehicleId)
.orElseThrow(() -> new BusinessCodeException(ErrorCodeEnum.DATA_NOT_EXIST, "车辆不存在,ID:" + vehicleId));
return inspectionReportRepository.findByVehicleAndDeleteFlag(vehicle, DeleteFlag.NOT_DELETED.getCode());
}
public List<InspectionReport> listByWoId(String woId) {
log.info("【报告查询】按工单号查询,工单号={}", woId);
return inspectionReportRepository.findByWoId(woId);
}
public List<InspectionReport> listByBindStatus(Integer bindStatus) {
log.info("【报告查询】按绑定状态查询,状态={}", bindStatus);
if (bindStatus != 1 && bindStatus != 2) {
throw new BusinessCodeException(ErrorCodeEnum.PARAM_ERROR, "无效的绑定状态:" + bindStatus);
throw new BusinessCodeException(ErrorCodeEnum.PARAM_ERROR, "无效的绑定状态:" + bindStatus + "(仅支持1=已绑定/2=未绑定)");
}
return inspectionReportRepository.findByBindStatusAndDeleteFlag(bindStatus, DeleteFlag.NOT_DELETED.getCode());
}
/**
* 分页查询
*/
public Page<InspectionReportRespVO> pageList(Pagination<InspectionReport> pagination) {
// 1. 处理关键词模糊查询(复用工单查询的KEYWORD常量)
Object keyword = pagination.getFilterValueOrElseNull(JpaQueryConstants.Inspector.KEYWORD);
......@@ -293,15 +457,32 @@ public class InspectionReportService {
}
/**
* 获取检测报告详情(参考工单详情逻辑)
*/
public InspectionReportDetailRespVO detail(Long id) {
return null;
}
log.info("【报告详情】查询,报告ID={}", id);
public void bindInspectionReport(long id) {
// 1. 查询报告(带删除标记校验)
InspectionReport report = inspectionReportRepository.findByIdAndDeleteFlag(id, DeleteFlag.NOT_DELETED.getCode())
.orElse(null);
if (report == null) {
throw new BusinessCodeException(ErrorCodeEnum.PARAM_ERROR, "检测报告没有找到", id);
}
}
// 2. 转换为报告基础RespVO
InspectionReportRespVO reportRespVO = inspectionReportConverter.inspectionReportMapRespVO(report);
// 3. 查询该报告的操作日志
List<InspectionReportOpLog> logList = inspectionReportOpLogRepository.findByReportInnerIdAndDeleteFlag(
report.getId(), DeleteFlag.NOT_DELETED.getCode()
);
public void unbindInspectionReport(long id) {
// 4. 转换日志为日志RespVO列表
List<InspectionReportOpLogRespVO> reportOpLogRespVos = inspectionReportOpLogConverter.inspectionReportOpLogMapRespVO(logList);
// 5. 构建并返回详情VO
log.info("【报告详情】查询成功: ID={}, 报告编号={}", id, report.getReportNo());
return new InspectionReportDetailRespVO(reportRespVO, reportOpLogRespVos);
}
}
\ No newline at end of file
package com.glsx.usedcar.module.inspect.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.*;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "检测报告详情返回")
public class InspectionReportDetailRespVO {
@Schema(description = "报告ID")
private Long id;
@Schema(description = "关联工单ID")
private Long workOrderId;
@Schema(description = "检测结论")
private String conclusion;
@Schema(description = "报告信息")
private InspectionReportRespVO inspectionReportRespVO;
@Schema(description = "检测评分")
private Double score;
@Schema(description = "日志信息")
private List<InspectionReportOpLogRespVO> logList;
}
\ No newline at end of file
package com.glsx.usedcar.module.inspect.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@Schema(description = "检测报告日志信息")
public class InspectionReportOpLogRespVO {
/**
* 操作类型
* 1:创建报告;2:修改评分/级别;3:修改绑定状态;4:绑定报告;5:解绑报告;6:删除报告;7:其他修改
*/
@Schema(description = "操作类型 1:创建报告;2:修改评分/级别;3:修改绑定状态;4:绑定报告;5:解绑报告;6:删除报告;7:其他修改")
private Integer operationType;
/**
* 操作内容描述
*/
@Schema(description = "操作内容描述")
private String operationContent;
/**
* 操作时间
*/
@Schema(description = "操作时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime operationTime;
/**
* 操作描述
*/
@Schema(description = "操作描述")
private String description;
/**
* 操作人姓名
*/
@Schema(description = "操作人姓名")
private String operatorName;
}
\ No newline at end of file
......@@ -9,7 +9,7 @@ import java.math.BigDecimal;
@Data
@Schema(description = "检测报告分页返回")
public class InspectionReportRespVO {
@Schema(description = "报告ID", example = "10001")
@Schema(description = "报告ID")
private Long id;
@Schema(description = "报告编号(唯一)", example = "REPORT20260317001")
......
......@@ -20,10 +20,6 @@ public class InspectionReportUpdateVO implements Serializable {
@Schema(description = "ID", requiredMode = Schema.RequiredMode.NOT_REQUIRED, example = "1")
private Long id;
@Schema(description = "报告编号(唯一)", requiredMode = Schema.RequiredMode.NOT_REQUIRED, example = "REP20260312001")
@Size(max = 50, message = "报告编号长度不能超过50个字符")
private String reportNo;
@Schema(description = "关联工单号", requiredMode = Schema.RequiredMode.NOT_REQUIRED, example = "WO20260312001")
@Size(max = 50, message = "关联工单号长度不能超过50个字符")
private String woId;
......@@ -31,26 +27,6 @@ public class InspectionReportUpdateVO implements Serializable {
@Schema(description = "车辆ID", requiredMode = Schema.RequiredMode.NOT_REQUIRED, example = "1001")
private Integer vehicleId;
@Schema(description = "车型名称", requiredMode = Schema.RequiredMode.NOT_REQUIRED, example = "2023款 宝马3系 325Li M运动套装")
@Size(max = 128, message = "车型名称长度不能超过128个字符")
private String carTypeName;
@Schema(description = "车源号", requiredMode = Schema.RequiredMode.NOT_REQUIRED, example = "CS20260312001")
@Size(max = 64, message = "车源号长度不能超过64个字符")
private String carSourceNo;
@Schema(description = "车辆识别码(VIN码)", requiredMode = Schema.RequiredMode.NOT_REQUIRED, example = "LVGDS123456789012")
@Size(max = 17, message = "VIN码长度不能超过17个字符")
private String vin;
@Schema(description = "车牌号", requiredMode = Schema.RequiredMode.NOT_REQUIRED, example = "京A12345")
@Size(max = 20, message = "车牌号长度不能超过20个字符")
private String plateNo;
@Schema(description = "车辆状态", requiredMode = Schema.RequiredMode.NOT_REQUIRED, example = "AUCTIONING")
@Size(max = 64, message = "车辆状态长度不能超过64个字符")
private String vehicleStatus;
@Schema(description = "评分(保留1位小数)", requiredMode = Schema.RequiredMode.NOT_REQUIRED, example = "4.0")
private BigDecimal score;
......@@ -58,9 +34,6 @@ public class InspectionReportUpdateVO implements Serializable {
@Size(max = 1, message = "评分级别只能是单个字符")
private String scoreLevel;
@Schema(description = "绑定状态(1:已绑定;2:未绑定)", requiredMode = Schema.RequiredMode.NOT_REQUIRED, example = "2")
private Integer bindStatus;
@Schema(description = "H5链接地址", requiredMode = Schema.RequiredMode.NOT_REQUIRED, example = "https://xxx.com/report/REP20260312001")
@Size(max = 512, message = "H5链接地址长度不能超过512个字符")
private String h5Url;
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!