一、概述

文档审核是知识库系统的核心质量控制功能,通过"作者提交 → 审核员审批"的流程,确保发布到知识库的文档符合质量标准。

本文详细介绍如何在 kb-document 服务中实现完整的三阶段审核流程。

1.1 功能定位

功能模块说明使用场景
提交审核作者将草稿或已编辑文档提交审核文档完成后提交审批
审核通过审核员审批通过,文档正式发布内容合规,允许发布
审核驳回审核员驳回文档,退回草稿状态内容不合规,需修改
审核历史查询文档的完整审核记录追溯审核流程
批量审核审核员一次性处理多个待审核文档提升审核效率
实时通知通过 WebSocket 实时推送审核结果作者和审核员及时获知状态变更

1.2 数据模型

审核流程采用文档与审核记录的一对多关系。

审核记录表核心字段结构:

图片.png

状态流转:

图片.png

1.3 技术实现

  • 状态管理:通过 DocumentStatus 枚举统一管理文档状态
  • 事务控制:审核操作在数据库事务中完成,保证状态一致性
  • 事件驱动:通过 RabbitMQ 发布审核事件,解耦审核逻辑与通知推送
  • 实时推送:通过 WebSocket STOMP 协议向在线用户实时推送审核结果
  • 异步索引:审核通过后异步触发 RAG/KAG/ES 索引构建
  • 孤儿修复:自动检测并修复状态为待审核但缺少审核记录的文档

二、数据库设计

2.1 审核记录表结构

在 kb_document 数据库中创建 tb_document_review 表:

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) COMMENT '审核人ID',
    `reviewer_name` VARCHAR(50) COMMENT '审核人姓名',

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

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

    `reviewed_at` DATETIME COMMENT '审核时间',

    `review_round` INT DEFAULT 1 COMMENT '审核轮次',
    `review_level` INT DEFAULT 1 COMMENT '审核级别(1=一级审核,预留多级扩展)',

    `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(20)审核记录ID(雪花ID)是雪花算法生成
document\_idBIGINT(20)关联文档ID是-
reviewer\_idBIGINT(20)审核人ID否-
reviewer\_nameVARCHAR(50)审核人姓名否-
review\_resultTINYINTNULL=待审核,1=通过,2=驳回否NULL
review\_commentTEXT审核意见否-
before\_statusTINYINT审核前文档状态否-
reviewed\_atDATETIME审核完成时间否-
review\_roundINT审核轮次是1
review\_levelINT审核级别是1
created\_atDATETIME创建时间是CURRENT\_TIMESTAMP

设计要点:

  1. review_result 使用 NULL 表示待审核,这样可以方便地使用 IS NULL 条件查询待审核记录
  2. before_status 记录审核前文档状态,用于审核流程追踪和数据分析
  3. review_round 支持多轮审核(驳回后重新提交自动递增轮次)
  4. review_level 预留多级审核扩展(如一级初审、二级终审)

2.3 索引设计

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

2.4 文档状态枚举

在本功能中,文档的状态字段(kb_document.status)新增一种状态:

状态码枚举值说明
0DRAFT草稿
1PUBLISHED已发布
2ARCHIVED已归档
3PENDING\_REVIEW待审核

三、实体类设计

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;

    /**
     * 审核级别(1=一级审核,预留多级扩展)
     */
    @Schema(description = "审核级别")
    private Integer reviewLevel;

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

3.2 创建DocumentStatus枚举类

创建 kb-common/src/main/java/com/knowledge/base/common/enums/DocumentStatus.java:

package com.knowledge.base.common.enums;

import lombok.Getter;

/**
 * 文档状态枚举
 *
 * @author 苏三
 * @since 1.0.0
 */
@Getter
public enum DocumentStatus {

    /**
     * 草稿
     */
    DRAFT(0, "草稿"),

    /**
     * 已发布
     */
    PUBLISHED(1, "已发布"),

    /**
     * 已归档
     */
    ARCHIVED(2, "已归档"),

    /**
     * 待审核
     */
    PENDING_REVIEW(3, "待审核");

    private final Integer code;
    private final String name;

    DocumentStatus(Integer code, String name) {
        this.code = code;
        this.name = name;
    }

    public static DocumentStatus getByCode(Integer code) {
        for (DocumentStatus status : values()) {
            if (status.getCode().equals(code)) {
                return status;
            }
        }
        return null;
    }
}

3.3 设计思路

  1. 使用雪花ID:通过 @TableId(type = IdType.ASSIGN_ID) 配合 SnowflakeIdGenerator 生成全局唯一ID
  2. 独立实体:DocumentReview 不继承 BaseEntity,因为审核记录不需要软删除等字段,保持表结构精简
  3. reviewResult = NULL:表示"待审核"状态,利用 NULL 的语义简化查询条件
  4. 冗余字段:reviewerName 和 beforeStatus 冗余存储,避免关联查询

四、DTO和VO设计

4.1 创建DocumentReviewDTO

创建 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 {

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

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

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

4.2 创建ReviewActionDTO

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

package com.knowledge.base.document.dto;

import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
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 ReviewActionDTO {

    @NotBlank(message = "审核结果不能为空")
    @Schema(description = "审核结果:approved-通过,rejected-驳回", example = "approved")
    private String status;

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

4.3 创建BatchReviewDTO

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

package com.knowledge.base.document.dto;

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

import java.util.List;

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

    @NotEmpty(message = "审核任务ID列表不能为空")
    @Schema(description = "审核任务ID列表")
    private List<Long> taskIds;

    @NotBlank(message = "审核结果不能为空")
    @Schema(description = "审核结果:approved-通过,rejected-驳回", example = "approved")
    private String status;

    @Schema(description = "审核意见(驳回时建议填写)")
    private String comment;
}

4.4 创建ReviewQueryDTO

创建 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 = "作者ID")
    private Long authorId;

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

4.5 创建DocumentReviewVO

创建 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 authorId;

    @Schema(description = "文档作者姓名")
    private String authorName;

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

    @Schema(description = "文档分类ID")
    private Long categoryId;

    @Schema(description = "文档分类名称")
    private String categoryName;
}

4.6 创建ReviewEventDTO

创建 kb-common/src/main/java/com/knowledge/base/common/event/ReviewEventDTO.java:

package com.knowledge.base.common.event;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * 文档审核事件 DTO
 *
 * <p>通过 RabbitMQ 在 kb-document(审核逻辑)与 kb-foundation(通知推送)之间传递审核事件,
 * 实现跨模块解耦,避免直接依赖。</p>
 *
 * <p>事件类型(eventType):
 * <ul>
 *   <li>SUBMITTED — 文档提交审核,推送给所有审核员</li>
 *   <li>APPROVED  — 审核通过,推送给文档作者</li>
 *   <li>REJECTED  — 审核驳回,推送给文档作者</li>
 * </ul>
 * </p>
 *
 * @author 苏三
 * @since 1.0.0
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ReviewEventDTO implements Serializable {

    private static final long serialVersionUID = 1L;

    /** 事件类型:SUBMITTED / APPROVED / REJECTED */
    private String eventType;

    /** 文档ID */
    private Long documentId;

    /** 文档标题 */
    private String documentTitle;

    /** 文档作者ID */
    private Long authorId;

    /** 文档作者名称(冗余字段,避免查询) */
    private String authorName;

    /** 审核员ID */
    private Long reviewerId;

    /** 审核员名称 */
    private String reviewerName;

    /** 审核轮次 */
    private Integer reviewRound;

    /** 审核级别(预留多级扩展,默认1) */
    private Integer reviewLevel;

    /** 审核意见(驳回时必填) */
    private String reviewComment;

    /** 事件时间 */
    private LocalDateTime timestamp;
}

4.7 设计说明

DTO vs VO 的区别:

类型用途特点
DocumentReviewDTO审核操作请求参数包含校验注解
ReviewActionDTO单条审核参数简化前端传参,使用字符串状态
BatchReviewDTO批量审核参数包含任务ID列表
ReviewQueryDTO查询条件支持分页和多条件筛选
DocumentReviewVO返回审核信息包含关联的文档标题、作者、分类
ReviewEventDTORabbitMQ 消息体跨模块传递,实现 Serializable

五、数据访问层

5.1 创建Mapper接口

创建 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> {

}

5.2 创建Mapper 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>

5.3 MyBatis Plus集成

使用MyBatis Plus后,简单的CRUD操作无需编写SQL:

// 自动生成SQL
documentReviewMapper.selectById(id);
documentReviewMapper.selectList(wrapper);
documentReviewMapper.insert(review);
documentReviewMapper.updateById(review);
documentReviewMapper.selectPage(page, wrapper);

六、业务逻辑层

6.1 创建Service接口

创建 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;

import java.util.List;
import java.util.Map;

/**
 * 文档审核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 审核历史列表
     */
    List<DocumentReviewVO> getDocumentReviewHistory(Long documentId);

    /**
     * 获取待审核文档数量
     *
     * @return 待审核数量
     */
    Long getPendingCount();

    /**
     * 获取审核统计数据(待审核、已通过、已驳回数量)
     *
     * @return 统计数据 Map:pending/approved/rejected
     */
    Map<String, Long> getReviewStats();

    /**
     * 批量审核(通过或驳回)
     *
     * @param taskIds 审核任务ID列表
     * @param status  审核结果:approved-通过,rejected-驳回
     * @param comment 审核意见
     */
    void batchReview(List<Long> taskIds, String status, String comment);
}

6.2 创建Service实现类

创建 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.enums.DocumentStatus;
import com.knowledge.base.common.event.ReviewEventDTO;
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.utils.UserContext;
import com.knowledge.base.document.vo.DocumentReviewVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
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.LinkedHashMap;
import java.util.List;
import java.util.Map;
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;

    @Resource
    private RabbitTemplate rabbitTemplate;

    private static final String REVIEW_EXCHANGE = "kb.notification.exchange";

    // ==================== 提交审核 ====================

    @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().equals(DocumentStatus.DRAFT.getCode())
                && !document.getStatus().equals(DocumentStatus.PUBLISHED.getCode())) {
            throw new BusinessException("只有草稿或已发布状态的文档才能提交审核");
        }

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

        // 获取当前用户信息
        Long reviewerId;
        String reviewerName;
        try {
            reviewerId = UserContext.getCurrentUserId();
            reviewerName = UserContext.getCurrentUserName();
        } catch (Exception e) {
            reviewerId = null;
            reviewerName = null;
        }

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

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

        // 更新文档状态为待审核
        document.setStatus(DocumentStatus.PENDING_REVIEW.getCode());
        documentMapper.updateById(document);

        // 发布审核提交事件 → RabbitMQ,通知审核员
        try {
            ReviewEventDTO event = ReviewEventDTO.builder()
                    .eventType("SUBMITTED")
                    .documentId(documentId)
                    .documentTitle(document.getTitle())
                    .authorId(document.getAuthorId())
                    .authorName(document.getAuthorName())
                    .reviewRound(review.getReviewRound())
                    .reviewLevel(review.getReviewLevel())
                    .timestamp(LocalDateTime.now())
                    .build();
            rabbitTemplate.convertAndSend(REVIEW_EXCHANGE,
                    "notification.review.submitted", event);
            log.info("已发布审核提交事件:documentId={}, eventType=SUBMITTED", documentId);
        } catch (Exception e) {
            log.warn("发布审核提交事件失败(不影响审核流程):documentId={}, error={}",
                    documentId, e.getMessage());
        }

        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("该记录已审核");
        }

        // 从上下文获取当前审核人信息
        Long reviewerId;
        String reviewerName;
        try {
            reviewerId = UserContext.getCurrentUserId();
            reviewerName = UserContext.getCurrentUserName();
        } catch (Exception e) {
            reviewerId = null;
            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(DocumentStatus.PUBLISHED.getCode());
            document.setPublishTime(LocalDateTime.now());
            documentMapper.updateById(document);

            // 审核通过后异步触发RAG/KAG/ES索引构建(略,见进阶功能章节)

            // 发布审核通过事件 → RabbitMQ,通知文档作者
            try {
                ReviewEventDTO event = ReviewEventDTO.builder()
                        .eventType("APPROVED")
                        .documentId(document.getId())
                        .documentTitle(document.getTitle())
                        .authorId(document.getAuthorId())
                        .authorName(document.getAuthorName())
                        .reviewerId(reviewerId)
                        .reviewerName(reviewerName)
                        .reviewRound(review.getReviewRound())
                        .reviewLevel(review.getReviewLevel() != null ? review.getReviewLevel() : 1)
                        .timestamp(LocalDateTime.now())
                        .build();
                rabbitTemplate.convertAndSend(REVIEW_EXCHANGE,
                        "notification.review.approved", event);
                log.info("已发布审核通过事件:documentId={}, eventType=APPROVED",
                        document.getId());
            } catch (Exception e) {
                log.warn("发布审核通过事件失败(不影响审核流程):documentId={}, error={}",
                        document.getId(), e.getMessage());
            }
        }

        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("该记录已审核");
        }

        // 从上下文获取当前审核人信息
        Long reviewerId;
        String reviewerName;
        try {
            reviewerId = UserContext.getCurrentUserId();
            reviewerName = UserContext.getCurrentUserName();
        } catch (Exception e) {
            reviewerId = null;
            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(DocumentStatus.DRAFT.getCode());
            documentMapper.updateById(document);

            // 发布审核驳回事件 → RabbitMQ,通知文档作者
            try {
                ReviewEventDTO event = ReviewEventDTO.builder()
                        .eventType("REJECTED")
                        .documentId(document.getId())
                        .documentTitle(document.getTitle())
                        .authorId(document.getAuthorId())
                        .authorName(document.getAuthorName())
                        .reviewerId(reviewerId)
                        .reviewerName(reviewerName)
                        .reviewRound(review.getReviewRound())
                        .reviewLevel(review.getReviewLevel() != null ? review.getReviewLevel() : 1)
                        .reviewComment(dto.getReviewComment())
                        .timestamp(LocalDateTime.now())
                        .build();
                rabbitTemplate.convertAndSend(REVIEW_EXCHANGE,
                        "notification.review.rejected", event);
                log.info("已发布审核驳回事件:documentId={}, eventType=REJECTED",
                        document.getId());
            } catch (Exception e) {
                log.warn("发布审核驳回事件失败(不影响审核流程):documentId={}, error={}",
                        document.getId(), e.getMessage());
            }
        }

        return true;
    }

    // ==================== 查询方法 ====================

    @Override
    public PageResult<DocumentReviewVO> getPendingReviews(ReviewQueryDTO dto) {
        // 自动修复孤儿待审核文档
        syncOrphanedPendingDocuments();

        LambdaQueryWrapper<DocumentReview> wrapper = new LambdaQueryWrapper<>();

        // 状态筛选
        if (dto.getStatus() == null) {
            // 不筛选
        } else if (dto.getStatus() == 0) {
            wrapper.isNull(DocumentReview::getReviewResult);
        } else {
            wrapper.eq(DocumentReview::getReviewResult, dto.getStatus());
        }

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

        // 作者ID筛选(通过子查询关联 kb_document 表)
        if (dto.getAuthorId() != null) {
            wrapper.exists(
                "SELECT 1 FROM kb_document d WHERE d.id = tb_document_review.document_id "
                + "AND d.author_id = {0}", dto.getAuthorId()
            );
        }

        // 关键词搜索(按文档标题)
        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() : "";
            String authorName = document != null ? document.getAuthorName() : "";
            Long authorId = document != null ? document.getAuthorId() : null;
            Long categoryId = document != null ? document.getCategoryId() : null;

            String categoryName = "";
            if (categoryId != null) {
                try {
                    categoryName = jdbcTemplate.queryForObject(
                        "SELECT category_name FROM kb_category WHERE id = ?",
                        String.class, categoryId);
                } catch (Exception ignored) {}
            }

            return DocumentReviewVO.builder()
                    .id(review.getId())
                    .documentId(review.getDocumentId())
                    .documentTitle(documentTitle)
                    .authorId(authorId)
                    .authorName(authorName)
                    .reviewerId(review.getReviewerId())
                    .reviewerName(review.getReviewerName())
                    .reviewResult(review.getReviewResult())
                    .reviewComment(review.getReviewComment())
                    .beforeStatus(review.getBeforeStatus())
                    .reviewedAt(review.getReviewedAt())
                    .reviewRound(review.getReviewRound())
                    .createdAt(review.getCreatedAt())
                    .categoryId(categoryId)
                    .categoryName(categoryName)
                    .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());
            // ... 同上的VO转换逻辑
            return DocumentReviewVO.builder()
                    .id(review.getId())
                    .documentId(review.getDocumentId())
                    .documentTitle(document != null ? document.getTitle() : "")
                    // ... 其他字段
                    .build();
        }).collect(Collectors.toList());
    }

    @Override
    public Long getPendingCount() {
        LambdaQueryWrapper<DocumentReview> wrapper = new LambdaQueryWrapper<>();
        wrapper.isNull(DocumentReview::getReviewResult);
        return documentReviewMapper.selectCount(wrapper);
    }

    @Override
    public Map<String, Long> getReviewStats() {
        Map<String, Long> stats = new LinkedHashMap<>();
        stats.put("pending", documentReviewMapper.selectCount(
                new LambdaQueryWrapper<DocumentReview>().isNull(DocumentReview::getReviewResult)));
        stats.put("approved", documentReviewMapper.selectCount(
                new LambdaQueryWrapper<DocumentReview>().eq(DocumentReview::getReviewResult, 1)));
        stats.put("rejected", documentReviewMapper.selectCount(
                new LambdaQueryWrapper<DocumentReview>().eq(DocumentReview::getReviewResult, 2)));
        return stats;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchReview(List<Long> taskIds, String status, String comment) {
        if (taskIds == null || taskIds.isEmpty()) {
            throw new BusinessException("审核任务ID列表不能为空");
        }

        DocumentReviewDTO dto = new DocumentReviewDTO();
        dto.setReviewComment(comment);

        for (Long taskId : taskIds) {
            dto.setReviewId(taskId);
            if ("approved".equalsIgnoreCase(status)) {
                approveReview(dto);
            } else if ("rejected".equalsIgnoreCase(status)) {
                rejectReview(dto);
            } else {
                throw new BusinessException("无效的审核结果:" + status);
            }
        }
    }

    // ==================== 自动修复 ====================

    /**
     * 自动修复:为状态是 PENDING_REVIEW 但缺少待审核记录的文档补建审核记录
     */
    private void syncOrphanedPendingDocuments() {
        try {
            List<Long> orphanedIds = jdbcTemplate.queryForList(
                    "SELECT d.id FROM kb_document d " +
                    "WHERE d.status = ? AND d.deleted = 0 " +
                    "AND NOT EXISTS (SELECT 1 FROM tb_document_review r " +
                    "WHERE r.document_id = d.id AND r.review_result IS NULL)",
                    Long.class,
                    DocumentStatus.PENDING_REVIEW.getCode()
            );

            if (!orphanedIds.isEmpty()) {
                log.info("发现 {} 个孤儿待审核文档,正在自动补建审核记录...", orphanedIds.size());
                for (Long docId : orphanedIds) {
                    try {
                        Document document = documentMapper.selectById(docId);
                        if (document == null) continue;

                        Integer currentRound = jdbcTemplate.queryForObject(
                            "SELECT COALESCE(MAX(review_round), 0) FROM tb_document_review "
                            + "WHERE document_id = ?", Integer.class, docId);

                        DocumentReview review = new DocumentReview();
                        review.setId(SnowflakeIdGenerator.getInstance().nextId());
                        review.setDocumentId(docId);
                        review.setReviewResult(null);
                        review.setBeforeStatus(document.getStatus());
                        review.setReviewRound((currentRound != null ? currentRound : 0) + 1);
                        review.setReviewLevel(1);
                        review.setCreatedAt(LocalDateTime.now());
                        documentReviewMapper.insert(review);
                    } catch (Exception e) {
                        log.warn("补建审核记录失败:documentId={}, error={}", docId, e.getMessage());
                    }
                }
                log.info("孤儿待审核文档补建完成,共处理 {} 条", orphanedIds.size());
            }
        } catch (Exception e) {
            log.warn("检查孤儿待审核文档失败(不影响查询流程):{}", e.getMessage());
        }
    }
}

6.3 核心业务逻辑

6.3.1 提交审核流程

图片.png

6.3.2 审核通过流程

图片.png

6.3.3 审核驳回流程

图片.png

6.3.4 孤儿文档自动修复

当系统出现数据不一致(文档状态为 PENDING\_REVIEW 但没有待审核记录)时,在查询审核任务列表时自动检测并补建审核记录:

private void syncOrphanedPendingDocuments() {
    // 查找:status = PENDING_REVIEW 但没有 review_result IS NULL 的记录
    List<Long> orphanedIds = jdbcTemplate.queryForList(
        "SELECT d.id FROM kb_document d " +
        "WHERE d.status = ? AND d.deleted = 0 " +
        "AND NOT EXISTS (SELECT 1 FROM tb_document_review r " +
        "WHERE r.document_id = d.id AND r.review_result IS NULL)",
        Long.class,
        DocumentStatus.PENDING_REVIEW.getCode()
    );
    // 为每个孤儿文档补建审核记录
    for (Long docId : orphanedIds) {
        // ... 创建审核记录
    }
}

七、控制器层

7.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.result.PageResult;
import com.knowledge.base.common.result.Result;
import com.knowledge.base.document.dto.BatchReviewDTO;
import com.knowledge.base.document.dto.DocumentReviewDTO;
import com.knowledge.base.document.dto.ReviewActionDTO;
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;
import java.util.Map;

/**
 * 文档审核Controller
 *
 * <p>映射路径 /review,通过网关 /api/document/review/** 访问。</p>
 *
 * @author 苏三
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/review")
@RequiredArgsConstructor
@Tag(name = "文档审核", description = "文档审核相关接口")
public class DocumentReviewController {

    private final DocumentReviewService reviewService;

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

    /**
     * 获取审核任务列表(支持按状态筛选)
     */
    @GetMapping("/tasks")
    @Operation(summary = "获取审核任务列表", description = "分页查询审核任务,支持按状态筛选")
    public Result<PageResult<DocumentReviewVO>> getReviewTasks(
            @RequestParam(required = false) String status,
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Long authorId) {
        ReviewQueryDTO dto = new ReviewQueryDTO();
        dto.setCurrent(page.longValue());
        dto.setSize(pageSize.longValue());
        dto.setKeyword(keyword);
        dto.setAuthorId(authorId);

        // 状态映射:pending→0, approved→1, rejected→2
        if (status != null) {
            dto.setStatus("pending".equals(status) ? 0 :
                          "approved".equals(status) ? 1 :
                          "rejected".equals(status) ? 2 : null);
        }

        PageResult<DocumentReviewVO> pageResult = reviewService.getPendingReviews(dto);
        return Result.success(pageResult);
    }

    /**
     * 获取待审核任务数量
     */
    @GetMapping("/tasks/pending-count")
    @Operation(summary = "获取待审核任务数量", description = "获取当前待审核的文档数量")
    public Result<Long> getPendingCount() {
        Long count = reviewService.getPendingCount();
        return Result.success(count);
    }

    /**
     * 获取审核统计数据
     */
    @GetMapping("/tasks/stats")
    @Operation(summary = "获取审核统计数据", description = "获取待审核、已通过、已驳回数量")
    public Result<Map<String, Long>> getReviewStats() {
        Map<String, Long> stats = reviewService.getReviewStats();
        return Result.success(stats);
    }

    /**
     * 单条审核(通过或驳回)
     */
    @PostMapping("/tasks/{taskId}/review")
    @Operation(summary = "审核文档", description = "对文档进行审核(通过或驳回)")
    public Result<Boolean> reviewDocument(@PathVariable Long taskId,
                                           @Valid @RequestBody ReviewActionDTO dto) {
        DocumentReviewDTO reviewDTO = new DocumentReviewDTO();
        reviewDTO.setReviewId(taskId);
        reviewDTO.setReviewComment(dto.getComment());

        Boolean result;
        if ("approved".equalsIgnoreCase(dto.getStatus())) {
            reviewDTO.setReviewResult(1);
            result = reviewService.approveReview(reviewDTO);
        } else if ("rejected".equalsIgnoreCase(dto.getStatus())) {
            reviewDTO.setReviewResult(2);
            result = reviewService.rejectReview(reviewDTO);
        } else {
            return Result.error("无效的审核结果:" + dto.getStatus());
        }

        return Result.success(result);
    }

    /**
     * 批量审核(通过或驳回)
     */
    @PostMapping("/tasks/batch-review")
    @Operation(summary = "批量审核", description = "批量对文档进行审核(通过或驳回)")
    public Result<String> batchReview(@Valid @RequestBody BatchReviewDTO dto) {
        reviewService.batchReview(dto.getTaskIds(), dto.getStatus(), dto.getComment());
        return Result.success("批量审核完成");
    }

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

7.2 RESTful API设计

方法路径说明参数
POST/review/submit/{documentId}提交文档审核documentId(路径参数)
GET/review/tasks获取审核任务列表status, page, pageSize, keyword, authorId
GET/review/tasks/pending-count获取待审核数量-
GET/review/tasks/stats获取审核统计数据-
POST/review/tasks/{taskId}/review单条审核taskId, ReviewActionDTO
POST/review/tasks/batch-review批量审核BatchReviewDTO
GET/review/documents/{documentId}/history获取审核历史documentId

九、进阶功能

9.1 RabbitMQ 事件驱动架构

审核功能通过 RabbitMQ 实现跨模块解耦,审核操作发布事件,通知模块消费事件。

9.1.1 RabbitMQ配置

在 kb-foundation/src/main/java/com/knowledge/base/foundation/config/RabbitMQConfig.java 中添加审核通知队列配置:

// ======================== 审核通知 ========================

public static final String REVIEW_NOTIFICATION_QUEUE = "kb.notification.review.queue";
public static final String REVIEW_NOTIFICATION_ROUTING_KEY = "notification.review.*";

/**
 * 审核通知队列
 */
@Bean
public Queue reviewNotificationQueue() {
    return QueueBuilder.durable(REVIEW_NOTIFICATION_QUEUE).build();
}

/**
 * 审核通知队列绑定
 */
@Bean
public Binding reviewNotificationBinding() {
    return BindingBuilder.bind(reviewNotificationQueue())
            .to(notificationExchange())
            .with(REVIEW_NOTIFICATION_ROUTING_KEY);
}

路由键设计:

路由键事件类型目标用户
notification.review.submittedSUBMITTED所有审核员
notification.review.approvedAPPROVED文档作者
notification.review.rejectedREJECTED文档作者

9.1.2 JSON消息转换器配置

为使RabbitMQ能正确序列化/反序列化 ReviewEventDTO 对象,需要配置 Jackson 消息转换器并注册受信任包:

@Bean
public Jackson2JsonMessageConverter jackson2JsonMessageConverter() {
    Jackson2JsonMessageConverter converter = new Jackson2JsonMessageConverter();
    DefaultClassMapper classMapper = new DefaultClassMapper();
    classMapper.setTrustedPackages(
            "com.knowledge.base.common.event",
            "com.knowledge.base.foundation.dto",
            "java.util",
            "java.lang"
    );
    converter.setClassMapper(classMapper);
    return converter;
}

9.2 WebSocket 实时通知推送

9.2.1 WebSocket配置

在 kb-foundation 模块中配置 STOMP over WebSocket:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // 启用简单消息代理,用于向客户端推送消息
        registry.enableSimpleBroker("/topic", "/queue");
        // 客户端发送消息的目标前缀
        registry.setApplicationDestinationPrefixes("/app");
        // 用户消息前缀(用于 convertAndSendToUser)
        registry.setUserDestinationPrefix("/user/");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws/notification")
                .setAllowedOriginPatterns("*")
                .withSockJS(); // 启用SockJS支持
    }
}

9.2.2 审核通知监听器

创建 kb-foundation/src/main/java/com/knowledge/base/foundation/mq/ReviewNotificationListener.java:

@Slf4j
@Component
public class ReviewNotificationListener {

    @Resource
    private NotificationService notificationService;

    @Resource
    private SimpMessagingTemplate messagingTemplate;

    @Resource
    private JdbcTemplate jdbcTemplate;

    @RabbitListener(queues = "kb.notification.review.queue")
    public void handleReviewEvent(ReviewEventDTO event) {
        if (event == null || event.getEventType() == null) {
            log.warn("收到空的审核事件,忽略");
            return;
        }

        String notificationType = "review";
        String link = "/documents/" + event.getDocumentId();

        try {
            switch (event.getEventType()) {
                case "SUBMITTED" -> handleSubmitted(event, notificationType, link);
                case "APPROVED"  -> handleApproved(event, notificationType, link);
                case "REJECTED"  -> handleRejected(event, notificationType, link);
                default -> log.warn("未知的审核事件类型:{}", event.getEventType());
            }
        } catch (Exception e) {
            log.error("处理审核事件失败:eventType={}, documentId={}, error={}",
                    event.getEventType(), event.getDocumentId(), e.getMessage(), e);
        }
    }

    /**
     * 处理提交审核事件 → 通知所有审核员
     */
    private void handleSubmitted(ReviewEventDTO event, String type, String link) {
        String title = "新文档待审核";
        String content = String.format("用户「%s」提交了文档《%s》,请及时审核。",
                event.getAuthorName(), event.getDocumentTitle());

        // 1. 查询所有审核员用户ID(通过角色表关联查询)
        List<Long> reviewerIds = findReviewerUserIds();

        // 2. 持久化通知 + WebSocket点对点推送给每个审核员
        for (Long reviewerId : reviewerIds) {
            persistAndPush(reviewerId, type, title, content, link, event.getDocumentId());
        }

        // 3. 广播到审核员公共频道(在线审核员实时收到)
        Map<String, Object> payload = buildPushPayload(event, type, title, content, link);
        messagingTemplate.convertAndSend("/topic/reviewers", payload);
    }

    /**
     * 处理审核通过/驳回事件 → 通知文档作者
     */
    private void handleApproved(ReviewEventDTO event, String type, String link) {
        String title = "文档审核通过";
        String content = String.format("您的文档《%s》已通过审核,正式发布。",
                event.getDocumentTitle());

        if (event.getAuthorId() != null) {
            persistAndPush(event.getAuthorId(), type, title, content, link,
                    event.getDocumentId());
        }
    }

    private void handleRejected(ReviewEventDTO event, String type, String link) {
        String title = "文档审核驳回";
        String reason = event.getReviewComment() != null && !event.getReviewComment().isBlank()
                ? event.getReviewComment() : "未填写原因";
        String content = String.format("您的文档《%s》未通过审核,驳回原因:%s",
                event.getDocumentTitle(), reason);

        if (event.getAuthorId() != null) {
            persistAndPush(event.getAuthorId(), type, title, content, link,
                    event.getDocumentId());
        }
    }

    /**
     * 持久化通知到数据库 + WebSocket 点对点推送
     */
    private void persistAndPush(Long userId, String type, String title,
                                 String content, String link, Long documentId) {
        // 1. 持久化到数据库(离线用户也能看到)
        NotificationDTO dto = new NotificationDTO();
        dto.setUserId(userId);
        dto.setNotificationType(type);
        dto.setTitle(title);
        dto.setContent(content);
        dto.setLink(link);
        dto.setRelatedType("document");
        dto.setRelatedId(documentId);
        dto.setIsRead(0);
        notificationService.sendNotification(dto);

        // 2. WebSocket 点对点推送给目标用户
        Map<String, Object> payload = new LinkedHashMap<>();
        payload.put("notificationType", type);
        payload.put("title", title);
        payload.put("content", content);
        payload.put("link", link);
        payload.put("documentId", documentId);
        messagingTemplate.convertAndSendToUser(
                String.valueOf(userId), "/queue/notifications", payload);
    }

    /**
     * 查询所有具有 ROLE_REVIEWER 角色的用户ID
     */
    private List<Long> findReviewerUserIds() {
        try {
            return jdbcTemplate.queryForList(
                    "SELECT ur.user_id FROM kb_user_role ur " +
                    "JOIN kb_role r ON ur.role_id = r.id " +
                    "WHERE r.role_code = 'ROLE_REVIEWER'", Long.class);
        } catch (Exception e) {
            log.warn("查询审核员列表失败:{}", e.getMessage());
            return List.of();
        }
    }
}

事件到通知的映射关系:

事件类型通知标题通知内容模板接收者推送方式
SUBMITTED新文档待审核用户「%s」提交了文档《%s》,请及时审核。所有审核员点对点 + 广播
APPROVED文档审核通过您的文档《%s》已通过审核,正式发布。文档作者点对点
REJECTED文档审核驳回您的文档《%s》未通过审核,驳回原因:%s文档作者点对点

9.3 前端审核管理页面

9.3.1 审核Service

创建 src/services/review.service.ts:

import { http } from './request';
import { ReviewTask, User } from '@/types';

interface BackendReviewRecord {
  id: number;
  documentId: number;
  documentTitle: string;
  authorId: number | null;
  authorName: string | null;
  reviewerId: number | null;
  reviewerName: string | null;
  reviewResult: number | null;  // null=待审核, 1=通过, 2=驳回
  reviewComment: string | null;
  beforeStatus: number;
  reviewedAt: string | null;
  reviewRound: number;
  createdAt: string;
  categoryId: number | null;
  categoryName: string | null;
}

interface BackendPageResult {
  records: BackendReviewRecord[];
  total: number;
  current: number;
  size: number;
}

function mapToReviewTask(record: BackendReviewRecord): ReviewTask {
  let status: ReviewTask['status'] = 'pending';
  if (record.reviewResult === 1) status = 'approved';
  else if (record.reviewResult === 2) status = 'rejected';

  return {
    id: String(record.id),
    documentId: String(record.documentId),
    documentTitle: record.documentTitle,
    documentAuthor: record.authorName
      ? { id: String(record.authorId || ''), username: record.authorName,
          email: '', status: 'active' }
      : ({ id: '', username: '未知', email: '', status: 'active' } as User),
    reviewerId: record.reviewerId ? String(record.reviewerId) : '',
    reviewer: record.reviewerName
      ? { id: String(record.reviewerId || ''), username: record.reviewerName,
          email: '', status: 'active' }
      : undefined,
    status,
    reviewRound: record.reviewRound,
    comment: record.reviewComment || undefined,
    createdAt: record.createdAt,
    reviewedAt: record.reviewedAt || undefined,
    categoryId: record.categoryId != null ? String(record.categoryId) : undefined,
    categoryName: record.categoryName || undefined,
  };
}

export const reviewService = {
  // 获取审核任务列表
  getReviewTasks: async (params?: {
      status?: string; page?: number; pageSize?: number;
      authorId?: string; keyword?: string }) => {
    const response = await http.get<BackendPageResult>(
        '/document/review/tasks', { params });
    return {
      list: (response as unknown as BackendPageResult).records.map(mapToReviewTask),
      total: (response as unknown as BackendPageResult).total,
    };
  },

  // 获取我的被驳回文档
  getMyRejectedDocuments: async (params: {
      authorId: string; page?: number; pageSize?: number }) => {
    const requestParams = {
      status: 'rejected',
      authorId: params.authorId,
      page: params.page || 1,
      pageSize: params.pageSize || 12,
    };
    const response = await http.get<BackendPageResult>(
        '/document/review/tasks', { params: requestParams });
    return {
      list: (response as unknown as BackendPageResult).records.map(mapToReviewTask),
      total: (response as unknown as BackendPageResult).total,
    };
  },

  // 获取待审核任务数量
  getPendingCount: () => {
    return http.get<number>('/document/review/tasks/pending-count');
  },

  // 获取审核统计数据
  getReviewStats: () => {
    return http.get<{ pending: number; approved: number; rejected: number }>(
        '/document/review/tasks/stats');
  },

  // 审核文档(通过或驳回)
  reviewDocument: (taskId: string, data: {
      status: 'approved' | 'rejected'; comment?: string }) => {
    return http.post(`/document/review/tasks/${taskId}/review`, data);
  },

  // 批量审核
  batchReview: (taskIds: string[], data: {
      status: 'approved' | 'rejected'; comment?: string }) => {
    return http.post('/document/review/tasks/batch-review',
        { taskIds, ...data });
  },

  // 提交文档审核
  submitForReview: (documentId: string) => {
    return http.post(`/document/review/submit/${documentId}`);
  },

  // 获取审核历史
  getReviewHistory: async (documentId: string) => {
    const response = await http.get<BackendReviewRecord[]>(
        `/document/review/documents/${documentId}/history`);
    return (response as unknown as BackendReviewRecord[]).map(mapToReviewTask);
  },
};

9.3.2 ReviewPage前端页面

审核管理页面提供三个Tab(待审核/已通过/已驳回),支持搜索、筛选、单条审核和批量审核:

import React, { useEffect, useState, useMemo, useCallback } from 'react';
import { Card, Button, Space, Tag, Typography, Row, Col,
  Table, Input, message, Modal, Popconfirm } from 'antd';
import {
  CheckOutlined, CloseOutlined, EyeOutlined, SearchOutlined,
  ClockCircleOutlined, CheckCircleOutlined, ExclamationCircleOutlined,
} from '@ant-design/icons';
import { reviewService } from '@/services';
import { ReviewTask } from '@/types';
import dayjs from 'dayjs';

// 状态元数据配置
const statusMeta = {
  pending:  { label: '待审核', color: '#f59e0b', icon: <ClockCircleOutlined /> },
  approved: { label: '已通过', color: '#10b981', icon: <CheckCircleOutlined /> },
  rejected: { label: '已驳回', color: '#ef4444', icon: <ExclamationCircleOutlined /> },
};

export const ReviewPage: React.FC = () => {
  const [tasks, setTasks] = useState<ReviewTask[]>([]);
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState({ pending: 0, approved: 0, rejected: 0 });
  const [activeTab, setActiveTab] = useState('pending');

  // 加载数据
  const loadData = useCallback(async (status: string) => {
    setLoading(true);
    try {
      const [taskRes, statsRes] = await Promise.all([
        reviewService.getReviewTasks({ status, page: 1, pageSize: 100 }),
        reviewService.getReviewStats(),
      ]);
      setTasks(taskRes.list || []);
      setStats(statsRes || { pending: 0, approved: 0, rejected: 0 });
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { loadData('pending'); }, [loadData]);

  // 审核通过
  const handleApprove = async (task: ReviewTask) => {
    await reviewService.reviewDocument(task.id, { status: 'approved' });
    message.success('审核已通过');
    loadData(activeTab);
  };

  // 审核驳回(需填写驳回原因)
  const handleReject = async (task: ReviewTask, comment: string) => {
    if (!comment.trim()) return message.warning('驳回时请填写审核意见');
    await reviewService.reviewDocument(task.id,
        { status: 'rejected', comment });
    message.success('已驳回');
    loadData(activeTab);
  };

  // 批量通过
  const handleBatchApprove = async () => {
    const pendingTasks = tasks.filter((t) => t.status === 'pending');
    if (!pendingTasks.length) return message.warning('没有待审核的任务');
    await reviewService.batchReview(pendingTasks.map((t) => t.id),
        { status: 'approved' });
    message.success(`已批量通过 ${pendingTasks.length} 个任务`);
    loadData(activeTab);
  };

  // 表格列定义
  const columns = [
    { title: '文档标题', dataIndex: 'documentTitle', width: 280,
      render: (title: string, record: ReviewTask) => (
        <a onClick={() => window.open(`/documents/${record.documentId}`, '_blank')}>
          {title}
        </a>
      ),
    },
    { title: '作者', dataIndex: ['documentAuthor', 'username'], width: 100 },
    { title: '状态', dataIndex: 'status', width: 90,
      render: (status: string) => {
        const meta = statusMeta[status as keyof typeof statusMeta];
        return <Tag color={meta.color}>{meta.label}</Tag>;
      },
    },
    { title: '轮次', dataIndex: 'reviewRound', width: 60 },
    { title: '提交时间', dataIndex: 'createdAt', width: 160,
      render: (t: string) => dayjs(t).fromNow(),
    },
    { title: '操作', key: 'action', width: 180,
      render: (_: any, record: ReviewTask) => (
        <Space>
          <Button size="small" icon={<EyeOutlined />}
            onClick={() => window.open(`/documents/${record.documentId}`, '_blank')}>
            预览
          </Button>
          {record.status === 'pending' && (
            <>
              <Popconfirm title="确认通过该文档?"
                  onConfirm={() => handleApprove(record)}>
                <Button size="small" type="link" icon={<CheckOutlined />}
                    style={{ color: '#10b981' }}>通过</Button>
              </Popconfirm>
              <Button size="small" type="link" danger icon={<CloseOutlined />}
                  onClick={() => openRejectModal(record)}>驳回</Button>
            </>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: 16, background: '#f6f7f9', minHeight: '100vh' }}>
      {/* Header + Stats Cards + Filter Bar + Table */}
      {/* ...(完整实现见 ReviewPage.tsx) */}
    </div>
  );
};

9.4 前端提交审核集成

在创建文档和编辑文档页面中集成"提交审核"选项。

创建文档页面(CreateDocumentPage.tsx)

// 发布选项:提交审核 or 保存草稿
const [saveOption, setSaveOption] = useState<'submit_review' | 'draft'>('submit_review');

// 统一的保存函数
const handleSaveDocument = async () => {
  if (saveOption === 'submit_review') {
    await handleSubmitForReview();
  } else {
    await handleSaveDraft();
  }
};

// 提交审核
const handleSubmitForReview = async () => {
  try {
    // 1. 先保存文档为草稿
    const result = await createDocument(documentData);
    // 2. 调用审核服务提交审核
    await reviewService.submitForReview(result.id);
    message.success('文档已提交审核!');
    navigate('/documents');
  } catch (error) {
    message.error('提交审核失败:' + error.message);
  }
};

编辑文档页面(EditDocumentPage.tsx)

const handleSubmitForReview = async () => {
  try {
    // 1. 先更新文档
    await documentService.updateDocument(String(documentId), documentData);
    // 2. 调用审核服务提交审核(支持已发布文档重新审核)
    await reviewService.submitForReview(String(documentId));
    message.success('文档已提交审核!');
    window.open(`/documents/${documentId}`, '_blank');
  } catch (error) {
    message.error('提交审核失败:' + error.message);
  }
};

用户体验设计:

  • 在编辑器中提供两个保存按钮:提交审核(主按钮)和保存草稿(次按钮)
  • 提交审核时做完整的前端表单验证
  • 审核提交成功后自动跳转,避免重复提交

测试

按顺序启动下面这些微服务:

kb-auth-user

kb-document

kb-gateway

启动前端

cd knowledge-base-frontend

npm run dev

浏览器访问文档中心页面:

http://localhost:3003/documents

图片.png

现在其中一个文档进行修改:

图片.png

修改后点击提交文档按钮,在审核管理页面的待审核状态下就能看到这个文档:

图片.png

点击通过之后,在已通过状态下,就能看到该文档:

图片.png

总结

本文详细介绍了文档审核功能的完整实现,涵盖了从数据库设计到前端页面的全栈开发流程。

已完成功能

功能实现方式说明
提交审核Service + Controller草稿/已发布文档提交审核
审核通过状态变更 + 事件发布文档变为已发布并触发索引
审核驳回状态变更 + 事件发布文档退回草稿并通知作者
审核历史关联查询完整追溯文档审核流
批量审核循环处理 + 事务一次处理多个待审核文档
实时通知RabbitMQ + WebSocket双向通知作者和审核员
孤儿修复自动检测补建修复数据不一致状态
前端页面React + Ant Design审核管理页面含搜索筛选

技术要点

  1. 状态管理:通过枚举统一管理文档状态,NULL表示"待审核"
  2. 事务控制:审核操作均在数据库事务中完成,保证数据一致性
  3. 事件驱动:RabbitMQ 解耦审核逻辑与通知推送,支持跨模块通信
  4. 实时推送:WebSocket STOMP 协议实现点对点 + 广播通知
  5. 数据修复:自动检测并修复孤儿审核记录
  6. 并发安全:乐观锁检查防止重复审核
  7. 优雅降级:消息推送失败不影响审核主流程

通过本文的学习,你应该能够掌握:

  • 文档审核流程的设计和实现
  • RabbitMQ 事件驱动架构的实践
  • WebSocket 实时通知的应用
  • MyBatis Plus 高级查询(子查询、关联查询)
  • RESTful API 的审核接口设计
  • 前端审核管理页面的完整开发

祝你开发顺利!

最后修改:2026 年 10 月 24 日
如果觉得我的文章对你有用,请随意赞赏