一、概述

文档审核功能是知识库系统内容质量控制的重要机制,通过审核流程确保发布内容的质量和合规性。

本文将详细介绍如何在kb-document服务中实现完整的文档审核功能。

1.1 功能定位

审核系统作为内容质量控制的核心功能,提供以下核心能力:

功能模块说明使用场景
提交审核将草稿状态的文档提交审核内容完成编辑后申请发布
审核通过审核通过后文档自动发布内容符合要求,允许发布
审核驳回驳回文档并返回草稿状态内容不符合要求,需要修改
待审核列表查看待审核的文档审核人员工作台
审核历史查看文档的所有审核记录追溯审核过程

1.2 审核流程设计

标准审核流程:

草稿状态(0) → 提交审核 → 待审核状态(3) → 审核通过 → 已发布状态(1)
                                   ↓
                              审核驳回
                                   ↓
                               草稿状态(0)

审核状态说明:

状态码状态名称说明
0草稿文档编辑中,未提交审核
1已发布审核通过,已对外发布
2已下架已发布后被下架
3待审核已提交审核,等待审核

审核结果说明:

结果码结果名称文档状态变化
1通过3 → 1(待审核 → 已发布)
2驳回3 → 0(待审核 → 草稿)

1.3 审核轮次机制

系统支持多轮审核,通过reviewRound字段记录审核轮次:

  1. 首次审核: reviewRound = 1
  2. 驳回后重新提交: reviewRound = 2
  3. 再次驳回后提交: reviewRound = 3
  4. 以此类推...

轮次计算方式:

SELECT COALESCE(MAX(review_round), 0) + 1
FROM tb_document_review
WHERE document_id = ?

1.4 数据模型

文档 (Document)
    ├── 审核记录1 (DocumentReview) - 第1轮审核
    ├── 审核记录2 (DocumentReview) - 第2轮审核(驳回后重提)
    └── 审核记录3 (DocumentReview) - 第3轮审核

二、数据库设计

2.1 文档审核表结构

-- 文档审核表
DROP TABLE IF EXISTS `tb_document_review`;
CREATE TABLE `tb_document_review` (
    `id` BIGINT(20) PRIMARY KEY COMMENT '审核记录ID(雪花ID)',
    `document_id` BIGINT(20) NOT NULL COMMENT '文档ID',

    `reviewer_id` BIGINT(20) NOT NULL COMMENT '审核人ID',
    `reviewer_name` VARCHAR(50) COMMENT '审核人姓名',

    `review_result` TINYINT NOT NULL COMMENT '审核结果:1-通过,2-驳回',
    `review_comment` TEXT COMMENT '审核意见',

    `before_status` TINYINT COMMENT '审核前状态',

    `reviewed_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '审核时间',

    `review_round` INT DEFAULT 1 COMMENT '审核轮次',

    `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',

    KEY `idx_document_id` (`document_id`),
    KEY `idx_reviewer_id` (`reviewer_id`),
    KEY `idx_reviewed_at` (`reviewed_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='文档审核记录表';

2.2 字段说明

字段类型说明必填默认值
idBIGINT审核记录ID(雪花ID)是自动生成
document\_idBIGINT文档ID是-
reviewer\_idBIGINT审核人ID是-
reviewer\_nameVARCHAR(50)审核人姓名(冗余)否-
review\_resultTINYINT审核结果(1-通过,2-驳回)是-
review\_commentTEXT审核意见否-
before\_statusTINYINT审核前状态(冗余)否-
reviewed\_atDATETIME审核时间是CURRENT\_TIMESTAMP
review\_roundINT审核轮次是1
created\_atDATETIME创建时间是CURRENT\_TIMESTAMP

2.3 索引设计

  • 主键索引:id - 主键唯一标识
  • 普通索引:idx_document_id - 加速按文档查询审核记录
  • 普通索引:idx_reviewer_id - 加速按审核人查询
  • 普通索引:idx_reviewed_at - 加速按时间排序

2.4 文档状态字段说明

文档表(kb\_document)中的status字段需要支持审核相关状态:

状态值状态名称说明
0草稿文档编辑中
1已发布审核通过并发布
2已下架已发布后被下架
3待审核已提交审核,等待审核

三、实体类设计

3.1 创建DocumentReview实体类

创建 kb-document/src/main/java/com/knowledge/base/document/entity/DocumentReview.java:

package com.knowledge.base.document.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import java.time.LocalDateTime;

/**
 * 文档审核记录实体
 *
 * @author 苏三
 * @since 1.0.0
 */
@Data
@TableName("tb_document_review")
@Schema(description = "文档审核记录实体")
public class DocumentReview {

    /**
     * 审核记录ID
     */
    @TableId(type = IdType.ASSIGN_ID)
    @Schema(description = "审核记录ID")
    private Long id;

    /**
     * 文档ID
     */
    @Schema(description = "文档ID")
    private Long documentId;

    /**
     * 审核人ID
     */
    @Schema(description = "审核人ID")
    private Long reviewerId;

    /**
     * 审核人姓名
     */
    @Schema(description = "审核人姓名")
    private String reviewerName;

    /**
     * 审核结果:1-通过,2-驳回
     */
    @Schema(description = "审核结果")
    private Integer reviewResult;

    /**
     * 审核意见
     */
    @Schema(description = "审核意见")
    private String reviewComment;

    /**
     * 审核前状态
     */
    @Schema(description = "审核前状态")
    private Integer beforeStatus;

    /**
     * 审核时间
     */
    @Schema(description = "审核时间")
    private LocalDateTime reviewedAt;

    /**
     * 审核轮次
     */
    @Schema(description = "审核轮次")
    private Integer reviewRound;

    /**
     * 创建时间
     */
    @Schema(description = "创建时间")
    private LocalDateTime createdAt;
}

设计要点:

  • 使用@TableId(type = IdType.ASSIGN_ID)配置雪花ID生成策略
  • 冗余存储审核人姓名,避免关联查询
  • 记录审核前状态,支持状态回溯
  • 记录审核轮次,支持多轮审核

四、DTO设计

4.1 创建文档审核DTO

创建 kb-document/src/main/java/com/knowledge/base/document/dto/DocumentReviewDTO.java:

package com.knowledge.base.document.dto;

import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 文档审核DTO
 *
 * @author 苏三
 * @since 1.0.0
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "文档审核参数")
public class DocumentReviewDTO {

    /**
     * 审核记录ID
     */
    @Schema(description = "审核记录ID")
    @NotNull(message = "审核记录ID不能为空")
    private Long reviewId;

    /**
     * 审核结果:1-通过,2-驳回
     */
    @Schema(description = "审核结果:1-通过,2-驳回")
    @NotNull(message = "审核结果不能为空")
    private Integer reviewResult;

    /**
     * 审核意见
     */
    @Schema(description = "审核意见")
    private String reviewComment;
}

设计要点:

  • 通过reviewId指定要审核的记录
  • reviewResult区分通过和驳回
  • reviewComment记录审核意见,驳回时必填

4.2 创建审核查询DTO

创建 kb-document/src/main/java/com/knowledge/base/document/dto/ReviewQueryDTO.java:

package com.knowledge.base.document.dto;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

/**
 * 审核查询DTO
 *
 * @author 苏三
 * @since 1.0.0
 */
@Data
@Schema(description = "审核查询请求")
public class ReviewQueryDTO {

    @Schema(description = "当前页")
    private Long current = 1L;

    @Schema(description = "每页大小")
    private Long size = 10L;

    @Schema(description = "审核状态:0-待审核,1-通过,2-驳回")
    private Integer status;

    @Schema(description = "审核人ID")
    private Long reviewerId;

    @Schema(description = "关键词搜索")
    private String keyword;
}

设计要点:

  • 支持分页查询
  • 支持按审核人筛选
  • 支持关键词搜索(搜索文档标题)

五、VO设计

5.1 创建文档审核VO

创建 kb-document/src/main/java/com/knowledge/base/document/vo/DocumentReviewVO.java:

package com.knowledge.base.document.vo;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;

/**
 * 文档审核VO
 *
 * @author 苏三
 * @since 1.0.0
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "文档审核信息")
public class DocumentReviewVO {

    @Schema(description = "审核记录ID")
    private Long id;

    @Schema(description = "文档ID")
    private Long documentId;

    @Schema(description = "文档标题")
    private String documentTitle;

    @Schema(description = "审核人ID")
    private Long reviewerId;

    @Schema(description = "审核人姓名")
    private String reviewerName;

    @Schema(description = "审核结果:1-通过,2-驳回")
    private Integer reviewResult;

    @Schema(description = "审核意见")
    private String reviewComment;

    @Schema(description = "审核前状态")
    private Integer beforeStatus;

    @Schema(description = "审核时间")
    private LocalDateTime reviewedAt;

    @Schema(description = "审核轮次")
    private Integer reviewRound;

    @Schema(description = "创建时间")
    private LocalDateTime createdAt;
}

设计要点:

  • 使用@Builder模式支持灵活构建
  • 冗余documentTitle字段,避免关联查询
  • 包含完整的审核信息用于展示

六、Mapper层设计

6.1 创建DocumentReviewMapper接口

创建 kb-document/src/main/java/com/knowledge/base/document/mapper/DocumentReviewMapper.java:

package com.knowledge.base.document.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.knowledge.base.document.entity.DocumentReview;
import org.apache.ibatis.annotations.Mapper;

/**
 * 文档审核Mapper接口
 *
 * @author 苏三
 * @since 1.0.0
 */
@Mapper
public interface DocumentReviewMapper extends BaseMapper<DocumentReview> {

}

设计要点:

  • 继承BaseMapper<DocumentReview>获得基础CRUD方法
  • 使用@Mapper注解标记为MyBatis Mapper接口
  • 定义了多个查询方法支持审核记录查询和统计

6.2 创建DocumentReviewMapper.xml

创建 kb-document/src/main/resources/mapper/DocumentReviewMapper.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.knowledge.base.document.mapper.DocumentReviewMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.knowledge.base.document.entity.DocumentReview">
        <id column="id" property="id" />
        <result column="document_id" property="documentId" />
        <result column="reviewer_id" property="reviewerId" />
        <result column="reviewer_name" property="reviewerName" />
        <result column="review_result" property="reviewResult" />
        <result column="review_comment" property="reviewComment" />
        <result column="before_status" property="beforeStatus" />
        <result column="reviewed_at" property="reviewedAt" />
        <result column="review_round" property="reviewRound" />
        <result column="created_at" property="createdAt" />
    </resultMap>
    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
        id, document_id, reviewer_id, reviewer_name, review_result, review_comment, before_status,
        reviewed_at, review_round, created_at
    </sql>
    <!-- 根据文档ID查询审核记录列表 -->
    <select id="selectByDocumentId" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_document_review
        WHERE document_id = #{documentId}
        ORDER BY review_round ASC, created_at DESC
    </select>
    <!-- 根据审核人ID查询审核记录列表 -->
    <select id="selectByReviewerId" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_document_review
        WHERE reviewer_id = #{reviewerId}
        ORDER BY created_at DESC
    </select>
    <!-- 根据文档ID和审核轮次查询审核记录 -->
    <select id="selectByDocumentIdAndRound" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_document_review
        WHERE document_id = #{documentId}
        AND review_round = #{reviewRound}
        ORDER BY created_at DESC
    </select>
    <!-- 查询文档的最新审核记录 -->
    <select id="selectLatestByDocumentId" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_document_review
        WHERE document_id = #{documentId}
        ORDER BY review_round DESC, created_at DESC
        LIMIT 1
    </select>
    <!-- 统计文档的审核轮次 -->
    <select id="countRoundsByDocumentId" resultType="java.lang.Integer">
        SELECT COALESCE(MAX(review_round), 0)
        FROM tb_document_review
        WHERE document_id = #{documentId}
    </select>
    <!-- 统计审核人的审核数量 -->
    <select id="countByReviewerId" resultType="java.lang.Long">
        SELECT COUNT(*)
        FROM tb_document_review
        WHERE reviewer_id = #{reviewerId}
    </select>
    <!-- 查询待审核的文档列表(审核人相关的) -->
    <select id="selectPendingReviews" resultMap="BaseResultMap">
        SELECT DISTINCT dr.*
        FROM tb_document_review dr
        INNER JOIN kb_document d ON dr.document_id = d.id
        WHERE d.status = 3
        AND dr.reviewer_id = #{reviewerId}
        AND dr.review_result IS NULL
        ORDER BY dr.created_at ASC
    </select>
</mapper>

Mapper方法说明:

方法说明使用场景
selectByDocumentId查询文档的所有审核记录审核历史展示
selectByReviewerId查询审核人的审核记录审核工作统计
selectByDocumentIdAndRound查询文档指定轮次的审核记录审核详情查看
selectLatestByDocumentId查询文档的最新审核记录当前审核状态
countRoundsByDocumentId统计文档的审核轮次计算下一轮次
countByReviewerId统计审核人的审核数量审核工作量统计
selectPendingReviews查询待审核的文档列表审核人员工作台

七、Service层设计

7.1 创建DocumentReviewService接口

创建 kb-document/src/main/java/com/knowledge/base/document/service/DocumentReviewService.java:

package com.knowledge.base.document.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.knowledge.base.common.result.PageResult;
import com.knowledge.base.document.dto.DocumentReviewDTO;
import com.knowledge.base.document.dto.ReviewQueryDTO;
import com.knowledge.base.document.entity.DocumentReview;
import com.knowledge.base.document.vo.DocumentReviewVO;

/**
 * 文档审核Service接口
 *
 * @author 苏三
 * @since 1.0.0
 */
public interface DocumentReviewService extends IService<DocumentReview> {

    /**
     * 提交审核
     *
     * @param documentId 文档ID
     * @return 是否成功
     */
    Boolean submitForReview(Long documentId);

    /**
     * 审核通过
     *
     * @param dto 审核DTO
     * @return 是否成功
     */
    Boolean approveReview(DocumentReviewDTO dto);

    /**
     * 审核驳回
     *
     * @param dto 审核DTO
     * @return 是否成功
     */
    Boolean rejectReview(DocumentReviewDTO dto);

    /**
     * 获取待审核文档列表
     *
     * @param dto 查询DTO
     * @return 分页结果
     */
    PageResult<DocumentReviewVO> getPendingReviews(ReviewQueryDTO dto);

    /**
     * 获取文档审核历史
     *
     * @param documentId 文档ID
     * @return 审核历史列表
     */
    java.util.List<DocumentReviewVO> getDocumentReviewHistory(Long documentId);
}

7.2 创建DocumentReviewServiceImpl实现类

创建 kb-document/src/main/java/com/knowledge/base/document/service/impl/DocumentReviewServiceImpl.java:

package com.knowledge.base.document.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.knowledge.base.common.exception.BusinessException;
import com.knowledge.base.common.result.PageResult;
import com.knowledge.base.common.utils.SnowflakeIdGenerator;
import com.knowledge.base.document.dto.DocumentReviewDTO;
import com.knowledge.base.document.dto.ReviewQueryDTO;
import com.knowledge.base.document.entity.Document;
import com.knowledge.base.document.entity.DocumentReview;
import com.knowledge.base.document.mapper.DocumentMapper;
import com.knowledge.base.document.mapper.DocumentReviewMapper;
import com.knowledge.base.document.service.DocumentReviewService;
import com.knowledge.base.document.vo.DocumentReviewVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 文档审核Service实现类
 *
 * <p>按照阿里巴巴Java开发规范设计,实现文档审核相关业务逻辑</p>
 *
 * @author 苏三
 * @since 1.0.0
 */
@Slf4j
@Service
public class DocumentReviewServiceImpl extends ServiceImpl<DocumentReviewMapper, DocumentReview> implements DocumentReviewService {

    @Resource
    private DocumentReviewMapper documentReviewMapper;

    @Resource
    private DocumentMapper documentMapper;

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean submitForReview(Long documentId) {
        log.info("提交文档审核:documentId={}", documentId);

        if (documentId == null) {
            throw new BusinessException("文档ID不能为空");
        }

        // 检查文档是否存在
        Document document = documentMapper.selectById(documentId);
        if (document == null) {
            throw new BusinessException("文档不存在");
        }

        // 检查文档状态
        if (document.getStatus() != 0) {
            throw new BusinessException("只有草稿状态的文档才能提交审核");
        }

        // 获取当前审核轮次
        Integer currentRound = jdbcTemplate.queryForObject(
                "SELECT COALESCE(MAX(review_round), 0) FROM tb_document_review WHERE document_id = ?",
                Integer.class,
                documentId
        );

        // 创建审核记录
        DocumentReview review = new DocumentReview();
        review.setId(SnowflakeIdGenerator.getInstance().nextId());
        review.setDocumentId(documentId);
        review.setReviewerId(null); // 待分配
        review.setReviewerName(null);
        review.setReviewResult(null);
        review.setReviewComment(null);
        review.setBeforeStatus(document.getStatus());
        review.setReviewedAt(null);
        review.setReviewRound((currentRound != null ? currentRound : 0) + 1);
        review.setCreatedAt(LocalDateTime.now());

        int count = documentReviewMapper.insert(review);
        if (count <= 0) {
            throw new BusinessException("提交审核失败");
        }

        // 更新文档状态为待审核
        document.setStatus(3); // 3-待审核
        documentMapper.updateById(document);

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean approveReview(DocumentReviewDTO dto) {
        log.info("审核通过:reviewId={}", dto.getReviewId());

        if (dto.getReviewId() == null) {
            throw new BusinessException("审核记录ID不能为空");
        }

        // 检查审核记录是否存在
        DocumentReview review = documentReviewMapper.selectById(dto.getReviewId());
        if (review == null) {
            throw new BusinessException("审核记录不存在");
        }

        if (review.getReviewResult() != null) {
            throw new BusinessException("该记录已审核");
        }

        // TODO: 从上下文获取当前审核人信息
        Long reviewerId = 1L;
        String reviewerName = "审核员";

        // 更新审核记录
        review.setReviewerId(reviewerId);
        review.setReviewerName(reviewerName);
        review.setReviewResult(1); // 1-通过
        review.setReviewComment(dto.getReviewComment());
        review.setReviewedAt(LocalDateTime.now());
        documentReviewMapper.updateById(review);

        // 更新文档状态为已发布
        Document document = documentMapper.selectById(review.getDocumentId());
        if (document != null) {
            document.setStatus(1); // 1-已发布
            documentMapper.updateById(document);
        }

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean rejectReview(DocumentReviewDTO dto) {
        log.info("审核驳回:reviewId={}", dto.getReviewId());

        if (dto.getReviewId() == null) {
            throw new BusinessException("审核记录ID不能为空");
        }

        if (!StringUtils.hasText(dto.getReviewComment())) {
            throw new BusinessException("驳回意见不能为空");
        }

        // 检查审核记录是否存在
        DocumentReview review = documentReviewMapper.selectById(dto.getReviewId());
        if (review == null) {
            throw new BusinessException("审核记录不存在");
        }

        if (review.getReviewResult() != null) {
            throw new BusinessException("该记录已审核");
        }

        // TODO: 从上下文获取当前审核人信息
        Long reviewerId = 1L;
        String reviewerName = "审核员";

        // 更新审核记录
        review.setReviewerId(reviewerId);
        review.setReviewerName(reviewerName);
        review.setReviewResult(2); // 2-驳回
        review.setReviewComment(dto.getReviewComment());
        review.setReviewedAt(LocalDateTime.now());
        documentReviewMapper.updateById(review);

        // 更新文档状态为草稿
        Document document = documentMapper.selectById(review.getDocumentId());
        if (document != null) {
            document.setStatus(0); // 0-草稿
            documentMapper.updateById(document);
        }

        return true;
    }

    @Override
    public PageResult<DocumentReviewVO> getPendingReviews(ReviewQueryDTO dto) {
        // 构建查询条件
        LambdaQueryWrapper<DocumentReview> wrapper = new LambdaQueryWrapper<>();
        wrapper.isNull(DocumentReview::getReviewResult); // 未审核的记录

        if (dto.getReviewerId() != null) {
            wrapper.eq(DocumentReview::getReviewerId, dto.getReviewerId());
        }

        // 关键词搜索
        if (StringUtils.hasText(dto.getKeyword())) {
            // 子查询文档标题
            wrapper.exists(
                    "SELECT 1 FROM kb_document d WHERE d.id = tb_document_review.document_id AND d.title LIKE CONCAT('%', {0}, '%')",
                    dto.getKeyword()
            );
        }

        // 排序
        wrapper.orderByDesc(DocumentReview::getCreatedAt);

        // 分页查询
        Page<DocumentReview> page = new Page<>(dto.getCurrent(), dto.getSize());
        IPage<DocumentReview> reviewPage = documentReviewMapper.selectPage(page, wrapper);

        // 转换为VO
        IPage<DocumentReviewVO> voPage = reviewPage.convert(review -> {
            // 获取文档标题
            Document document = documentMapper.selectById(review.getDocumentId());
            String documentTitle = document != null ? document.getTitle() : "";

            return DocumentReviewVO.builder()
                    .id(review.getId())
                    .documentId(review.getDocumentId())
                    .documentTitle(documentTitle)
                    .reviewerId(review.getReviewerId())
                    .reviewerName(review.getReviewerName())
                    .reviewResult(review.getReviewResult())
                    .reviewComment(review.getReviewComment())
                    .beforeStatus(review.getBeforeStatus())
                    .reviewedAt(review.getReviewedAt())
                    .reviewRound(review.getReviewRound())
                    .createdAt(review.getCreatedAt())
                    .build();
        });

        return PageResult.<DocumentReviewVO>builder()
                .records(voPage.getRecords())
                .total(voPage.getTotal())
                .current(voPage.getCurrent())
                .size(voPage.getSize())
                .build();
    }

    @Override
    public List<DocumentReviewVO> getDocumentReviewHistory(Long documentId) {
        if (documentId == null) {
            throw new BusinessException("文档ID不能为空");
        }

        List<DocumentReview> reviews = documentReviewMapper.selectList(
                new LambdaQueryWrapper<DocumentReview>()
                        .eq(DocumentReview::getDocumentId, documentId)
                        .orderByDesc(DocumentReview::getReviewRound)
        );

        return reviews.stream()
                .map(review -> {
                    // 获取文档标题
                    Document document = documentMapper.selectById(review.getDocumentId());
                    String documentTitle = document != null ? document.getTitle() : "";

                    return DocumentReviewVO.builder()
                            .id(review.getId())
                            .documentId(review.getDocumentId())
                            .documentTitle(documentTitle)
                            .reviewerId(review.getReviewerId())
                            .reviewerName(review.getReviewerName())
                            .reviewResult(review.getReviewResult())
                            .reviewComment(review.getReviewComment())
                            .beforeStatus(review.getBeforeStatus())
                            .reviewedAt(review.getReviewedAt())
                            .reviewRound(review.getReviewRound())
                            .createdAt(review.getCreatedAt())
                            .build();
                })
                .collect(Collectors.toList());
    }
}

核心实现要点:

  1. 提交审核逻辑:

    • 验证文档状态必须是草稿(0)
    • 自动计算审核轮次(最大轮次+1)
    • 创建审核记录并更新文档状态为待审核(3)
  2. 审核通过逻辑:

    • 验证审核记录未被审核过
    • 更新审核记录(结果=1,审核人信息)
    • 更新文档状态为已发布(1)
  3. 审核驳回逻辑:

    • 驳回意见必填校验
    • 更新审核记录(结果=2,审核人信息)
    • 更新文档状态为草稿(0)
  4. 待审核列表查询:

    • 查询reviewResult IS NULL的记录
    • 支持关键词搜索文档标题
    • 关联查询文档信息

八、Controller层设计

8.1 创建DocumentReviewController

创建 kb-document/src/main/java/com/knowledge/base/document/controller/DocumentReviewController.java:

package com.knowledge.base.document.controller;

import com.knowledge.base.common.annotation.OperationLog;
import com.knowledge.base.common.result.PageResult;
import com.knowledge.base.common.result.Result;
import com.knowledge.base.document.dto.DocumentReviewDTO;
import com.knowledge.base.document.dto.ReviewQueryDTO;
import com.knowledge.base.document.service.DocumentReviewService;
import com.knowledge.base.document.vo.DocumentReviewVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 文档审核Controller
 *
 * @author 苏三
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/api/document-reviews")
@RequiredArgsConstructor
@Tag(name = "文档审核", description = "文档审核相关接口")
public class DocumentReviewController {

    private final DocumentReviewService reviewService;

    /**
     * 提交审核
     */
    @PostMapping("/submit/{documentId}")
    @Operation(summary = "提交文档审核", description = "提交文档进行审核")
    @OperationLog(module = "文档审核", operation = "提交审核", description = "提交文档审核")
    public Result<Boolean> submitForReview(@PathVariable Long documentId) {
        Boolean result = reviewService.submitForReview(documentId);
        return Result.success(result);
    }

    /**
     * 审核通过
     */
    @PostMapping("/approve")
    @Operation(summary = "审核通过", description = "审核通过文档")
    @OperationLog(module = "文档审核", operation = "审核通过", description = "审核通过文档")
    public Result<Boolean> approveReview(@Valid @RequestBody DocumentReviewDTO dto) {
        Boolean result = reviewService.approveReview(dto);
        return Result.success(result);
    }

    /**
     * 审核驳回
     */
    @PostMapping("/reject")
    @Operation(summary = "审核驳回", description = "审核驳回文档")
    @OperationLog(module = "文档审核", operation = "审核驳回", description = "审核驳回文档")
    public Result<Boolean> rejectReview(@Valid @RequestBody DocumentReviewDTO dto) {
        Boolean result = reviewService.rejectReview(dto);
        return Result.success(result);
    }

    /**
     * 获取待审核文档列表
     */
    @PostMapping("/pending")
    @Operation(summary = "获取待审核文档", description = "获取待审核文档列表")
    public Result<PageResult<DocumentReviewVO>> getPendingReviews(@RequestBody ReviewQueryDTO dto) {
        PageResult<DocumentReviewVO> pageResult = reviewService.getPendingReviews(dto);
        return Result.success(pageResult);
    }

    /**
     * 获取文档审核历史
     */
    @GetMapping("/history/{documentId}")
    @Operation(summary = "获取审核历史", description = "获取文档的审核历史")
    public Result<List<DocumentReviewVO>> getDocumentReviewHistory(@PathVariable Long documentId) {
        List<DocumentReviewVO> history = reviewService.getDocumentReviewHistory(documentId);
        return Result.success(history);
    }
}

接口设计要点:

  1. 提交审核 - POST /api/document-reviews/submit/{documentId}

    • 将草稿文档提交审核
    • 自动计算审核轮次
  2. 审核通过 - POST /api/document-reviews/approve

    • 审核通过后文档自动发布
    • 可选填写审核意见
  3. 审核驳回 - POST /api/document-reviews/reject

    • 审核驳回后文档回到草稿状态
    • 必须填写驳回意见
  4. 待审核列表 - POST /api/document-reviews/pending

    • 查询待审核的文档列表
    • 支持分页和关键词搜索
  5. 审核历史 - GET /api/document-reviews/history/{documentId}

    • 查看文档的所有审核记录
    • 按审核轮次倒序排列

九、测试验证

9.1 启动应用

# 启动kb-document服务
cd kb-document
mvn spring-boot:run

9.2 测试提交审核

curl -X POST 'http://localhost:8083/api/document-reviews/submit/1' \
  -H 'Content-Type: application/json'

响应示例:

{
  "code": 200,
  "message": "操作成功",
  "data": true
}

9.3 测试获取待审核列表

curl -X POST 'http://localhost:8083/api/document-reviews/pending' \
  -H 'Content-Type: application/json' \
  -d '{
    "current": 1,
    "size": 10,
    "keyword": "技术"
  }'

响应示例:

{
  "code": 200,
  "message": "操作成功",
  "data": {
    "records": [
      {
        "id": 1,
        "documentId": 1,
        "documentTitle": "Spring Boot教程",
        "reviewerId": null,
        "reviewerName": null,
        "reviewResult": null,
        "reviewComment": null,
        "beforeStatus": 0,
        "reviewedAt": null,
        "reviewRound": 1,
        "createdAt": "2024-01-15T10:30:00"
      }
    ],
    "total": 1,
    "current": 1,
    "size": 10
  }
}

9.4 测试审核通过

curl -X POST 'http://localhost:8083/api/document-reviews/approve' \
  -H 'Content-Type: application/json' \
  -d '{
    "reviewId": 1,
    "reviewResult": 1,
    "reviewComment": "内容完整,审核通过"
  }'

9.5 测试审核驳回

curl -X POST 'http://localhost:8083/api/document-reviews/reject' \
  -H 'Content-Type: application/json' \
  -d '{
    "reviewId": 2,
    "reviewResult": 2,
    "reviewComment": "需要补充更多实例说明"
  }'

9.6 测试查询审核历史

curl -X GET 'http://localhost:8083/api/document-reviews/history/1'

响应示例:

{
  "code": 200,
  "message": "操作成功",
  "data": [
    {
      "id": 1,
      "documentId": 1,
      "documentTitle": "Spring Boot教程",
      "reviewerId": 1,
      "reviewerName": "审核员",
      "reviewResult": 2,
      "reviewComment": "需要补充更多实例说明",
      "beforeStatus": 0,
      "reviewedAt": "2024-01-15T11:00:00",
      "reviewRound": 1,
      "createdAt": "2024-01-15T10:30:00"
    },
    {
      "id": 2,
      "documentId": 1,
      "documentTitle": "Spring Boot教程",
      "reviewerId": 1,
      "reviewerName": "审核员",
      "reviewResult": 1,
      "reviewComment": "已修改,审核通过",
      "beforeStatus": 0,
      "reviewedAt": "2024-01-15T14:00:00",
      "reviewRound": 2,
      "createdAt": "2024-01-15T13:00:00"
    }
  ]
}

9.7 验证 Knife4j 文档

访问:http://localhost:8083/doc.html

查看文档审核相关接口的API文档和在线测试。

总结

本文详细介绍了kb-document服务中审核相关功能的完整实现,

包括:

核心功能

  • ✅ 提交审核(草稿 → 待审核)
  • ✅ 审核通过(待审核 → 已发布)
  • ✅ 审核驳回(待审核 → 草稿)
  • ✅ 待审核列表查询
  • ✅ 审核历史查询

审核流程图

编辑文档 → 草稿(0) → 提交审核 → 待审核(3)
                                   ↓
                            审核人审核
                                   ↓
                          ┌─────────┴─────────┐
                          ↓                   ↓
                     审核通过(1)          审核驳回(2)
                          ↓                   ↓
                       已发布(1)            草稿(0)
                          ↑                   │
                          └───────────────────┘
                        修改后重新提交
最后修改:2026 年 10 月 24 日
如果觉得我的文章对你有用,请随意赞赏