Commit 98561b99 authored by wujipeng's avatar wujipeng
Browse files

Merge remote-tracking branch 'origin/dev-v1.0' into dev-v1.0

parents aecd6374 1cf50da3
......@@ -3,6 +3,7 @@ package com.platform.business.model.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
/** 管理端评价任务列表和任务基础详情。 */
......@@ -19,9 +20,18 @@ public class EvaluationTaskVO {
private String className;
/** 班级所属工种,用于B10评议表的“培训职业(等级)”栏。 */
private String occupation;
/** 班级职业等级名称,例如“污泥五级”,用于生成B10评议表抬头。 */
private String levelName;
/** 原型中的课次信息,对应 class_subject.subject_times。 */
private Integer subjectTimes;
/** 当前课次的课时数,用于B10评议表课程信息栏。 */
private BigDecimal subjectHour;
private String teacherId;
private String teacherName;
......
......@@ -136,7 +136,7 @@ public class EvaluationController extends BaseController {
evaluationService.exportAdminTasks(query, response);
}
@ApiOperation("管理端-导出单个任务实名明细及维度统计Excel")
@ApiOperation("管理端-按已提交人员分别导出匿名B10评议表Word压缩包")
@GetMapping("/admin/{taskId}/export")
public void exportDetail(@PathVariable String taskId,
HttpServletRequest request,
......
......@@ -40,6 +40,6 @@ public interface EvaluationService {
/** 按当前管理端筛选条件导出任务汇总Excel。 */
void exportAdminTasks(EvaluationTaskQueryDTO query, HttpServletResponse response);
/** 导出单个任务的实名评价明细和七维度统计Excel。 */
/** 将单个任务内每条已提交评价分别生成匿名B10 Word,并打包为ZIP下载。 */
void exportTaskDetail(String taskId, HttpServletResponse response);
}
......@@ -30,6 +30,14 @@ 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.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHeightRule;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
......@@ -38,7 +46,9 @@ import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
......@@ -59,6 +69,8 @@ import java.util.Locale;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 学员评议核心业务实现。
......@@ -72,6 +84,8 @@ public class EvaluationServiceImpl implements EvaluationService {
private static final int MAX_BATCH_REVOKE_SIZE = 100;
private static final int MAX_COMMENT_LENGTH = 1000;
private static final String EVALUATION_WORD_TEMPLATE =
"templates/evaluation/B10-student-evaluation.docx";
/** 发布通知和历史通知详情统一使用该文案,避免同一撤回状态出现两种说法。 */
private static final String REVOKED_MESSAGE_CONTENT = "当前新增评价任务已被撤回";
......@@ -325,14 +339,154 @@ public class EvaluationServiceImpl implements EvaluationService {
public void exportTaskDetail(String taskId, HttpServletResponse response) {
refreshExpiredTasks();
EvaluationTaskDetailVO detail = adminDetail(taskId, null);
try (Workbook workbook = new XSSFWorkbook()) {
writeDetailSheet(workbook, detail);
writeStatisticsSheet(workbook, detail.getDimensionStatistics());
String courseName = isBlank(detail.getCourseName()) ? "课程" : detail.getCourseName();
writeWorkbook(response, workbook, courseName + "-学员评议明细.xlsx");
List<EvaluationRecordVO> submittedRecords = detail.getRecords() == null
? Collections.emptyList() : detail.getRecords().stream()
.filter(record -> EvaluationConstants.RECORD_SUBMITTED.equals(record.getStatus()))
.collect(Collectors.toList());
if (submittedRecords.isEmpty()) {
throw new BusinessException("暂无已提交的评价结果可导出");
}
String courseName = isBlank(detail.getCourseName()) ? "课程" : detail.getCourseName();
setDownloadHeaders(response, "application/zip", courseName + "-学员评议表.zip");
try (OutputStream output = response.getOutputStream();
ZipOutputStream zip = new ZipOutputStream(output)) {
for (int i = 0; i < submittedRecords.size(); i++) {
// 压缩包内只使用顺序号区分文档,避免文件名或正文泄露学员姓名和手机号。
zip.putNextEntry(new ZipEntry(String.format(Locale.ROOT,
"学员评议表-%03d.docx", i + 1)));
try (XWPFDocument document = createEvaluationDocument(detail, submittedRecords.get(i))) {
document.write(zip);
}
zip.closeEntry();
}
zip.finish();
} catch (IOException e) {
throw new BusinessException("导出评议明细失败");
throw new BusinessException("导出学员评议表失败");
}
}
/**
* 为一条已提交记录创建一份B10评议表。
*
* <p>每次都重新读取模板,确保不同学员的勾选和意见不会串到下一份文档;模板中没有
* 学员身份槽位,本方法也不会写入姓名、手机号或学员ID。</p>
*/
private XWPFDocument createEvaluationDocument(EvaluationTaskDetailVO detail,
EvaluationRecordVO record) throws IOException {
InputStream template = getClass().getClassLoader().getResourceAsStream(EVALUATION_WORD_TEMPLATE);
if (template == null) {
throw new BusinessException("学员评议表模板不存在");
}
try (InputStream input = template) {
XWPFDocument document = new XWPFDocument(input);
populateEvaluationDocument(document, detail, record);
return document;
}
}
/** 按B10模板的固定槽位写入课程信息、七项勾选、意见和提交日期。 */
private void populateEvaluationDocument(XWPFDocument document,
EvaluationTaskDetailVO detail,
EvaluationRecordVO record) {
if (document.getParagraphs().size() < 4 || document.getTables().isEmpty()) {
throw new BusinessException("学员评议表模板结构不正确");
}
replaceParagraphText(document.getParagraphs().get(1), trainingLevelText(detail));
XWPFTable table = document.getTables().get(0);
if (table.getNumberOfRows() < 16) {
throw new BusinessException("学员评议表模板结构不正确");
}
// 模板原始行为固定行高;课程名或意见较长时会被裁切,改为“最小高度”后仍保持原版式,
// 仅在内容确实超出时自动增高。
allowRowToGrow(table.getRow(0));
allowRowToGrow(table.getRow(15));
replaceCellText(table.getRow(0).getCell(1), "课程:" + value(detail.getCourseName())
+ " 课时数:" + decimalText(detail.getSubjectHour())
+ " 任课教师:" + value(detail.getTeacherName()));
markScore(table, 2, record.getTeachingAttitude(), "教学态度");
markScore(table, 4, record.getTeachingContent(), "教学内容");
markScore(table, 6, record.getTeachingMethod(), "教学方法");
markScore(table, 8, record.getTeachingMeans(), "教学手段");
markScore(table, 10, record.getDemonstration(), "讲解示范");
markScore(table, 12, record.getGuidance(), "巡回指导");
markScore(table, 14, record.getClassHourCompletion(), "课时完成情况");
// 最后一行右侧四个视觉网格合并为一个物理单元格,在POI中索引为1。
replaceCellText(table.getRow(15).getCell(1), value(record.getComment()));
replaceParagraphText(document.getParagraphs().get(3), evaluationDateText(record.getSubmittedAt()));
}
/** 在每个评分维度对应的四档单元格中仅写入一个勾选符号。 */
private void markScore(XWPFTable table, int rowIndex, String score, String dimensionName) {
int columnIndex;
if (EvaluationConstants.SCORE_GOOD.equals(score)) {
columnIndex = 2;
} else if (EvaluationConstants.SCORE_FAIR.equals(score)) {
columnIndex = 3;
} else if (EvaluationConstants.SCORE_OK.equals(score)) {
columnIndex = 4;
} else if (EvaluationConstants.SCORE_POOR.equals(score)) {
columnIndex = 5;
} else {
throw new BusinessException("评价记录评分数据不完整:" + dimensionName);
}
replaceCellText(table.getRow(rowIndex).getCell(columnIndex), "√");
}
/**
* 替换现有段落文字时复制首个文本运行的格式,避免setText重建段落后破坏模板字号和字形。
*/
private void replaceParagraphText(XWPFParagraph paragraph, String text) {
List<XWPFRun> runs = paragraph.getRuns();
CTRPr runProperties = runs.isEmpty() || !runs.get(0).getCTR().isSetRPr()
? null : (CTRPr) runs.get(0).getCTR().getRPr().copy();
for (int i = runs.size() - 1; i >= 0; i--) {
paragraph.removeRun(i);
}
XWPFRun run = paragraph.createRun();
if (runProperties != null) {
run.getCTR().setRPr(runProperties);
}
run.setText(text == null ? "" : text);
}
/** 合并单元格由多个网格坐标指向同一底层单元格,因此统一写第一个可见段落。 */
private void replaceCellText(XWPFTableCell cell, String text) {
if (cell == null) {
throw new BusinessException("学员评议表模板结构不正确");
}
replaceParagraphText(cell.getParagraphs().get(0), text);
}
/** 将模板的精确行高改为最小行高,防止合法的长课程名或意见内容在Word中被截断。 */
private void allowRowToGrow(XWPFTableRow row) {
if (row != null && row.getCtRow().getTrPr() != null
&& row.getCtRow().getTrPr().sizeOfTrHeightArray() > 0) {
row.getCtRow().getTrPr().getTrHeightArray(0).setHRule(STHeightRule.AT_LEAST);
}
}
private String trainingLevelText(EvaluationTaskDetailVO detail) {
String occupation = value(detail.getOccupation());
String level = value(detail.getLevelName());
if (!isBlank(occupation) && level.startsWith(occupation)) {
level = level.substring(occupation.length());
}
String vocation = isBlank(occupation) ? "" : occupation + "处理工";
String grade = isBlank(level) ? "" : "(" + level + ")";
return "培训职业(等级):" + vocation + grade
+ " 标号: 评议表编号:";
}
private String decimalText(BigDecimal number) {
return number == null ? "" : number.stripTrailingZeros().toPlainString();
}
private String evaluationDateText(Date date) {
return date == null ? "评议日期" : "评议日期 "
+ new SimpleDateFormat("yyyy 年 M 月 d 日").format(date);
}
/** 到达截止时间后采用惰性推进;列表、详情、提交和撤回入口均会先调用。 */
......@@ -536,39 +690,6 @@ public class EvaluationServiceImpl implements EvaluationService {
return item;
}
private void writeDetailSheet(Workbook workbook, EvaluationTaskDetailVO detail) {
Sheet sheet = workbook.createSheet("评价明细");
String[] headers = {"学员姓名", "手机号", "教学态度", "教学内容", "教学方法", "教学手段",
"讲解示范", "巡回指导", "课时完成情况", "意见与建议", "提交时间", "状态"};
writeHeader(sheet, headers, createHeaderStyle(workbook));
int rowIndex = 1;
for (EvaluationRecordVO record : detail.getRecords()) {
Row row = sheet.createRow(rowIndex++);
writeCells(row, Arrays.asList(record.getStudentName(), record.getPhoneNumber(), scoreLabel(record.getTeachingAttitude()),
scoreLabel(record.getTeachingContent()), scoreLabel(record.getTeachingMethod()),
scoreLabel(record.getTeachingMeans()), scoreLabel(record.getDemonstration()),
scoreLabel(record.getGuidance()), scoreLabel(record.getClassHourCompletion()),
record.getComment(), formatDate(record.getSubmittedAt()),
EvaluationConstants.RECORD_SUBMITTED.equals(record.getStatus()) ? "已评价" : "待评价"));
}
autoSize(sheet, headers.length);
sheet.setColumnWidth(9, 45 * 256);
}
private void writeStatisticsSheet(Workbook workbook, List<EvaluationDimensionStatisticsVO> statistics) {
Sheet sheet = workbook.createSheet("维度统计");
String[] headers = {"评分维度", "好", "较好", "尚可", "差", "已评人数", "四分制平均分"};
writeHeader(sheet, headers, createHeaderStyle(workbook));
int rowIndex = 1;
for (EvaluationDimensionStatisticsVO item : statistics) {
Row row = sheet.createRow(rowIndex++);
writeCells(row, Arrays.asList(item.getDimensionName(), value(item.getGoodCount()),
value(item.getFairCount()), value(item.getOkCount()), value(item.getPoorCount()),
value(item.getSubmittedCount()), value(item.getAverageScore())));
}
autoSize(sheet, headers.length);
}
private CellStyle createHeaderStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
......@@ -604,16 +725,28 @@ public class EvaluationServiceImpl implements EvaluationService {
}
private void writeWorkbook(HttpServletResponse response, Workbook workbook, String filename) throws IOException {
String encoded = URLEncoder.encode(filename, "UTF-8").replace("+", "%20");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encoded);
setDownloadHeaders(response,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", filename);
try (OutputStream output = response.getOutputStream()) {
workbook.write(output);
output.flush();
}
}
/** Excel和ZIP下载共用RFC 5987文件名编码,中文名称不会在不同浏览器中变成乱码。 */
private void setDownloadHeaders(HttpServletResponse response, String contentType,
String filename) {
try {
String encoded = URLEncoder.encode(filename, "UTF-8").replace("+", "%20");
response.setCharacterEncoding("UTF-8");
response.setContentType(contentType);
response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encoded);
} catch (IOException e) {
// Java 8运行环境必须支持UTF-8;保留明确异常,避免静默返回无文件名的下载响应。
throw new BusinessException("导出文件名编码失败");
}
}
private String taskStatusMessage(String status) {
if (EvaluationConstants.TASK_COMPLETED.equals(status)) {
return "评价任务已完成";
......@@ -635,14 +768,6 @@ public class EvaluationServiceImpl implements EvaluationService {
return value(status);
}
private String scoreLabel(String score) {
if (EvaluationConstants.SCORE_GOOD.equals(score)) return "好";
if (EvaluationConstants.SCORE_FAIR.equals(score)) return "较好";
if (EvaluationConstants.SCORE_OK.equals(score)) return "尚可";
if (EvaluationConstants.SCORE_POOR.equals(score)) return "差";
return "";
}
private String formatDate(Date date) {
return date == null ? "" : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
}
......
......@@ -9,7 +9,10 @@
cs.subject_name as courseName,
cs.class_id as classId,
c.name as className,
c.occupation,
level_info.name as levelName,
cs.subject_times as subjectTimes,
cs.subject_hour as subjectHour,
cs.teacher_id as teacherId,
teacher.nick_name as teacherName,
cs.date as courseDate,
......@@ -34,6 +37,7 @@
<sql id="taskViewJoins">
inner join class_subject cs on cs.id = t.subject_id
inner join class c on c.id = cs.class_id
left join sys_level level_info on cast(level_info.id as char) = c.level
left join user teacher on teacher.id = cs.teacher_id
left join user creator on creator.id = t.created_by
left join user revoker on revoker.id = t.revoked_by
......
......@@ -2,7 +2,8 @@
接口统一前缀:`/evaluation`。所有接口都要求请求头携带 `Authorization: Bearer <token>`。
本模块只有学员端和管理端。教师端没有接口;评价不支持匿名,只有管理员能够查看班级实名评价明细。
本模块只有学员端和管理端。教师端没有接口;数据库评价记录不匿名,只有管理员能够查看班级
实名评价明细,B10 Word 导出则按归档要求隐藏学员姓名和手机号。
## 状态与评分枚举
......@@ -137,9 +138,11 @@
### 导出
- 按列表筛选条件导出汇总:`POST /evaluation/admin/export`,请求体与管理端分页筛选一致。
- 导出单任务实名明细和维度统计:`GET /evaluation/admin/{taskId}/export`。
- 按单任务中已提交的评价记录逐人导出匿名B10评议表:`GET /evaluation/admin/{taskId}/export`。
响应文件格式为 `.xlsx`。
任务汇总响应为 `.xlsx`;单任务导出响应为 `.zip`,其中每条已提交评价对应一份独立
`.docx`。压缩包内文件按三位顺序号命名,文档及文件名均不包含学员姓名或手机号;尚未提交
的记录没有评价结果,因此不生成文档。
## 数据库部署
......
......@@ -24,7 +24,12 @@ import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.mock.web.MockHttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
......@@ -32,10 +37,14 @@ import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
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.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
......@@ -273,6 +282,101 @@ class EvaluationServiceImplTest {
org.junit.jupiter.api.Assertions.assertTrue(json.contains("\"evaluationProgress\":\"1/3\""));
}
@Test
void exportTaskDetailShouldCreateOneAnonymousWordPerSubmittedRecord() throws Exception {
EvaluationTaskVO task = new EvaluationTaskVO();
task.setId("T1");
task.setCourseName("污泥输送与处理");
task.setOccupation("污泥");
task.setLevelName("污泥五级");
task.setSubjectHour(new BigDecimal("8.0"));
task.setTeacherName("授课教师甲");
EvaluationRecordVO first = submittedRecord("学员甲", "建议增加实操时间",
EvaluationConstants.SCORE_GOOD);
EvaluationRecordVO second = submittedRecord("学员乙", "讲解清晰",
EvaluationConstants.SCORE_FAIR);
EvaluationRecordVO pending = new EvaluationRecordVO();
pending.setStatus(EvaluationConstants.RECORD_PENDING);
pending.setStudentName("未提交学员");
when(taskMapper.selectTaskView("T1")).thenReturn(task);
when(recordMapper.queryTaskRecords("T1", null)).thenReturn(Arrays.asList(first, second, pending));
MockHttpServletResponse response = new MockHttpServletResponse();
service.exportTaskDetail("T1", response);
assertEquals("application/zip", response.getContentType());
assertTrue(response.getHeader("Content-Disposition").contains(".zip"));
try (ZipInputStream zip = new ZipInputStream(
new ByteArrayInputStream(response.getContentAsByteArray()))) {
ZipEntry firstEntry = zip.getNextEntry();
assertEquals("学员评议表-001.docx", firstEntry.getName());
assertAnonymousEvaluationDocument(readZipEntry(zip), "建议增加实操时间", 2);
ZipEntry secondEntry = zip.getNextEntry();
assertEquals("学员评议表-002.docx", secondEntry.getName());
assertAnonymousEvaluationDocument(readZipEntry(zip), "讲解清晰", 3);
// 未提交记录没有评价结果,不应产生空白Word。
assertNull(zip.getNextEntry());
}
}
/** 构造七个维度均已提交的记录,确保测试覆盖模板全部勾选行。 */
private EvaluationRecordVO submittedRecord(String studentName, String comment, String score) {
EvaluationRecordVO record = new EvaluationRecordVO();
record.setStatus(EvaluationConstants.RECORD_SUBMITTED);
record.setStudentName(studentName);
record.setPhoneNumber("13800000000");
record.setTeachingAttitude(score);
record.setTeachingContent(score);
record.setTeachingMethod(score);
record.setTeachingMeans(score);
record.setDemonstration(score);
record.setGuidance(score);
record.setClassHourCompletion(score);
record.setComment(comment);
record.setSubmittedAt(new Date());
return record;
}
/** 读取当前ZIP条目的全部字节,不关闭ZipInputStream,以便继续检查后续文档。 */
private byte[] readZipEntry(ZipInputStream zip) throws Exception {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int length;
while ((length = zip.read(buffer)) != -1) {
output.write(buffer, 0, length);
}
return output.toByteArray();
}
/** 校验模板字段、勾选位置和匿名性,防止后续改动把实名信息重新写入导出文件。 */
private void assertAnonymousEvaluationDocument(byte[] content, String comment,
int selectedColumn) throws Exception {
try (XWPFDocument document = new XWPFDocument(new ByteArrayInputStream(content))) {
String text = document.getParagraphs().stream().map(paragraph -> paragraph.getText())
.collect(Collectors.joining("\n")) + document.getTables().get(0).getText();
assertTrue(text.contains("污泥处理工(五级)"));
assertTrue(text.contains("课程:污泥输送与处理"));
assertTrue(text.contains("课时数:8"));
assertTrue(text.contains("任课教师:授课教师甲"));
assertTrue(text.contains("评议日期"));
assertTrue(text.contains(comment));
assertFalse(text.contains("学员甲"));
assertFalse(text.contains("学员乙"));
assertFalse(text.contains("13800000000"));
// 七个评分行均应在同一档位出现一个勾选,其他档位保持空白。
int[] scoreRows = {2, 4, 6, 8, 10, 12, 14};
for (int row : scoreRows) {
assertEquals("√", document.getTables().get(0).getRow(row)
.getCell(selectedColumn).getText());
}
}
}
private EvaluationTaskEntity pendingTask() {
Calendar deadline = Calendar.getInstance();
deadline.add(Calendar.DAY_OF_MONTH, 1);
......
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