Commit 1b41cf3f authored by wujipeng's avatar wujipeng
Browse files

优化

parent 34a1862c
......@@ -77,6 +77,8 @@ public class TheoreticalLibraryAdminServiceImpl implements TheoreticalLibraryAdm
if (nodes.isEmpty()) {
return Collections.emptyList();
}
// 组树前先校验父子关系,防止断链节点因找不到父节点而被误当成根节点。
validateNodeHierarchy(normalizedBankType, nodes);
Map<String, Long> directCounts = new HashMap<>();
List<TheoreticalLibraryNodeCountVO> countRows =
......@@ -629,14 +631,18 @@ public class TheoreticalLibraryAdminServiceImpl implements TheoreticalLibraryAdm
vo.setOptions(readOptions(vo));
vo.setAnswerText(displayAnswer(vo));
vo.setNodePath(new ArrayList<>());
if (!StringUtils.hasText(vo.getNodeId()) || nodeMap == null) {
return;
if (!StringUtils.hasText(vo.getBankType()) || !StringUtils.hasText(vo.getNodeId())) {
throw new BusinessException("题目未绑定完整的题库层级,请先执行历史数据补齐");
}
if (nodeMap == null) {
throw new BusinessException("题目所属题库没有可用层级数据,请先执行历史数据补齐");
}
TheoreticalLibraryNodeEntity leaf = nodeMap.get(vo.getNodeId());
if (leaf == null) {
return;
throw new BusinessException("题目绑定的末级节点不存在,请先修复题库层级数据");
}
List<TheoreticalLibraryNodeEntity> entityPath = path(leaf, nodeMap);
validateCompleteQuestionPath(vo.getBankType(), entityPath);
vo.setFullPath(entityPath.stream().map(TheoreticalLibraryNodeEntity::getName)
.collect(Collectors.joining(" → ")));
for (TheoreticalLibraryNodeEntity node : entityPath) {
......@@ -650,6 +656,67 @@ public class TheoreticalLibraryAdminServiceImpl implements TheoreticalLibraryAdm
}
}
/**
* 校验树表中每个节点的父节点存在,且节点类型按固定层级相邻。
*
* <p>树允许停在任意中间层,以便展示尚未配题的空分支;但不允许跳过
* 章、节、目等层级,也不允许把断链子节点降级成新的根节点。</p>
*/
private void validateNodeHierarchy(String bankType,
List<TheoreticalLibraryNodeEntity> nodes) {
List<String> expectedTypes = TheoreticalLibraryAdminConstants.nodeTypes(bankType);
Map<String, TheoreticalLibraryNodeEntity> nodeMap = nodes.stream()
.collect(Collectors.toMap(TheoreticalLibraryNodeEntity::getId,
node -> node, (left, right) -> left, LinkedHashMap::new));
for (TheoreticalLibraryNodeEntity node : nodes) {
if (!bankType.equals(node.getBankType())) {
throw new BusinessException("题库层级存在跨题库节点,请先修复数据");
}
int nodeLevel = expectedTypes.indexOf(node.getNodeType());
if (nodeLevel < 0) {
throw new BusinessException("题库层级存在不支持的节点类型,请先修复数据");
}
if (TheoreticalLibraryAdminConstants.ROOT_PARENT_ID.equals(node.getParentId())) {
if (nodeLevel != 0) {
throw new BusinessException("题库根节点类型不正确,请先修复数据");
}
continue;
}
TheoreticalLibraryNodeEntity parent = nodeMap.get(node.getParentId());
if (parent == null) {
throw new BusinessException("题库层级链不完整,请先修复上级节点");
}
int parentLevel = expectedTypes.indexOf(parent.getNodeType());
if (!bankType.equals(parent.getBankType()) || parentLevel + 1 != nodeLevel) {
throw new BusinessException("题库层级存在越级或类型错位,请先修复数据");
}
}
}
/** 题目必须绑定到固定末级,因此分页和详情返回前要校验完整层级序列。 */
private void validateCompleteQuestionPath(String bankType,
List<TheoreticalLibraryNodeEntity> path) {
String normalizedBankType = TheoreticalLibraryAdminConstants.normalizeBankType(bankType);
List<String> expectedTypes = TheoreticalLibraryAdminConstants.nodeTypes(normalizedBankType);
if (path.size() != expectedTypes.size()) {
throw new BusinessException("题目所属层级不完整,请先执行历史数据补齐");
}
for (int index = 0; index < path.size(); index++) {
TheoreticalLibraryNodeEntity node = path.get(index);
if (!normalizedBankType.equals(node.getBankType())
|| !expectedTypes.get(index).equals(node.getNodeType())) {
throw new BusinessException("题目所属层级存在越级或类型错位,请先修复数据");
}
if (index == 0) {
if (!TheoreticalLibraryAdminConstants.ROOT_PARENT_ID.equals(node.getParentId())) {
throw new BusinessException("题目所属层级根节点不正确,请先修复数据");
}
} else if (!path.get(index - 1).getId().equals(node.getParentId())) {
throw new BusinessException("题目所属层级链不完整,请先修复数据");
}
}
}
private List<TheoreticalLibraryOptionDTO> readOptions(TheoreticalLibraryEntity entity) {
String[] values = {entity.getOptionA(), entity.getOptionB(), entity.getOptionC(),
entity.getOptionD(), entity.getOptionE()};
......
......@@ -509,29 +509,48 @@ public class TheoreticalLibraryServiceImpl extends ServiceImpl<TheoreticalLibrar
}
/**
* 将旧模板刚导入的题目投影到新版层级表。
* 将旧模板刚导入的结构行和题目行一起投影到新版层级表。
*
* <p>方法只处理指定 scope,并使用“父节点+名称”缓存避免同一次导入反复查库。
* 节点编码采用稳定哈希,重复导入会复用原节点;题目仍保留旧层级名称供组卷查询。</p>
* <p>旧模板会把章、节、目、点标题保存为 {@code is_problem=false}
* 的独立记录。如果只同步题目行,没有题目的空分支会从管理端树中消失,
* 因此这里必须查询指定 scope 的全部记录。结构行只创建自身已提供的
* 层级,题目行则使用“未分类”节点补到固定末级并回填 {@code node_id}。</p>
*/
private void synchronizeImportedScope(String scope) {
List<TheoreticalLibraryEntity> questions = list(
List<TheoreticalLibraryEntity> importedRows = list(
new LambdaQueryWrapper<TheoreticalLibraryEntity>()
.eq(TheoreticalLibraryEntity::getScope, scope)
.eq(TheoreticalLibraryEntity::getIsProblem, true));
.eq(TheoreticalLibraryEntity::getScope, scope));
Map<String, TheoreticalLibraryNodeEntity> cache = new HashMap<>();
boolean competition = "技能竞赛".equals(scope);
for (TheoreticalLibraryEntity question : questions) {
TheoreticalLibraryNodeEntity leaf;
for (TheoreticalLibraryEntity importedRow : importedRows) {
boolean question = Boolean.TRUE.equals(importedRow.getIsProblem());
if (competition) {
TheoreticalLibraryNodeEntity competitionNode = ensureLegacyNode(cache, "COMP", "0",
"COMPETITION", fallback(question.getFirstLevelName(), "技能竞赛"), 10);
String competitionName = importedLevelName(importedRow.getFirstLevelName(),
"技能竞赛", question);
if (!StringUtils.isNotBlank(competitionName)) {
continue;
}
TheoreticalLibraryNodeEntity competitionNode = ensureLegacyNode(cache, "COMP",
"0", "COMPETITION", competitionName, 10);
String categoryName = importedLevelName(importedRow.getSecondLevelName(),
"未分类", question);
if (!StringUtils.isNotBlank(categoryName)) {
continue;
}
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");
competitionNode.getId(), "CATEGORY", categoryName, 10);
String directionName = importedLevelName(importedRow.getThirdLevelName(),
"未分类方向", question);
if (!StringUtils.isNotBlank(directionName)) {
continue;
}
TheoreticalLibraryNodeEntity leaf = ensureLegacyNode(cache, "COMP",
category.getId(), "DIRECTION", directionName, 10);
if (question) {
updateImportedQuestion(importedRow, "COMP", leaf);
}
} else {
String craftName = scope != null && (scope.startsWith("污水") || scope.startsWith("污泥"))
? scope.substring(0, 2) : fallback(scope, "其他工艺");
......@@ -541,28 +560,71 @@ public class TheoreticalLibraryServiceImpl extends ServiceImpl<TheoreticalLibrar
"CRAFT", craftName, 10);
TheoreticalLibraryNodeEntity level = ensureLegacyNode(cache, "JOB", craft.getId(),
"LEVEL", levelName, 10);
String chapterName = importedLevelName(importedRow.getFirstLevelName(),
"未分类章", question);
if (!StringUtils.isNotBlank(chapterName)) {
continue;
}
TheoreticalLibraryNodeEntity chapter = ensureLegacyNode(cache, "JOB", level.getId(),
"CHAPTER", fallback(question.getFirstLevelName(), "未分类章"), 10);
"CHAPTER", chapterName, 10);
String sectionName = importedLevelName(importedRow.getSecondLevelName(),
"未分类节", question);
if (!StringUtils.isNotBlank(sectionName)) {
continue;
}
TheoreticalLibraryNodeEntity section = ensureLegacyNode(cache, "JOB", chapter.getId(),
"SECTION", fallback(question.getSecondLevelName(), "未分类节"), 10);
"SECTION", sectionName, 10);
String topicName = importedLevelName(importedRow.getThirdLevelName(),
"未分类目", question);
if (!StringUtils.isNotBlank(topicName)) {
continue;
}
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");
"TOPIC", topicName, 10);
String pointName = importedLevelName(importedRow.getFourthLevelName(),
"未分类知识点", question);
if (!StringUtils.isNotBlank(pointName)) {
continue;
}
TheoreticalLibraryNodeEntity leaf = ensureLegacyNode(cache, "JOB", topic.getId(),
"POINT", pointName, 10);
if (question) {
updateImportedQuestion(importedRow, "JOB", leaf);
}
}
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 String importedLevelName(String value, String missingQuestionName, boolean question) {
if (StringUtils.isNotBlank(value)) {
return value.trim();
}
return question ? missingQuestionName : null;
}
/** 只回写真正的题目行,历史结构行仍保持原表数据不变。 */
private void updateImportedQuestion(TheoreticalLibraryEntity question, String bankType,
TheoreticalLibraryNodeEntity leaf) {
question.setBankType(bankType);
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,
......
......@@ -129,28 +129,54 @@ SET bank_type = COALESCE(bank_type, CASE WHEN scope = '技能竞赛' THEN 'COMP'
update_time = COALESCE(update_time, create_time, NOW())
WHERE is_problem = TRUE;
-- 临时表只保存题目路径。固定 ID 由完整路径 MD5 生成,脚本重复执行时会命中原节点。
-- 临时表同时保存历史结构行和题目行:结构行用于保留当前没有题目的空分支,
-- 题目行则必须补成完整路径。固定 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,
SELECT id AS source_id,
is_problem,
CASE
WHEN bank_type IN ('JOB', 'COMP') THEN bank_type
WHEN scope = '技能竞赛' THEN 'COMP'
ELSE 'JOB'
END AS bank_type,
CASE
WHEN bank_type = 'COMP' OR scope = '技能竞赛' THEN NULL
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 bank_type = 'COMP' OR scope = '技能竞赛' THEN NULL
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,
CASE
WHEN is_problem = TRUE THEN COALESCE(NULLIF(TRIM(first_level_name), ''),
CASE WHEN bank_type = 'COMP' OR scope = '技能竞赛'
THEN '技能竞赛' ELSE '未分类章' END)
ELSE NULLIF(TRIM(first_level_name), '')
END AS level1_name,
CASE
WHEN is_problem = TRUE THEN COALESCE(NULLIF(TRIM(second_level_name), ''),
CASE WHEN bank_type = 'COMP' OR scope = '技能竞赛'
THEN '未分类' ELSE '未分类节' END)
ELSE NULLIF(TRIM(second_level_name), '')
END AS level2_name,
CASE
WHEN is_problem = TRUE THEN COALESCE(NULLIF(TRIM(third_level_name), ''),
CASE WHEN bank_type = 'COMP' OR scope = '技能竞赛'
THEN '未分类方向' ELSE '未分类目' END)
ELSE NULLIF(TRIM(third_level_name), '')
END AS level3_name,
CASE
WHEN is_problem = TRUE AND NOT (
COALESCE(bank_type = 'COMP', FALSE)
OR COALESCE(scope = '技能竞赛', FALSE))
THEN COALESCE(NULLIF(TRIM(fourth_level_name), ''), '未分类知识点')
WHEN COALESCE(is_problem, FALSE) = FALSE THEN NULLIF(TRIM(fourth_level_name), '')
ELSE NULL
END 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,
......@@ -158,7 +184,7 @@ SELECT id AS question_id,
CAST(NULL AS CHAR(32)) AS level3_id,
CAST(NULL AS CHAR(32)) AS level4_id
FROM theoretical_library
WHERE is_problem = TRUE;
WHERE COALESCE(TRIM(scope), '') <> '' OR bank_type IN ('JOB', 'COMP');
UPDATE tmp_tl_path
SET craft_id = MD5(CONCAT('JOB|CRAFT|', craft_name)),
......@@ -171,7 +197,9 @@ SET craft_id = MD5(CONCAT('JOB|CRAFT|', 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));
'|', level2_name, '|', level3_name, '|', level4_name))
-- source_id 来自理论题库主键,正常迁移行必然非空;显式 WHERE 同时兼容数据库客户端的安全更新检查。
WHERE source_id IS NOT NULL;
-- 职级题库:工艺 → 职级 → 章 → 节 → 目 → 点。
INSERT IGNORE INTO theoretical_library_node
......@@ -186,35 +214,42 @@ INSERT IGNORE INTO theoretical_library_node
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';
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';
FROM tmp_tl_path
WHERE bank_type = 'JOB' AND level1_name IS NOT NULL;
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';
FROM tmp_tl_path
WHERE bank_type = 'JOB' AND level1_name IS NOT NULL AND level2_name IS NOT NULL;
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';
FROM tmp_tl_path
WHERE bank_type = 'JOB' AND level1_name IS NOT NULL AND level2_name IS NOT NULL
AND level3_name IS NOT NULL;
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';
FROM tmp_tl_path
WHERE bank_type = 'JOB' AND level1_name IS NOT NULL AND level2_name IS NOT NULL
AND level3_name IS NOT NULL AND level4_name IS NOT NULL;
-- 竞赛题库:竞赛类型 → 题目分类 → 题目方向。
INSERT IGNORE INTO theoretical_library_node
......@@ -222,24 +257,28 @@ INSERT IGNORE INTO theoretical_library_node
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';
FROM tmp_tl_path
WHERE bank_type = 'COMP' AND level1_name IS NOT NULL;
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';
FROM tmp_tl_path
WHERE bank_type = 'COMP' AND level1_name IS NOT NULL AND level2_name IS NOT NULL;
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';
FROM tmp_tl_path
WHERE bank_type = 'COMP' AND level1_name IS NOT NULL AND level2_name IS NOT NULL
AND level3_name IS NOT NULL;
UPDATE theoretical_library q
INNER JOIN tmp_tl_path p ON p.question_id = q.id
INNER JOIN tmp_tl_path p ON p.source_id = q.id AND p.is_problem = TRUE
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());
......@@ -257,3 +296,47 @@ SELECT bank_type, parent_id, code, COUNT(*) AS duplicate_count
FROM theoretical_library_node
GROUP BY bank_type, parent_id, code
HAVING COUNT(*) > 1;
-- 核查所有非根节点是否存在直属上级,以及父子节点类型是否严格相邻。
SELECT child.id, child.bank_type, child.node_type, child.parent_id,
parent.node_type AS parent_node_type
FROM theoretical_library_node child
LEFT JOIN theoretical_library_node parent ON parent.id = child.parent_id
WHERE child.bank_type NOT IN ('JOB', 'COMP')
OR (child.parent_id = '0' AND
((child.bank_type = 'JOB' AND child.node_type <> 'CRAFT') OR
(child.bank_type = 'COMP' AND child.node_type <> 'COMPETITION')))
OR (child.parent_id <> '0' AND
(parent.id IS NULL OR parent.bank_type <> child.bank_type OR NOT (
(parent.node_type = 'CRAFT' AND child.node_type = 'LEVEL') OR
(parent.node_type = 'LEVEL' AND child.node_type = 'CHAPTER') OR
(parent.node_type = 'CHAPTER' AND child.node_type = 'SECTION') OR
(parent.node_type = 'SECTION' AND child.node_type = 'TOPIC') OR
(parent.node_type = 'TOPIC' AND child.node_type = 'POINT') OR
(parent.node_type = 'COMPETITION' AND child.node_type = 'CATEGORY') OR
(parent.node_type = 'CATEGORY' AND child.node_type = 'DIRECTION')
)));
-- 核查题目绑定路径的深度和类型顺序;执行后返回数据表示 JOB 非六级或 COMP 非三级。
SELECT q.id, q.bank_type, q.node_id, leaf.node_type AS leaf_type
FROM theoretical_library q
LEFT JOIN theoretical_library_node leaf ON leaf.id = q.node_id
LEFT JOIN theoretical_library_node p1 ON p1.id = leaf.parent_id
LEFT JOIN theoretical_library_node p2 ON p2.id = p1.parent_id
LEFT JOIN theoretical_library_node p3 ON p3.id = p2.parent_id
LEFT JOIN theoretical_library_node p4 ON p4.id = p3.parent_id
LEFT JOIN theoretical_library_node p5 ON p5.id = p4.parent_id
WHERE q.is_problem = TRUE
AND ((q.bank_type = 'JOB' AND NOT (
COALESCE(leaf.node_type = 'POINT', FALSE)
AND COALESCE(p1.node_type = 'TOPIC', FALSE)
AND COALESCE(p2.node_type = 'SECTION', FALSE)
AND COALESCE(p3.node_type = 'CHAPTER', FALSE)
AND COALESCE(p4.node_type = 'LEVEL', FALSE)
AND COALESCE(p5.node_type = 'CRAFT', FALSE)
AND COALESCE(p5.parent_id = '0', FALSE)))
OR (q.bank_type = 'COMP' AND NOT (
COALESCE(leaf.node_type = 'DIRECTION', FALSE)
AND COALESCE(p1.node_type = 'CATEGORY', FALSE)
AND COALESCE(p2.node_type = 'COMPETITION', FALSE)
AND COALESCE(p2.parent_id = '0', FALSE))));
......@@ -8,6 +8,11 @@
practical-business/src/main/resources/sql/theoretical_library_management.sql
```
该脚本可重复执行,除了为历史题目回填完整路径,还会迁移旧表中
`is_problem=false` 的章、节、目、点结构行,因此没有试题的空分支也会出现在树中。
题目历史字段缺级时会归入对应的“未分类章/节/目/知识点”节点。脚末的核查
SQL 应全部返回空结果,否则管理端树或分页接口会明确报告层级数据异常。
职级题库 `JOB` 固定为“工艺→职级→章→节→目→点”,竞赛题库 `COMP` 固定为
“竞赛类型→题目分类→题目方向”。节点编码在同题库、同父节点下唯一。
......
......@@ -20,7 +20,17 @@ class TheoreticalLibraryManagementSqlTest {
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"));
// 临时路径表必须携带 is_problem,才能区分“保留空分支”和“补齐题目路径”。
assertTrue(sql.contains("SELECT id AS source_id"));
assertTrue(sql.contains("WHERE source_id IS NOT NULL"));
assertTrue(sql.contains("ELSE NULLIF(TRIM(first_level_name), '')"));
assertTrue(sql.contains("未分类章"));
assertTrue(sql.contains("未分类节"));
assertTrue(sql.contains("未分类目"));
assertTrue(sql.contains("未分类知识点"));
assertTrue(sql.contains("q.node_id = CASE WHEN p.bank_type = 'COMP'"));
assertTrue(sql.contains("HAVING COUNT(*) > 1"));
assertTrue(sql.contains("核查所有非根节点是否存在直属上级"));
assertTrue(sql.contains("核查题目绑定路径的深度和类型顺序"));
}
}
......@@ -24,7 +24,6 @@ import java.util.Collections;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
......@@ -71,6 +70,43 @@ class TheoreticalLibraryAdminServiceImplTest {
assertEquals("一级", result.get(0).getChildren().get(0).getName());
}
@Test
void treeShouldKeepIntermediateBranchWithoutQuestions() {
TheoreticalLibraryNodeEntity craft = node("craft", "0", "CRAFT", "污水", "C-WATER");
TheoreticalLibraryNodeEntity level = node("level", "craft", "LEVEL", "一级", "L-1");
TheoreticalLibraryNodeEntity chapter =
node("chapter", "level", "CHAPTER", "第一章", "CH-1");
TheoreticalLibraryNodeEntity emptySection =
node("empty-section", "chapter", "SECTION", "暂无试题的节", "SEC-EMPTY");
when(nodeMapper.selectList(any())).thenReturn(
Arrays.asList(craft, level, chapter, emptySection));
when(libraryMapper.selectQuestionCounts("JOB")).thenReturn(Collections.emptyList());
List<TheoreticalLibraryNodeVO> result = service.tree("JOB", null);
TheoreticalLibraryNodeVO returnedSection = result.get(0).getChildren().get(0)
.getChildren().get(0).getChildren().get(0);
assertEquals("暂无试题的节", returnedSection.getName());
assertEquals(0L, returnedSection.getQuestionCount());
assertTrue(returnedSection.getChildren().isEmpty());
}
@Test
void treeShouldRejectDanglingOrSkippedIntermediateNode() {
TheoreticalLibraryNodeEntity dangling =
node("section", "missing", "SECTION", "第一节", "SEC-1");
when(nodeMapper.selectList(any())).thenReturn(Collections.singletonList(dangling));
assertThrows(BusinessException.class, () -> service.tree("JOB", null));
TheoreticalLibraryNodeEntity craft = node("craft", "0", "CRAFT", "污水", "C-WATER");
TheoreticalLibraryNodeEntity skipped =
node("chapter", "craft", "CHAPTER", "第一章", "CH-1");
when(nodeMapper.selectList(any())).thenReturn(Arrays.asList(craft, skipped));
assertThrows(BusinessException.class, () -> service.tree("JOB", null));
}
@Test
void nodeDeleteShouldRequireExplicitCascadeConfirmation() {
when(nodeMapper.selectById("node-1"))
......@@ -156,17 +192,27 @@ class TheoreticalLibraryAdminServiceImplTest {
}
@Test
void pageShouldReturnEmptyNodePathWhenBoundNodeDoesNotExist() {
void pageShouldRejectQuestionWhenBoundNodeDoesNotExist() {
when(libraryMapper.selectAdminQuestions(any()))
.thenReturn(Collections.singletonList(question("q-1", "JOB", "missing")));
when(nodeMapper.selectList(any())).thenReturn(Collections.emptyList());
TheoreticalLibraryQuestionQueryDTO query = new TheoreticalLibraryQuestionQueryDTO();
query.setBankType("JOB");
TheoreticalLibraryQuestionVO result = service.page(query).get(0);
assertThrows(BusinessException.class, () -> service.page(query));
}
assertTrue(result.getNodePath().isEmpty());
assertNull(result.getFullPath());
@Test
void pageShouldRejectPathThatSkipsExpectedNodeType() {
List<TheoreticalLibraryNodeEntity> path = completeJobPath();
path.get(3).setNodeType("TOPIC");
when(libraryMapper.selectAdminQuestions(any()))
.thenReturn(Collections.singletonList(question("q-1", "JOB", "point")));
when(nodeMapper.selectList(any())).thenReturn(path);
TheoreticalLibraryQuestionQueryDTO query = new TheoreticalLibraryQuestionQueryDTO();
query.setBankType("JOB");
assertThrows(BusinessException.class, () -> service.page(query));
}
@Test
......
package com.platform.business.service.impl;
import com.platform.business.mapper.TheoreticalLibraryMapper;
import com.platform.business.mapper.TheoreticalLibraryNodeMapper;
import com.platform.business.model.entity.TheoreticalLibraryEntity;
import com.platform.business.model.entity.TheoreticalLibraryNodeEntity;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.util.ReflectionTestUtils;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** 旧版理论题库导入同步新六级节点表的回归测试。 */
@ExtendWith(MockitoExtension.class)
class TheoreticalLibraryServiceImplTest {
@Mock
private TheoreticalLibraryMapper libraryMapper;
@Mock
private TheoreticalLibraryNodeMapper nodeMapper;
private TheoreticalLibraryServiceImpl service;
@BeforeEach
void setUp() {
service = new TheoreticalLibraryServiceImpl();
// ServiceImpl 的 list/updateById 都通过 baseMapper 执行,测试中与新节点 Mapper 分别注入。
ReflectionTestUtils.setField(service, "baseMapper", libraryMapper);
ReflectionTestUtils.setField(service, "theoreticalLibraryNodeMapper", nodeMapper);
}
@Test
void legacyImportShouldKeepEmptyBranchAndCompleteQuestionPath() {
TheoreticalLibraryEntity emptySection = row("structure", false);
emptySection.setFirstLevelName("第一章");
emptySection.setSecondLevelName("暂无试题的节");
TheoreticalLibraryEntity incompleteQuestion = row("question", true);
incompleteQuestion.setFirstLevelName("第一章");
incompleteQuestion.setType("单选题");
when(libraryMapper.selectList(any()))
.thenReturn(Arrays.asList(emptySection, incompleteQuestion));
when(nodeMapper.selectOne(any())).thenReturn(null);
// Mapper 被 mock 后不会触发 MyBatis-Plus 的 ASSIGN_ID,因此在 insert 回答中
// 分配可预期 ID,使后续子节点能正确引用刚创建的父节点。
AtomicInteger idSequence = new AtomicInteger();
doAnswer(invocation -> {
TheoreticalLibraryNodeEntity node = invocation.getArgument(0);
node.setId("generated-" + idSequence.incrementAndGet());
return 1;
}).when(nodeMapper).insert(any(TheoreticalLibraryNodeEntity.class));
when(libraryMapper.updateById(any(TheoreticalLibraryEntity.class))).thenReturn(1);
ReflectionTestUtils.invokeMethod(service, "synchronizeImportedScope", "污水一级");
ArgumentCaptor<TheoreticalLibraryNodeEntity> nodeCaptor =
ArgumentCaptor.forClass(TheoreticalLibraryNodeEntity.class);
verify(nodeMapper, org.mockito.Mockito.atLeastOnce()).insert(nodeCaptor.capture());
List<TheoreticalLibraryNodeEntity> insertedNodes = nodeCaptor.getAllValues();
List<String> insertedNames = insertedNodes.stream()
.map(TheoreticalLibraryNodeEntity::getName)
.collect(Collectors.toList());
assertTrue(insertedNames.contains("暂无试题的节"));
assertTrue(insertedNames.contains("未分类节"));
assertTrue(insertedNames.contains("未分类目"));
assertTrue(insertedNames.contains("未分类知识点"));
assertEquals("JOB", incompleteQuestion.getBankType());
assertNotNull(incompleteQuestion.getNodeId());
verify(libraryMapper).updateById(incompleteQuestion);
verify(libraryMapper, never()).updateById(emptySection);
}
/** 构造仅包含同步链路所需字段的旧表记录。 */
private TheoreticalLibraryEntity row(String id, boolean question) {
TheoreticalLibraryEntity row = new TheoreticalLibraryEntity();
row.setId(id);
row.setScope("污水一级");
row.setIsProblem(question);
return row;
}
}
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