"...git@gitlab.ruzhoukj.com:wujipeng/practical_train.git" did not exist on "381a8f9f688643c23e4c2474b35e33a93fbe7aa7"
Commit 9fc77652 authored by wujipeng's avatar wujipeng
Browse files

管理员-题库管理-理论题库

parent 5fe1aba7
...@@ -13,6 +13,9 @@ public interface BsFileService extends IService<BsFileEntity> { ...@@ -13,6 +13,9 @@ public interface BsFileService extends IService<BsFileEntity> {
/** 将文件保存到磁盘并持久化文件元数据。 */ /** 将文件保存到磁盘并持久化文件元数据。 */
BsFileEntity uploadFile(MultipartFile file) ; BsFileEntity uploadFile(MultipartFile file) ;
/** 保存服务端生成的Excel等字节内容,并登记到统一文件表。 */
BsFileEntity saveGeneratedFile(String fileName, byte[] content);
/** 以附件方式流式输出文件。 */ /** 以附件方式流式输出文件。 */
void downloadFile(Integer id); void downloadFile(Integer id);
} }
package com.platform.business.service;
import com.platform.business.model.dto.TheoreticalLibraryBatchDTO;
import com.platform.business.model.dto.TheoreticalLibraryBatchStatusDTO;
import com.platform.business.model.dto.TheoreticalLibraryBatchTransferDTO;
import com.platform.business.model.dto.TheoreticalLibraryNodeMoveDTO;
import com.platform.business.model.dto.TheoreticalLibraryNodeSaveDTO;
import com.platform.business.model.dto.TheoreticalLibraryQuestionQueryDTO;
import com.platform.business.model.dto.TheoreticalLibraryQuestionSaveDTO;
import com.platform.business.model.entity.TheoreticalLibraryNodeEntity;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.TheoreticalLibraryNodeVO;
import com.platform.business.model.vo.TheoreticalLibraryQuestionVO;
import java.util.List;
/** 管理员端理论题库完整业务接口。 */
public interface TheoreticalLibraryAdminService {
List<TheoreticalLibraryNodeVO> tree(String bankType, String keyword);
List<TheoreticalLibraryNodeEntity> flatNodes(String bankType);
TheoreticalLibraryNodeVO createNode(TheoreticalLibraryNodeSaveDTO body, UserEntity admin);
TheoreticalLibraryNodeVO updateNode(String id, TheoreticalLibraryNodeSaveDTO body);
Boolean moveNode(String id, TheoreticalLibraryNodeMoveDTO body);
Boolean changeNodeStatus(String id, Integer status);
Boolean deleteNode(String id, boolean cascade);
List<TheoreticalLibraryQuestionVO> page(TheoreticalLibraryQuestionQueryDTO query);
List<String> filteredIds(TheoreticalLibraryQuestionQueryDTO query);
TheoreticalLibraryQuestionVO detail(String id);
TheoreticalLibraryQuestionVO createQuestion(TheoreticalLibraryQuestionSaveDTO body,
UserEntity admin);
TheoreticalLibraryQuestionVO updateQuestion(String id,
TheoreticalLibraryQuestionSaveDTO body);
TheoreticalLibraryQuestionVO copyQuestion(String id, UserEntity admin);
Boolean deleteQuestion(String id);
Boolean batchStatus(TheoreticalLibraryBatchStatusDTO body);
Boolean batchTransfer(TheoreticalLibraryBatchTransferDTO body);
Boolean batchDelete(TheoreticalLibraryBatchDTO body);
}
package com.platform.business.service;
import com.platform.business.model.dto.TheoreticalLibraryExportDTO;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.TheoreticalLibraryImportResultVO;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
/** 理论题库 Excel 模板、导入、导出和错误明细服务。 */
public interface TheoreticalLibraryExcelService {
void template(String dataType, String bankType, HttpServletResponse response);
TheoreticalLibraryImportResultVO importData(String dataType, String bankType, String mode,
MultipartFile file, UserEntity admin);
void export(TheoreticalLibraryExportDTO body, HttpServletResponse response);
void downloadImportErrors(Integer fileId);
}
...@@ -81,6 +81,49 @@ public class BsFileServiceImpl extends ServiceImpl<BsFileMapper, BsFileEntity> i ...@@ -81,6 +81,49 @@ public class BsFileServiceImpl extends ServiceImpl<BsFileMapper, BsFileEntity> i
} }
} }
@Override
public BsFileEntity saveGeneratedFile(String fileName, byte[] content) {
if (content == null || content.length == 0) {
throw new BusinessException("生成文件内容不能为空");
}
if (content.length > MAX_FILE_SIZE) {
throw new BusinessException("生成文件不能超过500MB");
}
Path target = null;
try {
Path directory = Paths.get(uploadDirectory).toAbsolutePath().normalize();
Files.createDirectories(directory);
String safeName = safeOriginalFilename(fileName);
String storedFilename = UUID.randomUUID().toString().replace("-", "")
+ getExtension(safeName);
target = directory.resolve(storedFilename).normalize();
if (!target.startsWith(directory)) {
throw new BusinessException("文件保存路径非法");
}
Files.write(target, content);
BsFileEntity bsFile = BsFileEntity.builder()
.url(target.toString())
.fileName(safeName)
.delFlag(0)
.build();
if (!save(bsFile)) {
Files.deleteIfExists(target);
throw new BusinessException("文件信息保存失败");
}
return bsFile;
} catch (IOException e) {
if (target != null) {
try {
Files.deleteIfExists(target);
} catch (IOException cleanupException) {
log.warn("生成文件失败后清理临时文件失败:{}", target, cleanupException);
}
}
log.error("生成文件保存失败", e);
throw new BusinessException("生成文件保存失败");
}
}
@Override @Override
public void downloadFile(Integer id) { public void downloadFile(Integer id) {
// getById 会自动附带 del_flag=0 条件,已逻辑删除的文件不可下载。 // getById 会自动附带 del_flag=0 条件,已逻辑删除的文件不可下载。
......
...@@ -4,8 +4,10 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; ...@@ -4,8 +4,10 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.platform.business.mapper.TheoreticalLibraryMapper; import com.platform.business.mapper.TheoreticalLibraryMapper;
import com.platform.business.mapper.TheoreticalLibraryNodeMapper;
import com.platform.business.model.dto.TheoreticalLibraryDTO; import com.platform.business.model.dto.TheoreticalLibraryDTO;
import com.platform.business.model.entity.TheoreticalLibraryEntity; import com.platform.business.model.entity.TheoreticalLibraryEntity;
import com.platform.business.model.entity.TheoreticalLibraryNodeEntity;
import com.platform.business.model.entity.TheoreticalPaperDetailEntity; import com.platform.business.model.entity.TheoreticalPaperDetailEntity;
import com.platform.business.model.entity.TheoreticalPracticeStudentSimulationDetailEntity; import com.platform.business.model.entity.TheoreticalPracticeStudentSimulationDetailEntity;
import com.platform.business.model.vo.TheoreticalLibraryVO; import com.platform.business.model.vo.TheoreticalLibraryVO;
...@@ -25,7 +27,11 @@ import javax.servlet.http.HttpServletResponse; ...@@ -25,7 +27,11 @@ import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
...@@ -38,6 +44,9 @@ import java.util.regex.Pattern; ...@@ -38,6 +44,9 @@ import java.util.regex.Pattern;
*/ */
@Service @Service
public class TheoreticalLibraryServiceImpl extends ServiceImpl<TheoreticalLibraryMapper, TheoreticalLibraryEntity> implements TheoreticalLibraryService { public class TheoreticalLibraryServiceImpl extends ServiceImpl<TheoreticalLibraryMapper, TheoreticalLibraryEntity> implements TheoreticalLibraryService {
@javax.annotation.Resource
private TheoreticalLibraryNodeMapper theoreticalLibraryNodeMapper;
@Override @Override
public void removeDirtyData() { public void removeDirtyData() {
baseMapper.removeDirtyData(); baseMapper.removeDirtyData();
...@@ -280,6 +289,8 @@ public class TheoreticalLibraryServiceImpl extends ServiceImpl<TheoreticalLibrar ...@@ -280,6 +289,8 @@ public class TheoreticalLibraryServiceImpl extends ServiceImpl<TheoreticalLibrar
saveBatch(theoreticalLibraryList); saveBatch(theoreticalLibraryList);
//删除脏数据 //删除脏数据
removeDirtyData(); removeDirtyData();
// 旧竞赛模板仍由本入口导入;同步新节点和管理字段,保证新旧页面数据一致。
synchronizeImportedScope(scope);
return Result.success("导入成功"); return Result.success("导入成功");
} }
} }
...@@ -491,10 +502,118 @@ public class TheoreticalLibraryServiceImpl extends ServiceImpl<TheoreticalLibrar ...@@ -491,10 +502,118 @@ public class TheoreticalLibraryServiceImpl extends ServiceImpl<TheoreticalLibrar
saveBatch(theoreticalLibraryList); saveBatch(theoreticalLibraryList);
//删除脏数据 //删除脏数据
removeDirtyData(); removeDirtyData();
// 旧职级模板导入后补齐六级树及新字段,旧接口无需感知新表结构。
synchronizeImportedScope(scope);
return Result.success("导入成功"); return Result.success("导入成功");
} }
} }
/**
* 将旧模板刚导入的题目投影到新版层级表。
*
* <p>方法只处理指定 scope,并使用“父节点+名称”缓存避免同一次导入反复查库。
* 节点编码采用稳定哈希,重复导入会复用原节点;题目仍保留旧层级名称供组卷查询。</p>
*/
private void synchronizeImportedScope(String scope) {
List<TheoreticalLibraryEntity> questions = list(
new LambdaQueryWrapper<TheoreticalLibraryEntity>()
.eq(TheoreticalLibraryEntity::getScope, scope)
.eq(TheoreticalLibraryEntity::getIsProblem, true));
Map<String, TheoreticalLibraryNodeEntity> cache = new HashMap<>();
boolean competition = "技能竞赛".equals(scope);
for (TheoreticalLibraryEntity question : questions) {
TheoreticalLibraryNodeEntity leaf;
if (competition) {
TheoreticalLibraryNodeEntity competitionNode = ensureLegacyNode(cache, "COMP", "0",
"COMPETITION", fallback(question.getFirstLevelName(), "技能竞赛"), 10);
TheoreticalLibraryNodeEntity category = ensureLegacyNode(cache, "COMP",
competitionNode.getId(), "CATEGORY",
fallback(question.getSecondLevelName(), "未分类"), 10);
leaf = ensureLegacyNode(cache, "COMP", category.getId(), "DIRECTION",
fallback(question.getThirdLevelName(), "未分类方向"), 10);
question.setBankType("COMP");
} else {
String craftName = scope != null && (scope.startsWith("污水") || scope.startsWith("污泥"))
? scope.substring(0, 2) : fallback(scope, "其他工艺");
String levelName = scope != null && scope.length() > craftName.length()
? scope.substring(craftName.length()) : "未分级";
TheoreticalLibraryNodeEntity craft = ensureLegacyNode(cache, "JOB", "0",
"CRAFT", craftName, 10);
TheoreticalLibraryNodeEntity level = ensureLegacyNode(cache, "JOB", craft.getId(),
"LEVEL", levelName, 10);
TheoreticalLibraryNodeEntity chapter = ensureLegacyNode(cache, "JOB", level.getId(),
"CHAPTER", fallback(question.getFirstLevelName(), "未分类章"), 10);
TheoreticalLibraryNodeEntity section = ensureLegacyNode(cache, "JOB", chapter.getId(),
"SECTION", fallback(question.getSecondLevelName(), "未分类节"), 10);
TheoreticalLibraryNodeEntity topic = ensureLegacyNode(cache, "JOB", section.getId(),
"TOPIC", fallback(question.getThirdLevelName(), "未分类目"), 10);
leaf = ensureLegacyNode(cache, "JOB", topic.getId(), "POINT",
fallback(question.getFourthLevelName(), "未分类知识点"), 10);
question.setBankType("JOB");
}
question.setNodeId(leaf.getId());
question.setStatus(1);
question.setDifficulty("MEDIUM");
question.setScore(defaultScore(question.getType()));
question.setParticipate(question.getParticipate() == null || question.getParticipate());
question.setCreateUserName("旧格式导入");
question.setCreateTime(question.getCreateTime() == null ? new Date() : question.getCreateTime());
question.setUpdateTime(new Date());
updateById(question);
}
}
/** 查找或创建旧数据回填节点,数据库唯一索引承担并发场景的最终保护。 */
private TheoreticalLibraryNodeEntity ensureLegacyNode(
Map<String, TheoreticalLibraryNodeEntity> cache, String bankType, String parentId,
String nodeType, String name, int sortNo) {
String cacheKey = bankType + '|' + parentId + '|' + name;
TheoreticalLibraryNodeEntity cached = cache.get(cacheKey);
if (cached != null) {
return cached;
}
TheoreticalLibraryNodeEntity existing = theoreticalLibraryNodeMapper.selectOne(
new LambdaQueryWrapper<TheoreticalLibraryNodeEntity>()
.eq(TheoreticalLibraryNodeEntity::getBankType, bankType)
.eq(TheoreticalLibraryNodeEntity::getParentId, parentId)
.eq(TheoreticalLibraryNodeEntity::getName, name)
// 历史库可能曾人工创建同名不同编码节点;旧导入只需稳定复用其中一个。
.orderByAsc(TheoreticalLibraryNodeEntity::getSortNo)
.last("LIMIT 1"));
if (existing == null) {
existing = new TheoreticalLibraryNodeEntity();
existing.setBankType(bankType);
existing.setParentId(parentId);
existing.setNodeType(nodeType);
existing.setName(name);
existing.setCode("LEGACY-" + Integer.toHexString(cacheKey.hashCode())
.toUpperCase(Locale.ROOT));
existing.setSortNo(sortNo);
existing.setStatus(1);
existing.setCreateUserName("旧格式导入");
theoreticalLibraryNodeMapper.insert(existing);
}
cache.put(cacheKey, existing);
return existing;
}
private String fallback(String value, String fallback) {
return StringUtils.isNotBlank(value) ? value.trim() : fallback;
}
private double defaultScore(String type) {
if ("判断题".equals(type)) {
return 1D;
}
if ("单选题".equals(type)) {
return 2D;
}
if ("多选题".equals(type)) {
return 3D;
}
return 5D;
}
private String multipleAnswer(String column5) { private String multipleAnswer(String column5) {
// 定义正则表达式匹配中文括号内的A-E字母组合 // 定义正则表达式匹配中文括号内的A-E字母组合
Pattern pattern = Pattern.compile("(([A-E]+))"); Pattern pattern = Pattern.compile("(([A-E]+))");
......
...@@ -35,6 +35,23 @@ ...@@ -35,6 +35,23 @@
AND first_level_name = #{firstLevelName} AND first_level_name = #{firstLevelName}
AND second_level_name = #{secondLevelName} AND second_level_name = #{secondLevelName}
AND participate = true AND participate = true
AND COALESCE(status, 1) = 1
AND (node_id IS NULL OR EXISTS (
SELECT 1
FROM theoretical_library_node n0
LEFT JOIN theoretical_library_node n1 ON n1.id = n0.parent_id
LEFT JOIN theoretical_library_node n2 ON n2.id = n1.parent_id
LEFT JOIN theoretical_library_node n3 ON n3.id = n2.parent_id
LEFT JOIN theoretical_library_node n4 ON n4.id = n3.parent_id
LEFT JOIN theoretical_library_node n5 ON n5.id = n4.parent_id
WHERE n0.id = theoretical_library.node_id
AND n0.status = 1
AND COALESCE(n1.status, 1) = 1
AND COALESCE(n2.status, 1) = 1
AND COALESCE(n3.status, 1) = 1
AND COALESCE(n4.status, 1) = 1
AND COALESCE(n5.status, 1) = 1
))
ORDER BY RAND() ORDER BY RAND()
LIMIT #{count} LIMIT #{count}
</select> </select>
...@@ -63,6 +80,19 @@ ...@@ -63,6 +80,19 @@
AND first_level_name = #{firstLevelName} AND first_level_name = #{firstLevelName}
AND second_level_name = #{secondLevelName} AND second_level_name = #{secondLevelName}
AND participate = true AND participate = true
AND COALESCE(status, 1) = 1
AND (node_id IS NULL OR EXISTS (
SELECT 1 FROM theoretical_library_node n0
LEFT JOIN theoretical_library_node n1 ON n1.id = n0.parent_id
LEFT JOIN theoretical_library_node n2 ON n2.id = n1.parent_id
LEFT JOIN theoretical_library_node n3 ON n3.id = n2.parent_id
LEFT JOIN theoretical_library_node n4 ON n4.id = n3.parent_id
LEFT JOIN theoretical_library_node n5 ON n5.id = n4.parent_id
WHERE n0.id = theoretical_library.node_id
AND n0.status = 1 AND COALESCE(n1.status, 1) = 1
AND COALESCE(n2.status, 1) = 1 AND COALESCE(n3.status, 1) = 1
AND COALESCE(n4.status, 1) = 1 AND COALESCE(n5.status, 1) = 1
))
ORDER BY RAND() ORDER BY RAND()
LIMIT #{count} LIMIT #{count}
</select> </select>
...@@ -142,15 +172,104 @@ ...@@ -142,15 +172,104 @@
AND first_level_name = #{firstLevelName} AND first_level_name = #{firstLevelName}
AND second_level_name = #{secondLevelName} AND second_level_name = #{secondLevelName}
AND participate = true AND participate = true
AND COALESCE(status, 1) = 1
AND (node_id IS NULL OR EXISTS (
SELECT 1 FROM theoretical_library_node n0
LEFT JOIN theoretical_library_node n1 ON n1.id = n0.parent_id
LEFT JOIN theoretical_library_node n2 ON n2.id = n1.parent_id
LEFT JOIN theoretical_library_node n3 ON n3.id = n2.parent_id
LEFT JOIN theoretical_library_node n4 ON n4.id = n3.parent_id
LEFT JOIN theoretical_library_node n5 ON n5.id = n4.parent_id
WHERE n0.id = theoretical_library.node_id
AND n0.status = 1 AND COALESCE(n1.status, 1) = 1
AND COALESCE(n2.status, 1) = 1 AND COALESCE(n3.status, 1) = 1
AND COALESCE(n4.status, 1) = 1 AND COALESCE(n5.status, 1) = 1
))
ORDER BY RAND() ORDER BY RAND()
LIMIT #{count} LIMIT #{count}
</select> </select>
<!--
学员题库初始化仍需要旧的“章+节+两位序号”结构。新管理端不再维护旧伪层级行,
因此这里从固定六级节点反向投影为旧实体,保持调用方无需改动。
-->
<select id="groupByChapter" resultType="com.platform.business.model.entity.TheoreticalLibraryEntity"> <select id="groupByChapter" resultType="com.platform.business.model.entity.TheoreticalLibraryEntity">
SELECT CONCAT(craft.name, grade.name) AS scope,
chapter.name AS first_level_name,
section.name AS second_level_name,
CONCAT(
GREATEST(0, FLOOR(COALESCE(chapter.sort_no, 10) / 10) - 1),
GREATEST(1, FLOOR(COALESCE(section.sort_no, 10) / 10))
) AS sequence
FROM theoretical_library_node section
INNER JOIN theoretical_library_node chapter ON chapter.id = section.parent_id
INNER JOIN theoretical_library_node grade ON grade.id = chapter.parent_id
INNER JOIN theoretical_library_node craft ON craft.id = grade.parent_id
WHERE section.bank_type = 'JOB'
AND section.node_type = 'SECTION'
AND CONCAT(craft.name, grade.name) = #{level}
ORDER BY chapter.sort_no, section.sort_no
</select>
<sql id="adminQuestionWhere">
WHERE q.is_problem = TRUE
<if test="query.bankType != null and query.bankType != ''">
AND q.bank_type = #{query.bankType}
</if>
<if test="query.nodeIds != null and query.nodeIds.size() > 0">
AND q.node_id IN
<foreach collection="query.nodeIds" item="nodeId" open="(" separator="," close=")">
#{nodeId}
</foreach>
</if>
<if test="query.type != null and query.type != ''">
AND q.type = #{query.type}
</if>
<if test="query.keyword != null and query.keyword != ''">
AND (q.problem LIKE CONCAT('%', #{query.keyword}, '%')
OR q.code LIKE CONCAT('%', #{query.keyword}, '%')
OR q.keywords LIKE CONCAT('%', #{query.keyword}, '%'))
</if>
<if test="query.status != null">
AND COALESCE(q.status, 1) = #{query.status}
</if>
<if test="query.createStart != null">
AND q.create_time <![CDATA[>=]]> #{query.createStart}
</if>
<if test="query.createEnd != null">
AND q.create_time <![CDATA[<]]> DATE_ADD(#{query.createEnd}, INTERVAL 1 DAY)
</if>
</sql>
<select id="selectAdminQuestions" resultType="com.platform.business.model.vo.TheoreticalLibraryQuestionVO">
SELECT q.*
FROM theoretical_library q
<include refid="adminQuestionWhere"/>
ORDER BY q.create_time DESC, q.id DESC
</select>
<select id="selectAdminQuestionIds" resultType="java.lang.String">
SELECT q.id
FROM theoretical_library q
<include refid="adminQuestionWhere"/>
ORDER BY q.create_time DESC, q.id DESC
</select>
<select id="selectQuestionCounts" resultType="com.platform.business.model.vo.TheoreticalLibraryNodeCountVO">
SELECT node_id AS nodeId, COUNT(*) AS questionCount
FROM theoretical_library
WHERE is_problem = TRUE
AND bank_type = #{bankType}
AND node_id IS NOT NULL
GROUP BY node_id
</select>
<select id="selectQuestionForUpdate"
resultType="com.platform.business.model.entity.TheoreticalLibraryEntity">
SELECT * SELECT *
FROM theoretical_library FROM theoretical_library
WHERE sequence IS NOT NULL WHERE id = #{id}
AND CHAR_LENGTH(sequence) = 2 AND is_problem = TRUE
and scope = #{level} FOR UPDATE
</select> </select>
</mapper> </mapper>
-- 管理员端“题库管理-理论题库”增量数据库脚本(MySQL 5.7+/8.0)。
--
-- 执行原则:
-- 1. 只扩展 theoretical_library,不删除历史题目和旧的 is_problem=false 层级行。
-- 2. 新建规范化节点表,并把历史题目回填到六级职级树或三级竞赛树。
-- 3. 所有 DDL 先检查 information_schema,可在开发、测试和生产重复执行。
-- 4. 沿用项目现状不建立外键;级联删除、层级约束和兼容字段同步由事务服务保证。
CREATE TABLE IF NOT EXISTS theoretical_library_node (
id VARCHAR(64) NOT NULL COMMENT '节点ID',
bank_type VARCHAR(16) NOT NULL COMMENT 'JOB职级题库/COMP竞赛题库',
parent_id VARCHAR(64) NOT NULL DEFAULT '0' COMMENT '上级节点,0表示根',
node_type VARCHAR(32) NOT NULL COMMENT 'CRAFT/LEVEL/CHAPTER/SECTION/TOPIC/POINT等',
name VARCHAR(200) NOT NULL COMMENT '节点名称',
code VARCHAR(64) NOT NULL COMMENT '同一父节点下唯一编码',
sort_no INT NOT NULL DEFAULT 10 COMMENT '同级排序号',
status TINYINT NOT NULL DEFAULT 1 COMMENT '1启用,0禁用',
remark VARCHAR(500) NULL COMMENT '备注',
create_user_id VARCHAR(64) NULL COMMENT '创建人用户ID',
create_user_name VARCHAR(100) NULL COMMENT '创建人姓名快照',
create_time DATETIME NULL COMMENT '创建时间',
update_time DATETIME NULL COMMENT '最后更新时间',
PRIMARY KEY (id),
UNIQUE KEY uk_tl_node_parent_code (bank_type, parent_id, code),
KEY idx_tl_node_parent_sort (bank_type, parent_id, sort_no, id),
KEY idx_tl_node_name (bank_type, name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='理论题库层级节点';
DELIMITER $$
DROP PROCEDURE IF EXISTS migrate_theoretical_library_management$$
CREATE PROCEDURE migrate_theoretical_library_management()
BEGIN
IF NOT EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = 'theoretical_library'
AND column_name = 'bank_type') THEN
ALTER TABLE theoretical_library ADD COLUMN bank_type VARCHAR(16) NULL
COMMENT 'JOB职级题库/COMP竞赛题库' AFTER participate;
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = 'theoretical_library'
AND column_name = 'node_id') THEN
ALTER TABLE theoretical_library ADD COLUMN node_id VARCHAR(64) NULL
COMMENT '末级层级节点ID' AFTER bank_type;
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = 'theoretical_library'
AND column_name = 'score') THEN
ALTER TABLE theoretical_library ADD COLUMN score DECIMAL(10,2) NULL
COMMENT '题目默认分值' AFTER node_id;
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = 'theoretical_library'
AND column_name = 'difficulty') THEN
ALTER TABLE theoretical_library ADD COLUMN difficulty VARCHAR(16) NULL
COMMENT 'EASY/MEDIUM/HARD' AFTER score;
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = 'theoretical_library'
AND column_name = 'status') THEN
ALTER TABLE theoretical_library ADD COLUMN status TINYINT NULL
COMMENT '1启用,0禁用' AFTER difficulty;
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = 'theoretical_library'
AND column_name = 'keywords') THEN
ALTER TABLE theoretical_library ADD COLUMN keywords TEXT NULL
COMMENT '关键词JSON数组' AFTER status;
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = 'theoretical_library'
AND column_name = 'analysis') THEN
ALTER TABLE theoretical_library ADD COLUMN analysis TEXT NULL
COMMENT '题目解析' AFTER keywords;
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = 'theoretical_library'
AND column_name = 'create_user_id') THEN
ALTER TABLE theoretical_library ADD COLUMN create_user_id VARCHAR(64) NULL
COMMENT '创建人用户ID' AFTER analysis;
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = 'theoretical_library'
AND column_name = 'create_user_name') THEN
ALTER TABLE theoretical_library ADD COLUMN create_user_name VARCHAR(100) NULL
COMMENT '创建人姓名快照' AFTER create_user_id;
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = 'theoretical_library'
AND column_name = 'create_time') THEN
ALTER TABLE theoretical_library ADD COLUMN create_time DATETIME NULL
COMMENT '创建时间' AFTER create_user_name;
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = 'theoretical_library'
AND column_name = 'update_time') THEN
ALTER TABLE theoretical_library ADD COLUMN update_time DATETIME NULL
COMMENT '最后更新时间' AFTER create_time;
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.statistics
WHERE table_schema = DATABASE() AND table_name = 'theoretical_library'
AND index_name = 'idx_tl_admin_page') THEN
ALTER TABLE theoretical_library
ADD INDEX idx_tl_admin_page (bank_type, node_id, status, create_time, id);
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.statistics
WHERE table_schema = DATABASE() AND table_name = 'theoretical_library'
AND index_name = 'idx_tl_bank_code') THEN
ALTER TABLE theoretical_library ADD INDEX idx_tl_bank_code (bank_type, code);
END IF;
END$$
CALL migrate_theoretical_library_management()$$
DROP PROCEDURE IF EXISTS migrate_theoretical_library_management$$
DELIMITER ;
-- 先统一历史管理字段。旧记录没有时间时以脚本执行时间作为可排序的迁移时间。
UPDATE theoretical_library
SET bank_type = COALESCE(bank_type, CASE WHEN scope = '技能竞赛' THEN 'COMP' ELSE 'JOB' END),
score = COALESCE(score, CASE type
WHEN '判断题' THEN 1.00 WHEN '单选题' THEN 2.00 WHEN '多选题' THEN 3.00 ELSE 5.00 END),
difficulty = COALESCE(NULLIF(difficulty, ''), 'MEDIUM'),
status = COALESCE(status, 1),
participate = COALESCE(participate, TRUE),
create_user_name = COALESCE(NULLIF(create_user_name, ''), '历史数据迁移'),
create_time = COALESCE(create_time, NOW()),
update_time = COALESCE(update_time, create_time, NOW())
WHERE is_problem = TRUE;
-- 临时表只保存题目路径。固定 ID 由完整路径 MD5 生成,脚本重复执行时会命中原节点。
DROP TEMPORARY TABLE IF EXISTS tmp_tl_path;
CREATE TEMPORARY TABLE tmp_tl_path AS
SELECT id AS question_id,
CASE WHEN scope = '技能竞赛' THEN 'COMP' ELSE 'JOB' END AS bank_type,
CASE
WHEN scope LIKE '污水%' OR scope LIKE '污泥%' THEN LEFT(scope, 2)
WHEN scope = '技能竞赛' THEN NULL
ELSE COALESCE(NULLIF(TRIM(scope), ''), '其他工艺')
END AS craft_name,
CASE
WHEN scope LIKE '污水%' OR scope LIKE '污泥%' THEN
COALESCE(NULLIF(SUBSTRING(scope, 3), ''), '未分级')
WHEN scope = '技能竞赛' THEN NULL
ELSE '未分级'
END AS level_name,
COALESCE(NULLIF(TRIM(first_level_name), ''),
CASE WHEN scope = '技能竞赛' THEN '技能竞赛' ELSE '未分类章' END) AS level1_name,
COALESCE(NULLIF(TRIM(second_level_name), ''), '未分类') AS level2_name,
COALESCE(NULLIF(TRIM(third_level_name), ''),
CASE WHEN scope = '技能竞赛' THEN '未分类方向' ELSE '未分类目' END) AS level3_name,
COALESCE(NULLIF(TRIM(fourth_level_name), ''), '未分类知识点') AS level4_name,
CAST(NULL AS CHAR(32)) AS craft_id,
CAST(NULL AS CHAR(32)) AS level_id,
CAST(NULL AS CHAR(32)) AS level1_id,
CAST(NULL AS CHAR(32)) AS level2_id,
CAST(NULL AS CHAR(32)) AS level3_id,
CAST(NULL AS CHAR(32)) AS level4_id
FROM theoretical_library
WHERE is_problem = TRUE;
UPDATE tmp_tl_path
SET craft_id = MD5(CONCAT('JOB|CRAFT|', craft_name)),
level_id = MD5(CONCAT('JOB|LEVEL|', craft_name, '|', level_name)),
level1_id = MD5(CONCAT(bank_type, '|L1|', COALESCE(craft_name, ''), '|',
COALESCE(level_name, ''), '|', level1_name)),
level2_id = MD5(CONCAT(bank_type, '|L2|', COALESCE(craft_name, ''), '|',
COALESCE(level_name, ''), '|', level1_name, '|', level2_name)),
level3_id = MD5(CONCAT(bank_type, '|L3|', COALESCE(craft_name, ''), '|',
COALESCE(level_name, ''), '|', level1_name, '|', level2_name,
'|', level3_name)),
level4_id = MD5(CONCAT('JOB|L4|', craft_name, '|', level_name, '|', level1_name,
'|', level2_name, '|', level3_name, '|', level4_name));
-- 职级题库:工艺 → 职级 → 章 → 节 → 目 → 点。
INSERT IGNORE INTO theoretical_library_node
(id, bank_type, parent_id, node_type, name, code, sort_no, status,
create_user_name, create_time, update_time)
SELECT DISTINCT craft_id, 'JOB', '0', 'CRAFT', craft_name,
CONCAT('LEGACY-', UPPER(LEFT(craft_id, 12))), 10, 1, '历史数据迁移', NOW(), NOW()
FROM tmp_tl_path WHERE bank_type = 'JOB';
INSERT IGNORE INTO theoretical_library_node
(id, bank_type, parent_id, node_type, name, code, sort_no, status,
create_user_name, create_time, update_time)
SELECT DISTINCT level_id, 'JOB', craft_id, 'LEVEL', level_name,
CONCAT('LEGACY-', UPPER(LEFT(level_id, 12))), 10, 1, '历史数据迁移', NOW(), NOW()
FROM tmp_tl_path WHERE bank_type = 'JOB';
INSERT IGNORE INTO theoretical_library_node
(id, bank_type, parent_id, node_type, name, code, sort_no, status,
create_user_name, create_time, update_time)
SELECT DISTINCT level1_id, 'JOB', level_id, 'CHAPTER', level1_name,
CONCAT('LEGACY-', UPPER(LEFT(level1_id, 12))), 10, 1, '历史数据迁移', NOW(), NOW()
FROM tmp_tl_path WHERE bank_type = 'JOB';
INSERT IGNORE INTO theoretical_library_node
(id, bank_type, parent_id, node_type, name, code, sort_no, status,
create_user_name, create_time, update_time)
SELECT DISTINCT level2_id, 'JOB', level1_id, 'SECTION', level2_name,
CONCAT('LEGACY-', UPPER(LEFT(level2_id, 12))), 10, 1, '历史数据迁移', NOW(), NOW()
FROM tmp_tl_path WHERE bank_type = 'JOB';
INSERT IGNORE INTO theoretical_library_node
(id, bank_type, parent_id, node_type, name, code, sort_no, status,
create_user_name, create_time, update_time)
SELECT DISTINCT level3_id, 'JOB', level2_id, 'TOPIC', level3_name,
CONCAT('LEGACY-', UPPER(LEFT(level3_id, 12))), 10, 1, '历史数据迁移', NOW(), NOW()
FROM tmp_tl_path WHERE bank_type = 'JOB';
INSERT IGNORE INTO theoretical_library_node
(id, bank_type, parent_id, node_type, name, code, sort_no, status,
create_user_name, create_time, update_time)
SELECT DISTINCT level4_id, 'JOB', level3_id, 'POINT', level4_name,
CONCAT('LEGACY-', UPPER(LEFT(level4_id, 12))), 10, 1, '历史数据迁移', NOW(), NOW()
FROM tmp_tl_path WHERE bank_type = 'JOB';
-- 竞赛题库:竞赛类型 → 题目分类 → 题目方向。
INSERT IGNORE INTO theoretical_library_node
(id, bank_type, parent_id, node_type, name, code, sort_no, status,
create_user_name, create_time, update_time)
SELECT DISTINCT level1_id, 'COMP', '0', 'COMPETITION', level1_name,
CONCAT('LEGACY-', UPPER(LEFT(level1_id, 12))), 10, 1, '历史数据迁移', NOW(), NOW()
FROM tmp_tl_path WHERE bank_type = 'COMP';
INSERT IGNORE INTO theoretical_library_node
(id, bank_type, parent_id, node_type, name, code, sort_no, status,
create_user_name, create_time, update_time)
SELECT DISTINCT level2_id, 'COMP', level1_id, 'CATEGORY', level2_name,
CONCAT('LEGACY-', UPPER(LEFT(level2_id, 12))), 10, 1, '历史数据迁移', NOW(), NOW()
FROM tmp_tl_path WHERE bank_type = 'COMP';
INSERT IGNORE INTO theoretical_library_node
(id, bank_type, parent_id, node_type, name, code, sort_no, status,
create_user_name, create_time, update_time)
SELECT DISTINCT level3_id, 'COMP', level2_id, 'DIRECTION', level3_name,
CONCAT('LEGACY-', UPPER(LEFT(level3_id, 12))), 10, 1, '历史数据迁移', NOW(), NOW()
FROM tmp_tl_path WHERE bank_type = 'COMP';
UPDATE theoretical_library q
INNER JOIN tmp_tl_path p ON p.question_id = q.id
SET q.bank_type = p.bank_type,
q.node_id = CASE WHEN p.bank_type = 'COMP' THEN p.level3_id ELSE p.level4_id END,
q.update_time = COALESCE(q.update_time, NOW());
DROP TEMPORARY TABLE IF EXISTS tmp_tl_path;
-- 只读核查:执行后若返回数据,应先修复再开放管理端页面。
SELECT q.id, q.scope, q.code, q.problem
FROM theoretical_library q
LEFT JOIN theoretical_library_node n ON n.id = q.node_id
WHERE q.is_problem = TRUE
AND (q.bank_type NOT IN ('JOB', 'COMP') OR q.node_id IS NULL OR n.id IS NULL);
SELECT bank_type, parent_id, code, COUNT(*) AS duplicate_count
FROM theoretical_library_node
GROUP BY bank_type, parent_id, code
HAVING COUNT(*) > 1;
# 管理员端理论题库管理接口
页面路径为“管理员 → 题库管理 → 理论题库”,接口统一使用
`/theoretical/library/admin` 前缀。所有请求必须携带 `Authorization`,服务端从 JWT
解析用户并校验“管理员”角色。部署前先执行:
```text
practical-business/src/main/resources/sql/theoretical_library_management.sql
```
职级题库 `JOB` 固定为“工艺→职级→章→节→目→点”,竞赛题库 `COMP` 固定为
“竞赛类型→题目分类→题目方向”。节点编码在同题库、同父节点下唯一。
## 1. 层级树与节点维护
- `GET /nodes/tree?bankType=JOB&keyword=污水`:返回嵌套树、完整路径及子树题量。
- `POST /nodes`:新增节点。根节点 `parentId` 传 `0` 或留空;`nodeType` 由服务端根据父节点计算。
- `PUT /nodes/{id}`:编辑名称、编码、排序、状态和备注,不允许改变父节点或题库。
- `PUT /nodes/{id}/move`:请求体 `{"direction":"UP"}` 或 `DOWN`。
- `PUT /nodes/{id}/status`:请求体 `{"status":0}` 或 `1`。
- `DELETE /nodes/{id}?cascade=true`:彻底删除子树及关联试题;未显式传 `true` 会拒绝。
节点新增示例:
```json
{
"bankType": "JOB",
"parentId": "0",
"name": "污水",
"code": "CRAFT-WATER",
"sortNo": 10,
"status": 1,
"remark": "污水处理工艺"
}
```
## 2. 试题查询与维护
题型代码为 `SINGLE`、`MULTI`、`JUDGE`、`FILL`、`SHORT`、`CALC`;难度代码为
`EASY`、`MEDIUM`、`HARD`。
`POST /questions/page` 使用项目统一 `TableDataInfo`:
```json
{
"pageNum": 1,
"pageSize": 10,
"bankType": "JOB",
"nodeId": "末级或任意祖先节点ID",
"type": "SINGLE",
"keyword": "活性污泥",
"status": 1,
"createStart": "2026-08-01",
"createEnd": "2026-08-31"
}
```
选择祖先节点时自动包含全部后代。列表和详情同时返回稳定代码、中文标签、完整层级路径、
结构化选项、`answerText`、关键词数组及 `noExam`。
- `POST /questions/filter-ids`:同一筛选请求,返回页面“全选筛选结果”的 ID,最多 5000 条。
- `GET /questions/{id}`:预览和编辑回显。
- `POST /questions`、`PUT /questions/{id}`:新增或编辑。
- `POST /questions/{id}/copy`:复制为启用的新题,题干追加“(副本)”。
- `DELETE /questions/{id}`:彻底删除单题。
- `PUT /questions/batch/status`:`{"ids":["1"],"status":0}`。
- `PUT /questions/batch/transfer`:`{"ids":["1"],"targetNodeId":"末级节点ID"}`。
- `POST /questions/batch/delete`:`{"ids":["1","2"]}`。
新增单选题示例:
```json
{
"nodeId": "末级知识点ID",
"type": "SINGLE",
"score": 2,
"difficulty": "MEDIUM",
"status": 1,
"noExam": false,
"keywords": ["活性污泥", "重点"],
"stem": "活性污泥法的核心处理单元是?",
"options": [
{"text": "曝气池", "correct": true},
{"text": "消毒池", "correct": false}
],
"analysis": "考查活性污泥法基本流程。"
}
```
选择题只允许 2–5 个选项;单选必须恰好一个正确答案,多选至少两个。判断、填空、简答、
计算题必须提交 `answer`。`noExam=true` 会保存为 `participate=false`,不会参与随机组卷。
## 3. Excel 导入导出
- `GET /templates/{STRUCTURE|QUESTION}?bankType=JOB`:下载导入模板。
- `POST /imports`:`multipart/form-data`,字段为 `dataType`、`bankType`、`mode`、`file`。
`mode` 支持 `ADD` 和 `OVERWRITE`;仅允许 10MB 以内 `.xlsx`。
- 导入返回 `successCount`、`failureCount`、`errorFileId`;失败明细使用
`GET /imports/errors/{fileId}` 下载。
- `POST /exports`:导出层级或试题。
```json
{
"dataType": "QUESTION",
"bankType": "JOB",
"scope": "FILTERED",
"includeAnswer": false,
"query": {
"bankType": "JOB",
"nodeId": "节点ID",
"type": "SINGLE",
"keyword": "污泥"
}
}
```
结构覆盖按“题库+父节点编码路径+编码”匹配;试题覆盖按“题库+题号”匹配。结构文件必须
先放父节点、后放子节点。无答案导出会同时隐藏标准答案和解析。
## 4. 旧接口兼容
原 `/theoretical/library` 分页、旧模板导入、编辑、删除和导出继续保留。旧格式导入完成后
服务端自动创建新节点并回填管理字段。随机组卷和模拟练习仍按原 `scope/章/节` 参数调用,
但只会抽取题目启用、允许组卷且所属节点整条祖先链均启用的数据。
package com.platform.business.controller;
import com.platform.business.model.dto.TheoreticalLibraryBatchDTO;
import com.platform.business.model.dto.TheoreticalLibraryBatchStatusDTO;
import com.platform.business.model.dto.TheoreticalLibraryBatchTransferDTO;
import com.platform.business.model.dto.TheoreticalLibraryExportDTO;
import com.platform.business.model.dto.TheoreticalLibraryNodeMoveDTO;
import com.platform.business.model.dto.TheoreticalLibraryNodeSaveDTO;
import com.platform.business.model.dto.TheoreticalLibraryQuestionQueryDTO;
import com.platform.business.model.dto.TheoreticalLibraryQuestionSaveDTO;
import com.platform.business.model.dto.TheoreticalLibraryStatusDTO;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.TheoreticalLibraryImportResultVO;
import com.platform.business.service.AuthenticatedUserService;
import com.platform.business.service.TheoreticalLibraryAdminService;
import com.platform.business.service.TheoreticalLibraryExcelService;
import com.platform.exception.BusinessException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.util.ReflectionTestUtils;
import java.util.Collections;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** 管理员理论题库控制器的鉴权覆盖和分页边界测试。 */
@ExtendWith(MockitoExtension.class)
class TheoreticalLibraryAdminControllerTest {
@Mock
private TheoreticalLibraryAdminService adminService;
@Mock
private TheoreticalLibraryExcelService excelService;
@Mock
private AuthenticatedUserService authenticatedUserService;
private TheoreticalLibraryAdminController controller;
private MockHttpServletRequest request;
@BeforeEach
void setUp() {
controller = new TheoreticalLibraryAdminController();
ReflectionTestUtils.setField(controller, "adminService", adminService);
ReflectionTestUtils.setField(controller, "excelService", excelService);
ReflectionTestUtils.setField(controller, "authenticatedUserService", authenticatedUserService);
request = new MockHttpServletRequest();
}
@Test
void everyEndpointShouldRequireAdministrator() {
UserEntity admin = new UserEntity();
admin.setId("admin-1");
when(authenticatedUserService.current(request)).thenReturn(admin);
when(adminService.tree("JOB", null)).thenReturn(Collections.emptyList());
when(adminService.page(any())).thenReturn(Collections.emptyList());
when(adminService.filteredIds(any())).thenReturn(Collections.emptyList());
when(excelService.importData(any(), any(), any(), any(), any()))
.thenReturn(new TheoreticalLibraryImportResultVO());
MockHttpServletResponse response = new MockHttpServletResponse();
MockMultipartFile file = new MockMultipartFile("file", "questions.xlsx",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", new byte[]{1});
controller.tree("JOB", null, request);
controller.createNode(new TheoreticalLibraryNodeSaveDTO(), request);
controller.updateNode("n1", new TheoreticalLibraryNodeSaveDTO(), request);
controller.moveNode("n1", new TheoreticalLibraryNodeMoveDTO(), request);
controller.changeNodeStatus("n1", new TheoreticalLibraryStatusDTO(), request);
controller.deleteNode("n1", true, request);
TheoreticalLibraryQuestionQueryDTO query = new TheoreticalLibraryQuestionQueryDTO();
query.setBankType("JOB");
controller.page(query, request);
controller.filteredIds(query, request);
controller.questionDetail("q1", request);
controller.createQuestion(new TheoreticalLibraryQuestionSaveDTO(), request);
controller.updateQuestion("q1", new TheoreticalLibraryQuestionSaveDTO(), request);
controller.copyQuestion("q1", request);
controller.deleteQuestion("q1", request);
controller.batchStatus(new TheoreticalLibraryBatchStatusDTO(), request);
controller.batchTransfer(new TheoreticalLibraryBatchTransferDTO(), request);
controller.batchDelete(new TheoreticalLibraryBatchDTO(), request);
controller.template("QUESTION", "JOB", request, response);
controller.importData("QUESTION", "JOB", "ADD", file, request);
controller.importErrors(1, request);
controller.export(new TheoreticalLibraryExportDTO(), request, response);
verify(authenticatedUserService, times(20)).requireAdmin(admin);
verify(adminService).createNode(any(), org.mockito.ArgumentMatchers.eq(admin));
verify(adminService).createQuestion(any(), org.mockito.ArgumentMatchers.eq(admin));
verify(adminService).copyQuestion("q1", admin);
}
@Test
void pageShouldNormalizeUnsafePagination() {
TheoreticalLibraryQuestionQueryDTO query = new TheoreticalLibraryQuestionQueryDTO();
query.setPageNum(0);
query.setPageSize(1000);
controller.normalizePage(query);
assertEquals(1, query.getPageNum());
assertEquals(100, query.getPageSize());
}
@Test
void nonAdministratorShouldStopBeforeBusinessService() {
UserEntity user = new UserEntity();
when(authenticatedUserService.current(request)).thenReturn(user);
doThrow(new BusinessException("只有管理员可以访问管理端接口"))
.when(authenticatedUserService).requireAdmin(user);
assertThrows(BusinessException.class,
() -> controller.questionDetail("q1", request));
}
}
package com.platform.business.mapper;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.junit.jupiter.api.Test;
import java.io.InputStream;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** 在应用启动前验证题库分页、全选、题量聚合和锁定 SQL 能被 MyBatis 完整解析。 */
class TheoreticalLibraryAdminMapperXmlTest {
@Test
void mapperXmlShouldRegisterAdminStatements() throws Exception {
String resource = "com/platform/business/mapper/TheoreticalLibraryMapper.xml";
Configuration configuration = new Configuration();
try (InputStream input = Resources.getResourceAsStream(resource)) {
new XMLMapperBuilder(input, configuration, resource,
configuration.getSqlFragments()).parse();
}
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.TheoreticalLibraryMapper.selectAdminQuestions"));
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.TheoreticalLibraryMapper.selectAdminQuestionIds"));
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.TheoreticalLibraryMapper.selectQuestionCounts"));
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.TheoreticalLibraryMapper.selectQuestionForUpdate"));
}
}
package com.platform.business.mapper;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** 增量脚本关键 DDL、历史回填和只读核查语句的静态完整性测试。 */
class TheoreticalLibraryManagementSqlTest {
@Test
void migrationShouldBeIdempotentAndBackfillLegacyQuestions() throws Exception {
String sql = new String(Files.readAllBytes(Paths.get(
"src/main/resources/sql/theoretical_library_management.sql")),
StandardCharsets.UTF_8);
assertTrue(sql.contains("CREATE TABLE IF NOT EXISTS theoretical_library_node"));
assertTrue(sql.contains("information_schema.columns"));
assertTrue(sql.contains("CREATE TEMPORARY TABLE tmp_tl_path"));
assertTrue(sql.contains("q.node_id = CASE WHEN p.bank_type = 'COMP'"));
assertTrue(sql.contains("HAVING COUNT(*) > 1"));
}
}
package com.platform.business.service.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.platform.business.mapper.TheoreticalLibraryMapper;
import com.platform.business.mapper.TheoreticalLibraryNodeMapper;
import com.platform.business.model.dto.TheoreticalLibraryOptionDTO;
import com.platform.business.model.dto.TheoreticalLibraryQuestionSaveDTO;
import com.platform.business.model.entity.TheoreticalLibraryNodeEntity;
import com.platform.business.model.vo.TheoreticalLibraryNodeCountVO;
import com.platform.business.model.vo.TheoreticalLibraryNodeVO;
import com.platform.exception.BusinessException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.util.ReflectionTestUtils;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** 管理员理论题库树聚合、级联保护和题型服务端校验测试。 */
@ExtendWith(MockitoExtension.class)
class TheoreticalLibraryAdminServiceImplTest {
@Mock
private TheoreticalLibraryNodeMapper nodeMapper;
@Mock
private TheoreticalLibraryMapper libraryMapper;
private TheoreticalLibraryAdminServiceImpl service;
@BeforeEach
void setUp() {
service = new TheoreticalLibraryAdminServiceImpl();
ReflectionTestUtils.setField(service, "nodeMapper", nodeMapper);
ReflectionTestUtils.setField(service, "libraryMapper", libraryMapper);
ReflectionTestUtils.setField(service, "objectMapper", new ObjectMapper());
}
@Test
void treeSearchShouldKeepAncestorsAndAggregateQuestionCount() {
TheoreticalLibraryNodeEntity craft = node("craft", "0", "CRAFT", "污水", "C-WATER");
TheoreticalLibraryNodeEntity level = node("level", "craft", "LEVEL", "一级", "L-1");
when(nodeMapper.selectList(any())).thenReturn(Arrays.asList(craft, level));
TheoreticalLibraryNodeCountVO count = new TheoreticalLibraryNodeCountVO();
count.setNodeId("level");
count.setQuestionCount(3L);
when(libraryMapper.selectQuestionCounts("JOB")).thenReturn(Collections.singletonList(count));
List<TheoreticalLibraryNodeVO> result = service.tree("JOB", "一级");
assertEquals(1, result.size());
assertEquals("污水", result.get(0).getName());
assertEquals(3L, result.get(0).getQuestionCount());
assertEquals("一级", result.get(0).getChildren().get(0).getName());
}
@Test
void nodeDeleteShouldRequireExplicitCascadeConfirmation() {
when(nodeMapper.selectById("node-1"))
.thenReturn(node("node-1", "0", "CRAFT", "污水", "C-WATER"));
assertThrows(BusinessException.class, () -> service.deleteNode("node-1", false));
verify(libraryMapper, never()).delete(any());
}
@Test
void singleChoiceShouldRejectMoreThanOneCorrectOptionBeforeInsert() {
List<TheoreticalLibraryNodeEntity> path = completeJobPath();
for (TheoreticalLibraryNodeEntity node : path) {
when(nodeMapper.selectById(node.getId())).thenReturn(node);
}
TheoreticalLibraryQuestionSaveDTO body = new TheoreticalLibraryQuestionSaveDTO();
body.setNodeId("point");
body.setType("SINGLE");
body.setScore(2D);
body.setDifficulty("MEDIUM");
body.setStatus(1);
body.setStem("测试题干");
TheoreticalLibraryOptionDTO optionA = option("A", true);
TheoreticalLibraryOptionDTO optionB = option("B", true);
body.setOptions(Arrays.asList(optionA, optionB));
assertThrows(BusinessException.class, () -> service.createQuestion(body, null));
verify(libraryMapper, never()).insert(any());
}
private List<TheoreticalLibraryNodeEntity> completeJobPath() {
return Arrays.asList(
node("craft", "0", "CRAFT", "污水", "CRAFT-WATER"),
node("level", "craft", "LEVEL", "一级", "LEVEL-1"),
node("chapter", "level", "CHAPTER", "第一章", "CH-1"),
node("section", "chapter", "SECTION", "第一节", "SEC-1"),
node("topic", "section", "TOPIC", "第一目", "TOPIC-1"),
node("point", "topic", "POINT", "知识点", "POINT-1"));
}
private TheoreticalLibraryNodeEntity node(String id, String parentId, String type,
String name, String code) {
TheoreticalLibraryNodeEntity node = new TheoreticalLibraryNodeEntity();
node.setId(id);
node.setParentId(parentId);
node.setBankType("JOB");
node.setNodeType(type);
node.setName(name);
node.setCode(code);
node.setSortNo(10);
node.setStatus(1);
return node;
}
private TheoreticalLibraryOptionDTO option(String text, boolean correct) {
TheoreticalLibraryOptionDTO option = new TheoreticalLibraryOptionDTO();
option.setText(text);
option.setCorrect(correct);
return option;
}
}
package com.platform.business.service.impl;
import com.platform.exception.BusinessException;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.mock.web.MockHttpServletResponse;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.ByteArrayInputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
/** Excel 导入入口的格式和文件大小边界测试。 */
class TheoreticalLibraryExcelServiceImplTest {
@Test
void questionTemplateShouldContainStableImportHeaders() throws Exception {
TheoreticalLibraryExcelServiceImpl service = new TheoreticalLibraryExcelServiceImpl();
MockHttpServletResponse response = new MockHttpServletResponse();
service.template("QUESTION", "JOB", response);
try (XSSFWorkbook workbook = new XSSFWorkbook(
new ByteArrayInputStream(response.getContentAsByteArray()))) {
assertEquals("题号", workbook.getSheetAt(0).getRow(0).getCell(0).getStringCellValue());
assertEquals("节点编码路径",
workbook.getSheetAt(0).getRow(0).getCell(1).getStringCellValue());
assertEquals("答案", workbook.getSheetAt(0).getRow(0).getCell(14).getStringCellValue());
}
}
@Test
void importShouldRejectLegacyXlsBeforeReadingWorkbook() {
TheoreticalLibraryExcelServiceImpl service = new TheoreticalLibraryExcelServiceImpl();
MockMultipartFile file = new MockMultipartFile(
"file", "questions.xls", "application/vnd.ms-excel", new byte[]{1});
assertThrows(BusinessException.class,
() -> service.importData("QUESTION", "JOB", "ADD", file, null));
}
@Test
void importShouldRejectFileLargerThanTenMegabytes() {
TheoreticalLibraryExcelServiceImpl service = new TheoreticalLibraryExcelServiceImpl();
MockMultipartFile file = new MockMultipartFile(
"file", "questions.xlsx",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
new byte[10 * 1024 * 1024 + 1]);
assertThrows(BusinessException.class,
() -> service.importData("QUESTION", "JOB", "ADD", file, null));
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment