Commit 03bbec8e authored by wujipeng's avatar wujipeng
Browse files

教师-智能考评-成绩管理

parent 4d4449c1
package com.platform.business.model.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 教师端成绩管理的考试分页条件。
*
* <p>教师身份不属于查询条件,服务端只使用 JWT 解析出的当前用户 ID,避免调用方
* 通过请求体伪造 teacherId 查看其他教师负责的考试。</p>
*/
@Data
public class TeacherScoreExamQueryDTO {
@ApiModelProperty("页码,默认1")
private int pageNum;
@ApiModelProperty("每页条数,默认10,最大100")
private int pageSize;
@ApiModelProperty("班级ID;为空时查询当前教师负责的全部班级")
private Integer classId;
@ApiModelProperty("考试名称关键字,最多100个字符")
private String keyword;
}
package com.platform.business.model.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/** 教师端单场考试的应考学员分页条件。 */
@Data
public class TeacherScoreStudentQueryDTO {
@ApiModelProperty("页码,默认1")
private int pageNum;
@ApiModelProperty("每页条数,默认10,最大100")
private int pageSize;
@ApiModelProperty("学员姓名或身份证号关键字,最多100个字符")
private String keyword;
}
package com.platform.business.model.vo;
import lombok.Data;
/** 教师成绩页面的班级筛选选项。 */
@Data
public class TeacherScoreClassOptionVO {
private Integer classId;
private String className;
}
package com.platform.business.model.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
/** 教师端成绩管理的考试汇总行,同时用于成绩详情页头部。 */
@Data
public class TeacherScoreExamVO {
private Integer examId;
private Integer classId;
private String examName;
private String className;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date examTime;
private Integer duration;
private BigDecimal totalScore;
private BigDecimal passScore;
private Integer expectedCount;
private Integer actualCount;
@ApiModelProperty("已交卷、成绩已正式发布且成绩非空的学员数")
private Integer publishedScoreCount;
@ApiModelProperty("正式成绩中的最高分;没有正式成绩时为null")
private BigDecimal highestScore;
@ApiModelProperty("正式成绩中的最低分;没有正式成绩时为null")
private BigDecimal lowestScore;
@ApiModelProperty("正式成绩平均分,保留一位小数;没有正式成绩时为null")
private BigDecimal averageScore;
@ApiModelProperty("及格人数/正式成绩人数,保留两位小数;没有正式成绩时为null")
private BigDecimal passRate;
}
package com.platform.business.model.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.math.BigDecimal;
/** 教师端单场考试成绩详情中的应考学员。 */
@Data
public class TeacherScoreStudentVO {
private Integer examStudentId;
private Integer examId;
private Integer classId;
private String studentId;
private String studentName;
private String idCard;
private String className;
private String examName;
private Boolean submitted;
@ApiModelProperty("该学员成绩是否已经正式发布")
private Boolean published;
@ApiModelProperty("缺考或尚未正式发布时为null")
private BigDecimal score;
@ApiModelProperty("优秀/良好/及格/不及格;没有正式成绩时为null")
private String grade;
@ApiModelProperty("是否达到本场考试及格分;没有正式成绩时为null")
private Boolean passed;
private String answerTime;
private String duration;
}
package com.platform.business.controller;
import com.platform.business.model.dto.TeacherScoreExamQueryDTO;
import com.platform.business.model.dto.TeacherScoreStudentQueryDTO;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.TeacherScoreClassOptionVO;
import com.platform.business.model.vo.TeacherScoreExamVO;
import com.platform.business.service.AuthenticatedUserService;
import com.platform.business.service.TeacherScoreService;
import com.platform.controller.BaseController;
import com.platform.model.resp.Result;
import com.platform.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 教师端“智能考评-成绩管理”接口。
*
* <p>所有入口都从 Authorization 解析当前教师,不提供 teacherId 请求参数;考试归属
* 还会在 Mapper 层按 chief_id 再次过滤,确保教师只能读取本人主考的正式成绩。</p>
*/
@Api(tags = "教师端-成绩管理")
@RestController
@RequestMapping("/exam/teacher/scores")
public class TeacherScoreController extends BaseController {
@Resource
private TeacherScoreService teacherScoreService;
@Resource
private AuthenticatedUserService authenticatedUserService;
@ApiOperation("成绩管理班级筛选选项")
@GetMapping("/classes")
public Result<List<TeacherScoreClassOptionVO>> classes(HttpServletRequest request) {
return Result.data(teacherScoreService.classes(currentTeacherId(request)));
}
@ApiOperation("本人主考的已发布历史考试分页列表")
@PostMapping("/exams/page")
public TableDataInfo exams(@RequestBody(required = false) TeacherScoreExamQueryDTO query,
HttpServletRequest request) {
TeacherScoreExamQueryDTO safeQuery = query == null
? new TeacherScoreExamQueryDTO() : query;
normalizePage(safeQuery);
String teacherId = currentTeacherId(request);
startPage(safeQuery.getPageNum(), safeQuery.getPageSize());
return getDataTable(teacherScoreService.exams(safeQuery, teacherId));
}
@ApiOperation("单场考试成绩汇总")
@GetMapping("/exams/{examId}")
public Result<TeacherScoreExamVO> exam(@PathVariable Integer examId,
HttpServletRequest request) {
return Result.data(teacherScoreService.exam(examId, currentTeacherId(request)));
}
@ApiOperation("单场考试全部应考学员成绩分页列表")
@PostMapping("/exams/{examId}/students/page")
public TableDataInfo students(@PathVariable Integer examId,
@RequestBody(required = false) TeacherScoreStudentQueryDTO query,
HttpServletRequest request) {
TeacherScoreStudentQueryDTO safeQuery = query == null
? new TeacherScoreStudentQueryDTO() : query;
normalizePage(safeQuery);
String teacherId = currentTeacherId(request);
startPage(safeQuery.getPageNum(), safeQuery.getPageSize());
return getDataTable(teacherScoreService.students(examId, safeQuery, teacherId));
}
@ApiOperation("导出单场考试全部应考学员成绩")
@GetMapping("/exams/{examId}/export")
public void exportExam(@PathVariable Integer examId, HttpServletRequest request,
HttpServletResponse response) {
teacherScoreService.exportExam(examId, currentTeacherId(request), response);
}
/** 统一完成JWT解析与教师角色检查,并且只向业务层返回可信教师ID。 */
private String currentTeacherId(HttpServletRequest request) {
UserEntity teacher = authenticatedUserService.current(request);
authenticatedUserService.requireTeacher(teacher);
return teacher.getId();
}
private void normalizePage(TeacherScoreExamQueryDTO query) {
query.setPageNum(query.getPageNum() <= 0 ? 1 : query.getPageNum());
query.setPageSize(normalizePageSize(query.getPageSize()));
}
private void normalizePage(TeacherScoreStudentQueryDTO query) {
query.setPageNum(query.getPageNum() <= 0 ? 1 : query.getPageNum());
query.setPageSize(normalizePageSize(query.getPageSize()));
}
private int normalizePageSize(int pageSize) {
return pageSize <= 0 ? 10 : Math.min(pageSize, 100);
}
}
package com.platform.business.mapper;
import com.platform.business.model.dto.TeacherScoreExamQueryDTO;
import com.platform.business.model.dto.TeacherScoreStudentQueryDTO;
import com.platform.business.model.vo.TeacherScoreClassOptionVO;
import com.platform.business.model.vo.TeacherScoreExamVO;
import com.platform.business.model.vo.TeacherScoreStudentVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 教师端成绩管理专用查询。
*
* <p>所有涉及考试内容的方法都显式接收 teacherId,并在 SQL 中使用 exam.chief_id
* 校验归属。该限制不能只放在 Controller 中,否则猜测 examId 仍可能造成越权读取。</p>
*/
@Mapper
public interface TeacherScoreMapper {
List<TeacherScoreClassOptionVO> queryClasses(@Param("teacherId") String teacherId);
List<TeacherScoreExamVO> queryExams(@Param("teacherId") String teacherId,
@Param("query") TeacherScoreExamQueryDTO query);
TeacherScoreExamVO findExam(@Param("examId") Integer examId,
@Param("teacherId") String teacherId);
List<TeacherScoreStudentVO> queryStudents(@Param("examId") Integer examId,
@Param("teacherId") String teacherId,
@Param("query") TeacherScoreStudentQueryDTO query);
List<TeacherScoreStudentVO> queryExportStudents(@Param("examId") Integer examId,
@Param("teacherId") String teacherId);
}
package com.platform.business.service;
import com.platform.business.model.dto.TeacherScoreExamQueryDTO;
import com.platform.business.model.dto.TeacherScoreStudentQueryDTO;
import com.platform.business.model.vo.TeacherScoreClassOptionVO;
import com.platform.business.model.vo.TeacherScoreExamVO;
import com.platform.business.model.vo.TeacherScoreStudentVO;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/** 教师端“智能考评-成绩管理”业务接口。 */
public interface TeacherScoreService {
List<TeacherScoreClassOptionVO> classes(String teacherId);
List<TeacherScoreExamVO> exams(TeacherScoreExamQueryDTO query, String teacherId);
TeacherScoreExamVO exam(Integer examId, String teacherId);
List<TeacherScoreStudentVO> students(Integer examId, TeacherScoreStudentQueryDTO query,
String teacherId);
void exportExam(Integer examId, String teacherId, HttpServletResponse response);
}
package com.platform.business.service.impl;
import com.platform.business.mapper.TeacherScoreMapper;
import com.platform.business.model.dto.TeacherScoreExamQueryDTO;
import com.platform.business.model.dto.TeacherScoreStudentQueryDTO;
import com.platform.business.model.vo.TeacherScoreClassOptionVO;
import com.platform.business.model.vo.TeacherScoreExamVO;
import com.platform.business.model.vo.TeacherScoreStudentVO;
import com.platform.business.service.TeacherScoreService;
import com.platform.exception.BusinessException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
/**
* 教师端成绩查询与导出实现。
*
* <p>权限采用“双层保护”:Controller 负责校验当前用户确实具有教师角色,本服务传递
* JWT 中的教师 ID,Mapper 的每一条考试查询再通过 exam.chief_id 校验业务归属。</p>
*/
@Service
public class TeacherScoreServiceImpl implements TeacherScoreService {
private static final int MAX_KEYWORD_LENGTH = 100;
private static final String[] EXPORT_HEADERS = {
"序号", "考试名称", "班级", "学员姓名", "身份证号",
"参考状态", "成绩", "等级", "是否及格", "交卷时间", "答题时长"
};
@Resource
private TeacherScoreMapper teacherScoreMapper;
@Override
@Transactional(readOnly = true)
public List<TeacherScoreClassOptionVO> classes(String teacherId) {
String safeTeacherId = requireTeacherId(teacherId);
List<TeacherScoreClassOptionVO> result = teacherScoreMapper.queryClasses(safeTeacherId);
return result == null ? Collections.emptyList() : result;
}
@Override
@Transactional(readOnly = true)
public List<TeacherScoreExamVO> exams(TeacherScoreExamQueryDTO query, String teacherId) {
String safeTeacherId = requireTeacherId(teacherId);
normalizeExamQuery(query);
List<TeacherScoreExamVO> result = teacherScoreMapper.queryExams(safeTeacherId, query);
return result == null ? Collections.emptyList() : result;
}
@Override
@Transactional(readOnly = true)
public TeacherScoreExamVO exam(Integer examId, String teacherId) {
return requireOwnedPublishedExam(examId, teacherId);
}
@Override
@Transactional(readOnly = true)
public List<TeacherScoreStudentVO> students(Integer examId, TeacherScoreStudentQueryDTO query,
String teacherId) {
String safeTeacherId = requireTeacherId(teacherId);
requirePositiveId(examId, "考试ID");
normalizeStudentQuery(query);
List<TeacherScoreStudentVO> result = teacherScoreMapper.queryStudents(
examId, safeTeacherId, query);
if (result == null || result.isEmpty()) {
/*
* 分页由 Controller 在调用本方法前启动,PageHelper 只作用于第一次查询,因此必须
* 先执行真正的学员列表查询。列表为空后再查考试归属,既不会吞掉分页设置,又能
* 区分“合法考试暂无匹配学员”和“考试不存在或越权”。
*/
requireOwnedPublishedExam(examId, safeTeacherId);
// result 可能是 PageHelper 的空 Page,必须原样返回以保留总记录数等分页元数据。
return result == null ? Collections.emptyList() : result;
}
return result;
}
@Override
@Transactional(readOnly = true)
public void exportExam(Integer examId, String teacherId, HttpServletResponse response) {
String safeTeacherId = requireTeacherId(teacherId);
TeacherScoreExamVO exam = requireOwnedPublishedExam(examId, safeTeacherId);
List<TeacherScoreStudentVO> students = teacherScoreMapper.queryExportStudents(
examId, safeTeacherId);
if (students == null || students.isEmpty()) {
throw new BusinessException("本场考试暂无应考学员,不能导出成绩单");
}
try (XSSFWorkbook workbook = new XSSFWorkbook()) {
Sheet sheet = workbook.createSheet("成绩明细");
writeExportSheet(sheet, students, workbook);
writeWorkbook(response, workbook, safeFileName(exam.getExamName()) + "_成绩单.xlsx");
} catch (IOException e) {
throw new BusinessException("成绩单导出失败,请稍后重试");
}
}
/** 清洗考试分页条件,防止超长模糊查询和非法班级ID进入数据库。 */
void normalizeExamQuery(TeacherScoreExamQueryDTO query) {
if (query == null) {
throw new BusinessException("查询条件不能为空");
}
if (query.getClassId() != null) {
requirePositiveId(query.getClassId(), "班级ID");
}
query.setKeyword(normalizeKeyword(query.getKeyword(), "考试名称关键字"));
}
/** 清洗学员列表关键字;分页边界由 Controller 在启动 PageHelper 前统一处理。 */
void normalizeStudentQuery(TeacherScoreStudentQueryDTO query) {
if (query == null) {
throw new BusinessException("查询条件不能为空");
}
query.setKeyword(normalizeKeyword(query.getKeyword(), "学员关键字"));
}
/**
* 只返回当前教师本人主考、已经结束且正式发布的考试。
* Mapper 将不存在、未结束、未发布和不属于本人统一查询为空,避免暴露其他考试状态。
*/
private TeacherScoreExamVO requireOwnedPublishedExam(Integer examId, String teacherId) {
requirePositiveId(examId, "考试ID");
String safeTeacherId = requireTeacherId(teacherId);
TeacherScoreExamVO exam = teacherScoreMapper.findExam(examId, safeTeacherId);
if (exam == null) {
throw new BusinessException("考试不存在或无权访问");
}
return exam;
}
private String requireTeacherId(String teacherId) {
if (!StringUtils.hasText(teacherId)) {
throw new BusinessException("当前教师身份无效");
}
return teacherId.trim();
}
private void requirePositiveId(Integer id, String fieldName) {
if (id == null || id <= 0) {
throw new BusinessException(fieldName + "必须为正整数");
}
}
private String normalizeKeyword(String keyword, String fieldName) {
if (!StringUtils.hasText(keyword)) {
return null;
}
String normalized = keyword.trim();
if (normalized.length() > MAX_KEYWORD_LENGTH) {
throw new BusinessException(fieldName + "不能超过" + MAX_KEYWORD_LENGTH + "个字符");
}
return normalized;
}
/**
* 导出全部应考学员。缺考人员保留在表格中并把成绩单元格留空;已交卷但尚未补充
* 发布的历史异常记录标记为“成绩待发布”,避免把空分误解成零分。
*/
private void writeExportSheet(Sheet sheet, List<TeacherScoreStudentVO> students,
XSSFWorkbook workbook) {
CellStyle headerStyle = createHeaderStyle(workbook);
CellStyle bodyStyle = createBodyStyle(workbook);
Row header = sheet.createRow(0);
for (int i = 0; i < EXPORT_HEADERS.length; i++) {
Cell cell = header.createCell(i);
cell.setCellValue(EXPORT_HEADERS[i]);
cell.setCellStyle(headerStyle);
}
int rowIndex = 1;
for (TeacherScoreStudentVO student : students) {
Row row = sheet.createRow(rowIndex);
writeTextCell(row, 0, String.valueOf(rowIndex), bodyStyle);
writeTextCell(row, 1, student.getExamName(), bodyStyle);
writeTextCell(row, 2, student.getClassName(), bodyStyle);
writeTextCell(row, 3, student.getStudentName(), bodyStyle);
writeTextCell(row, 4, student.getIdCard(), bodyStyle);
writeTextCell(row, 5, participationStatus(student), bodyStyle);
// POI 不创建值即可得到真正的空单元格,前端打开后不会看到0或字符串“null”。
Cell scoreCell = row.createCell(6);
scoreCell.setCellStyle(bodyStyle);
if (student.getScore() != null) {
scoreCell.setCellValue(student.getScore().doubleValue());
}
writeTextCell(row, 7, student.getGrade(), bodyStyle);
writeTextCell(row, 8, passLabel(student), bodyStyle);
writeTextCell(row, 9, student.getAnswerTime(), bodyStyle);
writeTextCell(row, 10, student.getDuration(), bodyStyle);
rowIndex++;
}
int[] widths = {8, 28, 22, 14, 24, 14, 12, 12, 12, 20, 14};
for (int i = 0; i < widths.length; i++) {
sheet.setColumnWidth(i, widths[i] * 256);
}
sheet.createFreezePane(0, 1);
}
private String participationStatus(TeacherScoreStudentVO student) {
if (!Boolean.TRUE.equals(student.getSubmitted())) {
return "缺考";
}
return Boolean.TRUE.equals(student.getPublished()) ? "实考" : "成绩待发布";
}
private String passLabel(TeacherScoreStudentVO student) {
if (student.getPassed() == null) {
return "";
}
return Boolean.TRUE.equals(student.getPassed()) ? "是" : "否";
}
private void writeTextCell(Row row, int index, String value, CellStyle style) {
Cell cell = row.createCell(index);
cell.setCellValue(value == null ? "" : value);
cell.setCellStyle(style);
}
private CellStyle createHeaderStyle(XSSFWorkbook workbook) {
CellStyle style = workbook.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
Font font = workbook.createFont();
font.setBold(true);
style.setFont(font);
return style;
}
private CellStyle createBodyStyle(XSSFWorkbook workbook) {
CellStyle style = workbook.createCellStyle();
style.setVerticalAlignment(org.apache.poi.ss.usermodel.VerticalAlignment.CENTER);
return style;
}
private void writeWorkbook(HttpServletResponse response, XSSFWorkbook workbook,
String fileName) throws IOException {
String encoded = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name())
.replace("+", "%20");
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
response.setContentType(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encoded);
workbook.write(response.getOutputStream());
}
/** 删除文件系统不兼容字符,避免考试名称导致下载失败。 */
private String safeFileName(String name) {
String safe = StringUtils.hasText(name) ? name.trim() : "考试";
safe = safe.replaceAll("[\\\\/:*?\"<>|]", "_");
return safe.length() > 80 ? safe.substring(0, 80) : safe;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.platform.business.mapper.TeacherScoreMapper">
<!--
成绩页面只展示已结束且考试主记录已经发布的考试。结束时间使用考试开始时间加时长
计算,避免仅按日期判断时把仍在进行的考试提前暴露到历史成绩页面。
-->
<sql id="visibleExamCondition">
e.chief_id = #{teacherId}
AND IFNULL(e.mark_flag, 0) = 1
AND DATE_ADD(e.exam_time, INTERVAL IFNULL(e.duration, 0) MINUTE) &lt;= NOW()
</sql>
<!--
应考、实考与正式成绩是三个不同口径:
1. 应考统计全部 exam_student;
2. 实考只判断 submit;
3. 分数统计还要求学员 mark_flag 已发布且 score 非空。
这样历史异常数据或补交试卷不会把未发布分数混入最高分、平均分和及格率。
-->
<sql id="examSummaryColumns">
e.id AS examId,
e.class_id AS classId,
e.name AS examName,
c.name AS className,
e.exam_time AS examTime,
e.duration,
e.total_score AS totalScore,
e.pass_score AS passScore,
COUNT(es.id) AS expectedCount,
COALESCE(SUM(CASE WHEN IFNULL(es.submit, 0) = 1 THEN 1 ELSE 0 END), 0) AS actualCount,
COALESCE(SUM(CASE
WHEN IFNULL(es.submit, 0) = 1
AND IFNULL(es.mark_flag, 0) = 1
AND es.score IS NOT NULL THEN 1 ELSE 0
END), 0) AS publishedScoreCount,
MAX(CASE
WHEN IFNULL(es.submit, 0) = 1
AND IFNULL(es.mark_flag, 0) = 1 THEN es.score
END) AS highestScore,
MIN(CASE
WHEN IFNULL(es.submit, 0) = 1
AND IFNULL(es.mark_flag, 0) = 1 THEN es.score
END) AS lowestScore,
ROUND(AVG(CASE
WHEN IFNULL(es.submit, 0) = 1
AND IFNULL(es.mark_flag, 0) = 1 THEN es.score
END), 1) AS averageScore,
CASE
WHEN SUM(CASE
WHEN IFNULL(es.submit, 0) = 1
AND IFNULL(es.mark_flag, 0) = 1
AND es.score IS NOT NULL THEN 1 ELSE 0
END) = 0 THEN NULL
ELSE ROUND(
SUM(CASE
WHEN IFNULL(es.submit, 0) = 1
AND IFNULL(es.mark_flag, 0) = 1
AND es.score IS NOT NULL
AND es.score &gt;= IFNULL(e.pass_score, 60) THEN 1 ELSE 0
END) * 100.0 /
SUM(CASE
WHEN IFNULL(es.submit, 0) = 1
AND IFNULL(es.mark_flag, 0) = 1
AND es.score IS NOT NULL THEN 1 ELSE 0
END), 2)
END AS passRate
</sql>
<sql id="examSummaryJoins">
FROM exam e
LEFT JOIN exam_student es ON es.exam_id = e.id
LEFT JOIN class c ON c.id = e.class_id
</sql>
<sql id="examSummaryGroup">
GROUP BY e.id, e.class_id, e.name, c.name, e.exam_time, e.duration,
e.total_score, e.pass_score
</sql>
<select id="queryClasses" resultType="com.platform.business.model.vo.TeacherScoreClassOptionVO">
SELECT DISTINCT c.id AS classId, c.name AS className
FROM exam e
INNER JOIN class c ON c.id = e.class_id
WHERE <include refid="visibleExamCondition"/>
ORDER BY c.name, c.id
</select>
<select id="queryExams" resultType="com.platform.business.model.vo.TeacherScoreExamVO">
SELECT <include refid="examSummaryColumns"/>
<include refid="examSummaryJoins"/>
WHERE <include refid="visibleExamCondition"/>
<if test="query.classId != null">
AND e.class_id = #{query.classId}
</if>
<if test="query.keyword != null and query.keyword != ''">
AND e.name LIKE CONCAT('%', #{query.keyword}, '%')
</if>
<include refid="examSummaryGroup"/>
ORDER BY e.exam_time DESC, e.id DESC
</select>
<!-- examId 与 teacherId 同时参与过滤,使不存在和越权访问得到相同结果。 -->
<select id="findExam" resultType="com.platform.business.model.vo.TeacherScoreExamVO">
SELECT <include refid="examSummaryColumns"/>
<include refid="examSummaryJoins"/>
WHERE e.id = #{examId}
AND <include refid="visibleExamCondition"/>
<include refid="examSummaryGroup"/>
</select>
<sql id="studentColumns">
es.id AS examStudentId,
es.exam_id AS examId,
es.class_id AS classId,
es.student_id AS studentId,
u.nick_name AS studentName,
u.id_card AS idCard,
c.name AS className,
e.name AS examName,
CASE WHEN IFNULL(es.submit, 0) = 1 THEN TRUE ELSE FALSE END AS submitted,
CASE
WHEN IFNULL(es.submit, 0) = 1
AND IFNULL(es.mark_flag, 0) = 1
AND es.score IS NOT NULL THEN TRUE ELSE FALSE
END AS published,
CASE
WHEN IFNULL(es.submit, 0) = 1
AND IFNULL(es.mark_flag, 0) = 1 THEN es.score
ELSE NULL
END AS score,
CASE
WHEN IFNULL(es.submit, 0) = 0
OR IFNULL(es.mark_flag, 0) = 0
OR es.score IS NULL THEN NULL
WHEN es.score &lt; IFNULL(e.pass_score, 60) THEN '不及格'
WHEN es.score &gt;= 90 THEN '优秀'
WHEN es.score &gt;= 80 THEN '良好'
ELSE '及格'
END AS grade,
CASE
WHEN IFNULL(es.submit, 0) = 0
OR IFNULL(es.mark_flag, 0) = 0
OR es.score IS NULL THEN NULL
WHEN es.score &gt;= IFNULL(e.pass_score, 60) THEN TRUE ELSE FALSE
END AS passed,
es.answer_time AS answerTime,
es.duration
</sql>
<sql id="studentFromAndPermission">
FROM exam_student es
INNER JOIN exam e ON e.id = es.exam_id
LEFT JOIN user u ON u.id = es.student_id
LEFT JOIN class c ON c.id = es.class_id
WHERE es.exam_id = #{examId}
AND e.chief_id = #{teacherId}
AND IFNULL(e.mark_flag, 0) = 1
AND DATE_ADD(e.exam_time, INTERVAL IFNULL(e.duration, 0) MINUTE) &lt;= NOW()
</sql>
<select id="queryStudents" resultType="com.platform.business.model.vo.TeacherScoreStudentVO">
SELECT <include refid="studentColumns"/>
<include refid="studentFromAndPermission"/>
<if test="query.keyword != null and query.keyword != ''">
AND (u.nick_name LIKE CONCAT('%', #{query.keyword}, '%')
OR u.id_card LIKE CONCAT('%', #{query.keyword}, '%'))
</if>
ORDER BY IFNULL(es.submit, 0) DESC, IFNULL(es.mark_flag, 0) DESC,
es.score DESC, u.nick_name, es.id
</select>
<!-- 导出不应用页面关键字和分页,必须覆盖该场考试的全部应考学员。 -->
<select id="queryExportStudents" resultType="com.platform.business.model.vo.TeacherScoreStudentVO">
SELECT <include refid="studentColumns"/>
<include refid="studentFromAndPermission"/>
ORDER BY IFNULL(es.submit, 0) DESC, IFNULL(es.mark_flag, 0) DESC,
es.score DESC, u.nick_name, es.id
</select>
</mapper>
# 教师端成绩管理接口
页面路径为“教师端 → 智能考评 → 成绩管理”,接口统一使用
`/exam/teacher/scores` 前缀。所有请求必须携带 `Authorization`。服务端从 JWT 解析当前
用户并校验“教师”角色,教师 ID 不允许由前端传入;所有考试查询还会校验
`exam.chief_id` 等于当前教师 ID。
本模块只读取现有 `exam`、`exam_student`、`class` 和 `user` 表。现有数据库脚本已经
提供 `idx_exam_chief_time` 与 `idx_exam_student_exam_user` 索引,因此本功能无数据库结构
变更,不需要执行新增迁移脚本。
## 统计口径
- 页面只展示已经结束且 `exam.mark_flag = 1` 的考试。
- 应考人数:该场考试全部 `exam_student` 记录数。
- 实考人数:`exam_student.submit = 1` 的人数。
- 最高分、最低分、平均分:只统计已交卷、`exam_student.mark_flag = 1` 且成绩非空的记录,平均分保留一位小数。
- 及格率:达到该场 `exam.pass_score` 的正式成绩人数 ÷ 正式成绩人数,保留两位小数。
- 没有正式成绩时,最高分、最低分、平均分和及格率均返回 `null`,不会返回误导性的零。
## 1. 班级筛选选项
`GET /exam/teacher/scores/classes`
只返回当前教师担任主考且存在已发布历史考试的班级:
```json
{
"code": 200,
"data": [
{"classId": 12, "className": "净化1班"},
{"classId": 15, "className": "净化2班"}
]
}
```
前端的“全部班级”不需要对应数据库记录,查询考试时不传 `classId` 即可。
## 2. 考试成绩分页列表
`POST /exam/teacher/scores/exams/page`
```json
{
"pageNum": 1,
"pageSize": 10,
"keyword": "月考",
"classId": 12
}
```
`keyword` 和 `classId` 均可省略。返回项目统一 `TableDataInfo`,`rows` 中每项结构如下:
```json
{
"examId": 101,
"classId": 12,
"examName": "污泥脱水工艺月考",
"className": "净化1班",
"examTime": "2026-08-10 09:00:00",
"duration": 90,
"totalScore": 100,
"passScore": 60,
"expectedCount": 32,
"actualCount": 31,
"publishedScoreCount": 31,
"highestScore": 96,
"lowestScore": 52,
"averageScore": 81.3,
"passRate": 93.55
}
```
默认按考试时间、考试 ID 倒序;页码默认 1,每页默认 10 条,最多 100 条。
## 3. 单场考试汇总
`GET /exam/teacher/scores/exams/{examId}`
返回结构与考试列表行一致,用于成绩详情页头部。考试不存在、不是当前教师主考、尚未
结束或成绩未发布时,统一提示“考试不存在或无权访问”,避免通过 ID 探测其他考试。
## 4. 应考学员成绩分页
`POST /exam/teacher/scores/exams/{examId}/students/page`
```json
{
"pageNum": 1,
"pageSize": 10,
"keyword": "张三"
}
```
关键字同时匹配学员姓名和身份证号。返回全部应考学员,缺考人员也会出现在列表中:
```json
{
"examStudentId": 9001,
"examId": 101,
"classId": 12,
"studentId": "student-1",
"studentName": "张三",
"idCard": "310000********0001",
"className": "净化1班",
"examName": "污泥脱水工艺月考",
"submitted": true,
"published": true,
"score": 88.5,
"grade": "良好",
"passed": true,
"answerTime": "2026-08-10 10:12:30",
"duration": "72分钟"
}
```
缺考人员的 `submitted`、`published` 为 `false`,`score`、`grade`、`passed` 为 `null`。
## 5. 导出单场考试成绩
`GET /exam/teacher/scores/exams/{examId}/export`
响应类型为
`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,文件名为
“考试名称_成绩单.xlsx”。导出不受页面关键字和分页影响,包含全部应考学员;缺考人员
标记为“缺考”且成绩单元格留空。前端应按二进制 Blob 接收响应,并优先从
`Content-Disposition` 读取 UTF-8 文件名。
package com.platform.business.controller;
import com.platform.business.model.dto.TeacherScoreExamQueryDTO;
import com.platform.business.model.dto.TeacherScoreStudentQueryDTO;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.service.AuthenticatedUserService;
import com.platform.business.service.TeacherScoreService;
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.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.ArgumentMatchers.eq;
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 TeacherScoreControllerTest {
@Mock
private TeacherScoreService teacherScoreService;
@Mock
private AuthenticatedUserService authenticatedUserService;
private TeacherScoreController controller;
@BeforeEach
void setUp() {
controller = new TeacherScoreController();
ReflectionTestUtils.setField(controller, "teacherScoreService", teacherScoreService);
ReflectionTestUtils.setField(controller, "authenticatedUserService", authenticatedUserService);
}
@Test
void allEndpointsShouldUseJwtTeacherAndNormalizePage() {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
UserEntity teacher = new UserEntity();
teacher.setId("teacher-1");
when(authenticatedUserService.current(request)).thenReturn(teacher);
when(teacherScoreService.classes("teacher-1")).thenReturn(Collections.emptyList());
when(teacherScoreService.exams(any(TeacherScoreExamQueryDTO.class), eq("teacher-1")))
.thenReturn(Collections.emptyList());
when(teacherScoreService.students(eq(11), any(TeacherScoreStudentQueryDTO.class),
eq("teacher-1"))).thenReturn(Collections.emptyList());
TeacherScoreExamQueryDTO examQuery = new TeacherScoreExamQueryDTO();
examQuery.setPageNum(0);
examQuery.setPageSize(1000);
TeacherScoreStudentQueryDTO studentQuery = new TeacherScoreStudentQueryDTO();
studentQuery.setPageNum(-1);
studentQuery.setPageSize(0);
controller.classes(request);
controller.exams(examQuery, request);
controller.exam(11, request);
controller.students(11, studentQuery, request);
controller.exportExam(11, request, response);
verify(authenticatedUserService, times(5)).requireTeacher(teacher);
verify(teacherScoreService).exam(11, "teacher-1");
verify(teacherScoreService).exportExam(11, "teacher-1", response);
assertEquals(1, examQuery.getPageNum());
assertEquals(100, examQuery.getPageSize());
assertEquals(1, studentQuery.getPageNum());
assertEquals(10, studentQuery.getPageSize());
}
@Test
void roleFailureShouldStopBeforeScoreService() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserEntity student = new UserEntity();
student.setId("student-1");
when(authenticatedUserService.current(request)).thenReturn(student);
doThrow(new BusinessException("只有教师可以访问教师端接口"))
.when(authenticatedUserService).requireTeacher(student);
assertThrows(BusinessException.class, () -> controller.exam(1, request));
}
}
package com.platform.business.mapper;
import com.platform.business.model.dto.TeacherScoreExamQueryDTO;
import com.platform.business.model.dto.TeacherScoreStudentQueryDTO;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.session.Configuration;
import org.junit.jupiter.api.Test;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** 教师成绩 SQL 的启动解析、教师归属限制和正式成绩统计口径测试。 */
class TeacherScoreMapperXmlTest {
private static final String NAMESPACE = "com.platform.business.mapper.TeacherScoreMapper.";
@Test
void mapperShouldParseAndEveryExamQueryShouldContainTeacherOwnership() throws Exception {
Configuration configuration = parse();
Map<String, Object> examParams = new HashMap<>();
examParams.put("teacherId", "teacher-1");
examParams.put("examId", 1);
examParams.put("query", new TeacherScoreExamQueryDTO());
String classSql = compact(boundSql(configuration, "queryClasses", examParams));
String listSql = compact(boundSql(configuration, "queryExams", examParams));
String detailSql = compact(boundSql(configuration, "findExam", examParams));
Map<String, Object> studentParams = new HashMap<>();
studentParams.put("teacherId", "teacher-1");
studentParams.put("examId", 1);
studentParams.put("query", new TeacherScoreStudentQueryDTO());
String studentSql = compact(boundSql(configuration, "queryStudents", studentParams));
String exportSql = compact(boundSql(configuration, "queryExportStudents", studentParams));
assertVisibleExamProtection(classSql);
assertVisibleExamProtection(listSql);
assertVisibleExamProtection(detailSql);
assertVisibleExamProtection(studentSql);
assertVisibleExamProtection(exportSql);
assertTrue(studentSql.contains("es.score < ifnull(e.pass_score, 60) then '不及格'"));
}
@Test
void summaryShouldSeparateExpectedSubmittedAndPublishedScoreStatistics() throws Exception {
Configuration configuration = parse();
Map<String, Object> params = new HashMap<>();
params.put("teacherId", "teacher-1");
params.put("query", new TeacherScoreExamQueryDTO());
String sql = compact(boundSql(configuration, "queryExams", params));
assertTrue(sql.contains("count(es.id) as expectedcount"));
assertTrue(sql.contains("es.submit"));
assertTrue(sql.contains("es.mark_flag"));
assertTrue(sql.contains("max(case"));
assertTrue(sql.contains("min(case"));
assertTrue(sql.contains("round(avg(case"));
assertTrue(sql.contains("es.score >= ifnull(e.pass_score, 60)"));
assertTrue(sql.contains("then null"));
}
private void assertVisibleExamProtection(String sql) {
assertTrue(sql.contains("e.chief_id = ?"));
assertTrue(sql.contains("ifnull(e.mark_flag, 0) = 1"));
assertTrue(sql.contains("date_add(e.exam_time"));
}
private String boundSql(Configuration configuration, String id, Object parameter) {
BoundSql boundSql = configuration.getMappedStatement(NAMESPACE + id)
.getBoundSql(parameter);
return boundSql.getSql();
}
private Configuration parse() throws Exception {
String resource = "com/platform/business/mapper/TeacherScoreMapper.xml";
Configuration configuration = new Configuration();
try (InputStream input = Resources.getResourceAsStream(resource)) {
XMLMapperBuilder builder = new XMLMapperBuilder(
input, configuration, resource, configuration.getSqlFragments());
builder.parse();
}
return configuration;
}
private String compact(String sql) {
return sql.replaceAll("\\s+", " ").trim().toLowerCase();
}
}
package com.platform.business.service.impl;
import com.platform.business.mapper.TeacherScoreMapper;
import com.platform.business.model.dto.TeacherScoreExamQueryDTO;
import com.platform.business.model.dto.TeacherScoreStudentQueryDTO;
import com.platform.business.model.vo.TeacherScoreExamVO;
import com.platform.business.model.vo.TeacherScoreStudentVO;
import com.platform.exception.BusinessException;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.web.MockHttpServletResponse;
import java.io.ByteArrayInputStream;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import static org.junit.jupiter.api.Assertions.assertEquals;
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.Mockito.verify;
import static org.mockito.Mockito.when;
/** 教师成绩服务的参数清洗、归属保护、空列表和全应考导出测试。 */
@ExtendWith(MockitoExtension.class)
class TeacherScoreServiceImplTest {
@Mock
private TeacherScoreMapper teacherScoreMapper;
@InjectMocks
private TeacherScoreServiceImpl service;
@Test
void examQueryShouldTrimKeywordAndAllowAllClasses() {
TeacherScoreExamQueryDTO query = new TeacherScoreExamQueryDTO();
query.setKeyword(" 月考 ");
when(teacherScoreMapper.queryExams("teacher-1", query))
.thenReturn(Collections.emptyList());
service.exams(query, " teacher-1 ");
assertEquals("月考", query.getKeyword());
assertNull(query.getClassId());
verify(teacherScoreMapper).queryExams("teacher-1", query);
}
@Test
void invalidClassAndTooLongKeywordShouldBeRejected() {
TeacherScoreExamQueryDTO invalidClass = new TeacherScoreExamQueryDTO();
invalidClass.setClassId(0);
assertThrows(BusinessException.class, () -> service.exams(invalidClass, "teacher-1"));
TeacherScoreStudentQueryDTO longKeyword = new TeacherScoreStudentQueryDTO();
longKeyword.setKeyword(repeat("学", 101));
assertThrows(BusinessException.class,
() -> service.students(1, longKeyword, "teacher-1"));
}
@Test
void detailShouldHideMissingUnpublishedFutureAndOtherTeacherExamWithSameMessage() {
when(teacherScoreMapper.findExam(7, "teacher-1")).thenReturn(null);
BusinessException error = assertThrows(BusinessException.class,
() -> service.exam(7, "teacher-1"));
assertEquals("考试不存在或无权访问", error.getMessage());
}
@Test
void invalidExamIdAndMissingTeacherIdentityShouldBeRejectedBeforeQuery() {
assertThrows(BusinessException.class, () -> service.exam(0, "teacher-1"));
assertThrows(BusinessException.class, () -> service.exam(1, " "));
}
@Test
void emptyStudentResultShouldStillVerifyExamOwnership() {
TeacherScoreStudentQueryDTO query = new TeacherScoreStudentQueryDTO();
when(teacherScoreMapper.queryStudents(9, "teacher-1", query))
.thenReturn(Collections.emptyList());
when(teacherScoreMapper.findExam(9, "teacher-1")).thenReturn(new TeacherScoreExamVO());
assertTrue(service.students(9, query, "teacher-1").isEmpty());
verify(teacherScoreMapper).findExam(9, "teacher-1");
}
@Test
void exportShouldContainPresentZeroScoreAndAbsentStudentWithBlankScore() throws Exception {
TeacherScoreExamVO exam = new TeacherScoreExamVO();
exam.setExamId(1);
exam.setExamName("污水一级月考");
when(teacherScoreMapper.findExam(1, "teacher-1")).thenReturn(exam);
TeacherScoreStudentVO present = student("张三", true, true, BigDecimal.ZERO, false);
TeacherScoreStudentVO absent = student("李四", false, false, null, null);
when(teacherScoreMapper.queryExportStudents(1, "teacher-1"))
.thenReturn(Arrays.asList(present, absent));
MockHttpServletResponse response = new MockHttpServletResponse();
service.exportExam(1, "teacher-1", response);
assertTrue(response.getHeader("Content-Disposition").contains("UTF-8''"));
try (XSSFWorkbook workbook = new XSSFWorkbook(
new ByteArrayInputStream(response.getContentAsByteArray()))) {
assertEquals("成绩明细", workbook.getSheetAt(0).getSheetName());
assertEquals("参考状态", workbook.getSheetAt(0).getRow(0)
.getCell(5).getStringCellValue());
assertEquals("实考", workbook.getSheetAt(0).getRow(1)
.getCell(5).getStringCellValue());
assertEquals(0D, workbook.getSheetAt(0).getRow(1)
.getCell(6).getNumericCellValue());
assertEquals("否", workbook.getSheetAt(0).getRow(1)
.getCell(8).getStringCellValue());
assertEquals("缺考", workbook.getSheetAt(0).getRow(2)
.getCell(5).getStringCellValue());
assertEquals(CellType.BLANK, workbook.getSheetAt(0).getRow(2)
.getCell(6).getCellType());
assertEquals("", workbook.getSheetAt(0).getRow(2)
.getCell(8).getStringCellValue());
}
}
private TeacherScoreStudentVO student(String name, boolean submitted, boolean published,
BigDecimal score, Boolean passed) {
TeacherScoreStudentVO student = new TeacherScoreStudentVO();
student.setExamName("污水一级月考");
student.setClassName("污水一级一班");
student.setStudentName(name);
student.setIdCard("310000000000000001");
student.setSubmitted(submitted);
student.setPublished(published);
student.setScore(score);
student.setGrade(score == null ? null : "不及格");
student.setPassed(passed);
return student;
}
private String repeat(String value, int count) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < count; i++) {
builder.append(value);
}
return builder.toString();
}
}
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