Commit bb53a972 authored by wujipeng's avatar wujipeng
Browse files

题库管理-理论题库-批量导入-优化

parent fb3c0f0e
package com.platform.business.model.dto;
import com.platform.business.model.vo.TheoreticalLibraryImportOptionVO;
import lombok.Data;
import java.util.List;
/** 管理员在理论题库导入预览页对单条异常题目的处理决定。 */
@Data
public class TheoreticalLibraryImportDecisionDTO {
/** 预览结果中的 Excel 题干行号,从 1 开始。 */
private Integer sourceRow;
/** 重复题处理决定:true 跳过,false 仍然导入;非重复题可不传。 */
private Boolean skip;
/** 多答案括号歧义时选中的 answerCandidates.index。 */
private Integer answerCandidateIndex;
/** 选项解析异常时管理员修正后的完整选项列表。 */
private List<TheoreticalLibraryImportOptionVO> options;
}
package com.platform.business.model.vo;
import lombok.Data;
/** 题干中可供前端点选为答案位的括号。 */
@Data
public class TheoreticalLibraryImportBracketVO {
/** 候选括号在当前题干中的顺序,从 0 开始。 */
private Integer index;
/** 包含中英文括号的原始文本,例如“(B)”。 */
private String rawText;
/** 括号内部文本,例如“B”或“Pb”。 */
private String content;
/** 候选括号在题干中的起始字符下标,前端可据此精确高亮。 */
private Integer startIndex;
/** 候选括号在题干中的结束字符下标(不包含该下标)。 */
private Integer endIndex;
}
package com.platform.business.model.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/** 理论题库导入预览异常。 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TheoreticalLibraryImportIssueVO {
/** 稳定异常代码,前端应按代码选择对应处理组件。 */
private String code;
/** 可直接展示给管理员的中文说明。 */
private String message;
}
package com.platform.business.model.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/** 旧格式理论题库预览中解析出的单个选项。 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TheoreticalLibraryImportOptionVO {
/** 选项字母,例如 A、B、C。 */
private String label;
/** 去除选项字母标记后的选项正文。 */
private String content;
}
package com.platform.business.model.vo;
import lombok.Data;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/** 旧格式理论题库批量导入预览汇总。 */
@Data
public class TheoreticalLibraryImportPreviewVO {
private String fileName;
private String scope;
private Integer totalCount;
private Integer normalCount;
private Integer abnormalCount;
/** 按判断题、单选题、多选题顺序返回数量,供左侧题型树直接渲染。 */
private Map<String, Integer> questionTypeCounts = new LinkedHashMap<>();
private List<TheoreticalLibraryImportQuestionVO> abnormalQuestions;
private List<TheoreticalLibraryImportQuestionVO> normalQuestions;
}
package com.platform.business.model.vo;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/** 旧格式理论题库拆题后的单题预览结果。 */
@Data
public class TheoreticalLibraryImportQuestionVO {
/** Excel 中题干所在行号,从 1 开始。 */
private Integer sourceRow;
/** 本次文件内连续题号,从 1 开始,可作为前端稳定行键。 */
private Integer sequence;
private String type;
/** 去除已识别答案后的题干,与旧导入落库口径一致。 */
private String problem;
/** Excel 中未经答案替换的原始题干。 */
private String rawProblem;
private String answer;
private String firstLevelName;
private String secondLevelName;
private String thirdLevelName;
private String fourthLevelName;
private List<TheoreticalLibraryImportOptionVO> options = new ArrayList<>();
private List<TheoreticalLibraryImportBracketVO> answerCandidates = new ArrayList<>();
private List<TheoreticalLibraryImportIssueVO> issues = new ArrayList<>();
/** 是否需要管理员处理;由 issues 是否为空计算后回填。 */
private Boolean abnormal;
/** 命中数据库重复题时返回原题 ID,便于前端查看原题。 */
private String duplicateQuestionId;
/** 命中文件内重复题时返回前一题的 sequence。 */
private Integer duplicateSequence;
}
package com.platform.business.controller;
import com.platform.business.model.dto.TheoreticalLibraryDTO;
import com.platform.business.model.dto.TheoreticalLibraryImportDecisionDTO;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.TheoreticalLibraryImportPreviewVO;
import com.platform.business.service.AuthenticatedUserService;
import com.platform.business.service.TheoreticalLibraryImportPreviewService;
import com.platform.business.service.TheoreticalLibraryService;
import com.platform.controller.BaseController;
import com.platform.model.resp.Result;
......@@ -16,6 +19,8 @@ import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
/**
* @author : wujipeng
......@@ -31,8 +36,48 @@ public class TheoreticalLibraryController extends BaseController {
@Resource
private TheoreticalLibraryService theoreticalLibraryService;
@Resource
private TheoreticalLibraryImportPreviewService theoreticalLibraryImportPreviewService;
@Resource
private AuthenticatedUserService authenticatedUserService;
/**
* 旧格式题库导入预览。
*
* <p>该接口只解析上传文件并读取现有题库用于重复校验,不执行删除或写入。
* 确认导入仍调用原有 {@code POST /theoretical/library/import},因此不会改变
* 已上线的拆题和落库逻辑。</p>
*/
@ApiOperation("旧格式题库批量导入预览")
@PostMapping("/import/preview")
public Result<TheoreticalLibraryImportPreviewVO> previewImport(
@RequestParam(name = "file") MultipartFile file,
HttpServletRequest request) throws IOException {
UserEntity administrator = authenticatedUserService.current(request);
authenticatedUserService.requireAdmin(administrator);
return Result.data(theoreticalLibraryImportPreviewService.preview(file));
}
/**
* 确认导入预览中已处理的数据。
*
* <p>处理决定只用于生成内存文件,最终仍调用原有正式导入方法。这样既能让
* 跳过、答案位选择和选项编辑生效,又不复制或改写原来的拆题落库逻辑。</p>
*/
@ApiOperation("确认导入已处理的旧格式题库")
@PostMapping("/import/confirm")
public Result<Boolean> confirmImport(
@RequestPart(name = "file") MultipartFile file,
@RequestPart(name = "decisions", required = false)
List<TheoreticalLibraryImportDecisionDTO> decisions,
HttpServletRequest request) throws IOException {
UserEntity administrator = authenticatedUserService.current(request);
authenticatedUserService.requireAdmin(administrator);
MultipartFile confirmedFile = theoreticalLibraryImportPreviewService
.prepareConfirmedFile(file,
decisions == null ? Collections.emptyList() : decisions);
return theoreticalLibraryService.importTheoreticalLibrary(confirmedFile, administrator);
}
@ApiOperation("上传")
@PostMapping("/import")
public Result<Boolean> importTheoreticalLibrary(@RequestParam(name = "file") MultipartFile file,
......
package com.platform.business.service;
import com.platform.business.model.dto.TheoreticalLibraryImportDecisionDTO;
import com.platform.business.model.vo.TheoreticalLibraryImportPreviewVO;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
/** 旧格式理论题库导入前的只读拆题与异常检查。 */
public interface TheoreticalLibraryImportPreviewService {
/**
* 解析上传文件但不写数据库。
*
* @param file 与旧导入接口完全相同的 Excel 文件
* @return 可用于“异常题目/无异常”双 Tab 的预览数据
*/
TheoreticalLibraryImportPreviewVO preview(MultipartFile file) throws IOException;
/**
* 校验预览页处理决定并生成仅存在于内存中的修正版文件。
* 返回文件继续交给原正式导入服务,确保旧拆题和落库实现保持唯一。
*/
MultipartFile prepareConfirmedFile(MultipartFile file,
List<TheoreticalLibraryImportDecisionDTO> decisions)
throws IOException;
}
# 理论题库旧格式批量导入预览:前后端联调文档
## 1. 适用范围
本文对应“题库管理 → 理论题库 → 批量导入”的三步流程:
1. 上传文件;
2. 预览确认并处理异常;
3. 确认导入并展示结果。
接口读取原有五列层级题库模板,例如 `污水三级理论题库.xlsx`。正式导入仍由原接口和
原拆题方法完成;新增确认接口只在内存中应用预览页决定,再把修正版文件交给原导入服务。
支持 `.xlsx`、`.xls`,单文件不超过 10MB。文件名必须包含以下一种路由信息:
- `污水`或`污泥` + `一级`~`五级`;
- `技能竞赛`。
所有接口均要求当前登录用户为管理员,认证方式与项目其他管理接口一致。
## 2. 接口总览
| 步骤 | 方法 | 路径 | 说明 |
|---|---|---|---|
| 预览 | POST | `/theoretical/library/import/preview` | 只读解析、重复校验、异常分类,不写数据库 |
| 确认 | POST | `/theoretical/library/import/confirm` | 应用处理决定后调用原拆题导入 |
| 兼容导入 | POST | `/theoretical/library/import` | 原接口,保留给无异常文件或旧前端使用 |
## 3. 上传预览
### 3.1 请求
`POST /theoretical/library/import/preview`
`Content-Type: multipart/form-data`
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| `file` | File | 是 | 原始 Excel 文件 |
### 3.2 成功响应示例
项目统一响应外壳中的业务数据位于 `data`:
```json
{
"code": 200,
"msg": "操作成功",
"data": {
"fileName": "污水三级理论题库.xlsx",
"scope": "污水三级",
"totalCount": 120,
"normalCount": 116,
"abnormalCount": 4,
"questionTypeCounts": {
"判断题": 40,
"单选题": 50,
"多选题": 30
},
"abnormalQuestions": [
{
"sourceRow": 18,
"sequence": 9,
"type": "单选题",
"rawProblem": "以下(B)方法常用于处理含铅(Pb)废水。",
"problem": "以下(B)方法常用于处理含铅(Pb)废水。",
"answer": "P",
"firstLevelName": "基本要求",
"secondLevelName": "职业道德",
"thirdLevelName": "基本知识",
"fourthLevelName": "知识点一",
"options": [
{"label": "A", "content": "吸附"},
{"label": "B", "content": "沉淀"}
],
"answerCandidates": [
{"index": 0, "rawText": "(B)", "content": "B", "startIndex": 2, "endIndex": 5},
{"index": 1, "rawText": "(Pb)", "content": "Pb", "startIndex": 14, "endIndex": 18}
],
"issues": [
{
"code": "ANSWER_BRACKET_AMBIGUOUS",
"message": "题干检测到 2 组英文字母括号,请点选一组作为标准答案位"
}
],
"abnormal": true
}
],
"normalQuestions": []
}
}
```
### 3.3 前端展示映射
| 原型区域 | 响应字段 |
|---|---|
| 题目总数 | `totalCount` |
| 无需处理 | `normalCount` |
| 待处理初始值 | `abnormalCount` |
| 左侧题型树 | `questionTypeCounts`,再按题目 `type` 分组 |
| 异常题目 Tab | `abnormalQuestions` |
| 无异常 Tab | `normalQuestions` |
| 题干虚线括号 | `answerCandidates` 的字符坐标和 `index` |
`answer` 是旧拆题算法产生的默认结果。存在 `ANSWER_BRACKET_AMBIGUOUS` 时不能直接采用,
必须以管理员选择的 `answerCandidates.index` 为准。
## 4. 异常代码与处理组件
| code | 含义 | 前端处理 |
|---|---|---|
| `ANSWER_BRACKET_AMBIGUOUS` | 题干至少两组纯英文字母括号 | 点选答案括号,提交 `answerCandidateIndex` |
| `DUPLICATE_IN_FILE` | 与本文件前一题重复 | “跳过/仍然导入”,提交 `skip` |
| `DUPLICATE_IN_DATABASE` | 同范围、四级层级、题型、题干已存在 | “跳过/仍然导入”,提交 `skip` |
| `OPTION_MISSING` | 题目下一行没有选项 | 编辑完整选项后提交 `options` |
| `OPTION_PARSE_ERROR` | 未识别出(A)~(E)标记 | 编辑完整选项后提交 `options` |
| `OPTION_DUPLICATE_LABEL` | 选项字母重复 | 编辑完整选项后提交 `options` |
| `OPTION_LABEL_DISCONTINUOUS` | 选项字母跳号 | 编辑完整选项后提交 `options` |
| `ANSWER_OPTION_MISSING` | 答案字母不存在对应选项 | 编辑完整选项后提交 `options` |
同一题可能同时包含多个 `issues`,必须全部处理。前端可以维护本地 `resolved` 状态:
- 初始待处理数 = `abnormalCount`;
- 某题所需字段全部填写后标记已处理;
- 待处理数大于 0 时禁用“确认导入”;
- 已处理题仍保留在异常 Tab,可在确认前继续修改。
## 5. 确认导入
### 5.1 请求
`POST /theoretical/library/import/confirm`
`Content-Type: multipart/form-data`
| Part | Content-Type | 必填 | 说明 |
|---|---|---|---|
| `file` | Excel 对应类型 | 是 | 必须是本次预览使用的原文件 |
| `decisions` | `application/json` | 有异常时是 | 异常题处理决定数组;无异常可传 `[]` 或不传 |
`decisions` 示例:
```json
[
{
"sourceRow": 18,
"answerCandidateIndex": 0
},
{
"sourceRow": 36,
"skip": true
},
{
"sourceRow": 52,
"skip": false
},
{
"sourceRow": 68,
"options": [
{"label": "A", "content": "低 DO"},
{"label": "B", "content": "高 SRT"},
{"label": "C", "content": "高 F/M"},
{"label": "D", "content": "营养失衡"}
]
}
]
```
字段规则:
| 字段 | 必填条件 | 说明 |
|---|---|---|
| `sourceRow` | 始终必填 | 直接使用预览返回值,不要用列表序号代替 |
| `skip` | 重复题必填 | `true` 跳过,`false` 仍然导入 |
| `answerCandidateIndex` | 答案括号歧义且未跳过 | 使用候选项的 `index` |
| `options` | 选项异常且未跳过 | 2~5 项,从 A 开始连续、不可重复、内容非空,并覆盖答案字母 |
同一题有多种异常时将所需字段合并在同一个对象中。后端会重新预览原文件并校验所有异常;
任何一题未处理都会整体拒绝,不会删除或写入数据。
### 5.2 浏览器 FormData 示例
```javascript
const form = new FormData();
form.append('file', selectedFile);
form.append(
'decisions',
new Blob([JSON.stringify(decisions)], { type: 'application/json' })
);
await axios.post('/theoretical/library/import/confirm', form);
```
不要手工设置 `Content-Type` 的 boundary,让浏览器或 Axios 自动生成。
### 5.3 成功响应
确认接口原样返回旧导入服务的统一 `Result<Boolean>`,现有实现以 `code` 和 `msg` 表示结果:
```json
{
"code": 200,
"msg": "导入成功"
}
```
原导入按文件名对应范围执行覆盖导入;这是既有行为,本次没有改变。
## 6. 推荐前端调用时序
1. 前端先校验扩展名和 10MB 大小;
2. 调用 `/import/preview`,保存原始 `File` 对象;
3. 渲染双 Tab,按 `issues.code` 收集处理决定;
4. 待处理数归零后,将同一个 `File` 和 `decisions` 提交 `/import/confirm`;
5. 成功后展示成功数。当前旧导入为整范围覆盖且返回布尔值,因此成功数可使用
`totalCount - skip=true 的题数`,失败数为跳过数;
6. 关闭弹窗并刷新题库树、统计和列表。
如果预览后用户重新选择文件,必须清空旧预览及全部 `decisions`,禁止把旧行号应用到新文件。
## 7. 常见错误
| 场景 | 后端提示 |
|---|---|
| 空文件 | 请选择需要导入的 Excel 文件 |
| 超过 10MB | 文件大小不能超过 10MB |
| 格式错误 | 仅支持 .xlsx 或 .xls 文件 |
| 文件名无法路由 | 文件名需包含污水/污泥(一级~五级)或技能竞赛 |
| 异常未处理 | 第 N 行异常尚未处理 |
| 重复题未选择动作 | 第 N 行重复题需选择跳过或仍然导入 |
| 未选择答案括号 | 第 N 行需选择有效的答案括号 |
| 修正选项不合法 | 第 N 行修正后的选项字母必须从 A 开始连续且不可重复 |
## 8. 数据库变更
本功能不新增表、不新增字段,也不需要 MySQL 建表或变更语句。重复检查直接读取现有
`theoretical_library` 表;正式写入继续由原导入服务完成。
## 9. 样例文件验收结果
使用本次提供的 `污水三级理论题库.xlsx` 进行本地真实文件解析:共拆出 1200 题,
其中判断题 300、单选题 600、多选题 300;在不连接现有题库重复数据的情况下,
1181 题无异常、19 题需处理。部署环境还会叠加数据库重复校验,因此实际异常数可能增加。
package com.platform.business.controller;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.dto.TheoreticalLibraryImportDecisionDTO;
import com.platform.business.service.AuthenticatedUserService;
import com.platform.business.service.TheoreticalLibraryImportPreviewService;
import com.platform.business.service.TheoreticalLibraryService;
import com.platform.exception.BusinessException;
import org.junit.jupiter.api.BeforeEach;
......@@ -20,6 +22,8 @@ import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Collections;
/** 旧格式理论题库接口的登录用户传递与管理员鉴权测试。 */
@ExtendWith(MockitoExtension.class)
class TheoreticalLibraryControllerTest {
......@@ -27,6 +31,8 @@ class TheoreticalLibraryControllerTest {
@Mock
private TheoreticalLibraryService theoreticalLibraryService;
@Mock
private TheoreticalLibraryImportPreviewService theoreticalLibraryImportPreviewService;
@Mock
private AuthenticatedUserService authenticatedUserService;
private TheoreticalLibraryController controller;
......@@ -38,6 +44,8 @@ class TheoreticalLibraryControllerTest {
controller = new TheoreticalLibraryController();
ReflectionTestUtils.setField(controller, "theoreticalLibraryService",
theoreticalLibraryService);
ReflectionTestUtils.setField(controller, "theoreticalLibraryImportPreviewService",
theoreticalLibraryImportPreviewService);
ReflectionTestUtils.setField(controller, "authenticatedUserService",
authenticatedUserService);
request = new MockHttpServletRequest();
......@@ -72,4 +80,34 @@ class TheoreticalLibraryControllerTest {
verify(theoreticalLibraryService, never())
.importTheoreticalLibrary(any(), any());
}
@Test
void legacyPreviewShouldAuthenticateAdministratorAndOnlyCallPreviewService() throws Exception {
UserEntity administrator = new UserEntity();
administrator.setId("admin-1");
when(authenticatedUserService.current(request)).thenReturn(administrator);
controller.previewImport(file, request);
// 预览与正式导入使用相同管理员权限,但绝不能提前触发原正式导入链路。
verify(authenticatedUserService).requireAdmin(administrator);
verify(theoreticalLibraryImportPreviewService).preview(file);
verify(theoreticalLibraryService, never()).importTheoreticalLibrary(any(), any());
}
@Test
void confirmShouldPrepareCorrectedFileBeforeCallingUnchangedImporter() throws Exception {
UserEntity administrator = new UserEntity();
administrator.setId("admin-1");
when(authenticatedUserService.current(request)).thenReturn(administrator);
when(theoreticalLibraryImportPreviewService.prepareConfirmedFile(file, Collections.emptyList()))
.thenReturn(file);
controller.confirmImport(file, Collections.<TheoreticalLibraryImportDecisionDTO>emptyList(), request);
verify(theoreticalLibraryImportPreviewService)
.prepareConfirmedFile(file, Collections.emptyList());
// 控制器最终仍进入旧 importTheoreticalLibrary,而不是另建一套拆题落库实现。
verify(theoreticalLibraryService).importTheoreticalLibrary(file, administrator);
}
}
package com.platform.business.service.impl;
import com.platform.business.mapper.TheoreticalLibraryMapper;
import com.platform.business.model.dto.TheoreticalLibraryImportDecisionDTO;
import com.platform.business.model.vo.TheoreticalLibraryImportPreviewVO;
import com.platform.business.model.vo.TheoreticalLibraryImportQuestionVO;
import com.platform.exception.BusinessException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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.MockMultipartFile;
import org.springframework.test.util.ReflectionTestUtils;
import java.io.ByteArrayOutputStream;
import java.util.Collections;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** 旧格式题库预览拆题和产品异常规则测试。 */
@ExtendWith(MockitoExtension.class)
class TheoreticalLibraryImportPreviewServiceImplTest {
@Mock
private TheoreticalLibraryMapper theoreticalLibraryMapper;
private TheoreticalLibraryImportPreviewServiceImpl service;
@BeforeEach
void setUp() {
service = new TheoreticalLibraryImportPreviewServiceImpl();
ReflectionTestUtils.setField(service, "theoreticalLibraryMapper", theoreticalLibraryMapper);
}
@Test
void previewShouldKeepLegacySplitResultAndExposeAmbiguousAnswerBrackets() throws Exception {
when(theoreticalLibraryMapper.selectList(any())).thenReturn(Collections.emptyList());
MockMultipartFile file = workbook("污水三级理论题库.xlsx", sheet -> {
hierarchy(sheet, 4, 0, "基本要求");
hierarchy(sheet, 5, 1, "职业道德");
hierarchy(sheet, 6, 2, "基本知识");
hierarchy(sheet, 7, 3, "知识点一");
cell(sheet, 8, "单选题");
cell(sheet, 9, "以下(B)方法常用于处理含铅(Pb)废水。");
cell(sheet, 10, "(A)吸附 (B)沉淀 (C)过滤 (D)消毒");
});
TheoreticalLibraryImportPreviewVO result = service.preview(file);
assertEquals("污水三级", result.getScope());
assertEquals(1, result.getTotalCount());
assertEquals(1, result.getAbnormalCount());
TheoreticalLibraryImportQuestionVO question = result.getAbnormalQuestions().get(0);
// 旧导入按最后一个中文括号取首字母,因此默认仍为 P;预览通过候选位让管理员修正为 B。
assertEquals("P", question.getAnswer());
assertEquals(2, question.getAnswerCandidates().size());
assertTrue(question.getIssues().stream()
.anyMatch(issue -> "ANSWER_BRACKET_AMBIGUOUS".equals(issue.getCode())));
assertEquals(4, question.getOptions().size());
verify(theoreticalLibraryMapper).selectList(any());
}
@Test
void previewShouldReportOptionDiscontinuityAndMissingAnswerOption() throws Exception {
when(theoreticalLibraryMapper.selectList(any())).thenReturn(Collections.emptyList());
MockMultipartFile file = workbook("污泥二级题库.xlsx", sheet -> {
hierarchy(sheet, 4, 0, "第一章");
hierarchy(sheet, 5, 1, "第一节");
hierarchy(sheet, 6, 2, "第一目");
hierarchy(sheet, 7, 3, "知识点");
cell(sheet, 8, "多选题");
cell(sheet, 9, "正确选项是(ABD)。");
cell(sheet, 10, "(A)甲 (B)乙 (D)丁");
});
TheoreticalLibraryImportQuestionVO question =
service.preview(file).getAbnormalQuestions().get(0);
assertTrue(question.getIssues().stream()
.anyMatch(issue -> "OPTION_LABEL_DISCONTINUOUS".equals(issue.getCode())));
// D 虽存在,但答案中的所有字母都有对应项;不应产生错误的缺项提示。
assertTrue(question.getIssues().stream()
.noneMatch(issue -> "ANSWER_OPTION_MISSING".equals(issue.getCode())));
}
@Test
void previewShouldRejectFilenameThatOriginalImporterCannotRoute() throws Exception {
MockMultipartFile file = workbook("理论题库.xlsx", sheet -> cell(sheet, 4, "判断题"));
assertThrows(BusinessException.class, () -> service.preview(file));
}
@Test
void confirmPreparationShouldMakeSelectedAnswerVisibleToLegacySplitter() throws Exception {
when(theoreticalLibraryMapper.selectList(any())).thenReturn(Collections.emptyList());
MockMultipartFile file = workbook("污水三级理论题库.xlsx", sheet -> {
hierarchy(sheet, 4, 0, "基本要求");
hierarchy(sheet, 5, 1, "职业道德");
hierarchy(sheet, 6, 2, "基本知识");
hierarchy(sheet, 7, 3, "知识点一");
cell(sheet, 8, "单选题");
cell(sheet, 9, "以下(B)方法常用于处理含铅(Pb)废水。");
cell(sheet, 10, "(A)吸附 (B)沉淀 (C)过滤 (D)消毒");
});
TheoreticalLibraryImportDecisionDTO decision = new TheoreticalLibraryImportDecisionDTO();
decision.setSourceRow(10);
decision.setAnswerCandidateIndex(0);
org.springframework.web.multipart.MultipartFile transformed =
service.prepareConfirmedFile(file, Collections.singletonList(decision));
try (Workbook workbook = WorkbookFactory.create(transformed.getInputStream())) {
String rewritten = workbook.getSheetAt(0).getRow(9).getCell(4).getStringCellValue();
assertEquals("以下(B)方法常用于处理含铅(Pb)废水。", rewritten);
// 处理后只剩答案位使用全角括号,旧 singleAnswer 的“最后括号”规则会稳定取得 B。
int lastBracket = rewritten.lastIndexOf('(');
assertEquals("B", String.valueOf(rewritten.charAt(lastBracket + 1)));
}
}
private MockMultipartFile workbook(String fileName, SheetWriter writer) throws Exception {
try (Workbook workbook = new XSSFWorkbook();
ByteArrayOutputStream output = new ByteArrayOutputStream()) {
Sheet sheet = workbook.createSheet("Sheet1");
writer.write(sheet);
workbook.write(output);
return new MockMultipartFile("file", fileName,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
output.toByteArray());
}
}
/** 写入旧模板第五列内容,行下标与 POI 保持从 0 开始。 */
private static void cell(Sheet sheet, int rowIndex, String value) {
Row row = sheet.getRow(rowIndex) == null ? sheet.createRow(rowIndex) : sheet.getRow(rowIndex);
row.createCell(4).setCellValue(value);
}
/** 写入层级编码列和第五列层级名称。 */
private static void hierarchy(Sheet sheet, int rowIndex, int depth, String value) {
Row row = sheet.createRow(rowIndex);
for (int i = 0; i <= depth; i++) {
row.createCell(i).setCellValue(i == 0 ? "0" : "1");
}
row.createCell(4).setCellValue(value);
}
@FunctionalInterface
private interface SheetWriter {
void write(Sheet sheet);
}
}
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