Commit e34240ea authored by wujipeng's avatar wujipeng
Browse files

管理员-教务管理-理论练习

parent 226897b4
package com.platform.business.model.dto; package com.platform.business.model.dto;
import com.platform.business.model.entity.TheoreticalPracticeEntity; import com.platform.business.model.entity.TheoreticalPracticeEntity;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import java.util.Date;
/** /**
* @author : wujipeng * @author : wujipeng
* @date : 2026/4/21 10:17 * @date : 2026/4/21 10:17
...@@ -17,4 +21,21 @@ public class TheoreticalPracticeDTO extends TheoreticalPracticeEntity { ...@@ -17,4 +21,21 @@ public class TheoreticalPracticeDTO extends TheoreticalPracticeEntity {
private Integer pageNum; private Integer pageNum;
private Integer pageSize; private Integer pageSize;
/**
* 管理端列表状态筛选。接口接受PENDING、ONGOING、ENDED,服务层会统一转成大写,
* 避免前端传入小写状态时出现查询不到数据的问题。
*/
@ApiModelProperty("状态筛选:PENDING/ONGOING/ENDED,忽略大小写")
private String status;
/** 练习开始时间的筛选下界,页面日期控件按yyyy-MM-dd提交。 */
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
@ApiModelProperty("筛选开始日期,包含当天")
private Date filterStartDate;
/** 练习结束时间的筛选上界,SQL会将该日期扩展到当天23:59:59.999。 */
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
@ApiModelProperty("筛选结束日期,包含当天")
private Date filterEndDate;
} }
package com.platform.business.model.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/** 管理端练习统计页的学员分页查询条件。 */
@Data
public class TheoreticalPracticeStatisticsQueryDTO {
@ApiModelProperty("页码,默认1")
private Integer pageNum;
@ApiModelProperty("每页条数,默认10,最大100")
private Integer pageSize;
@ApiModelProperty("学员姓名关键字,支持模糊查询")
private String keyword;
}
...@@ -3,6 +3,7 @@ package com.platform.business.model.dto; ...@@ -3,6 +3,7 @@ package com.platform.business.model.dto;
import com.platform.business.model.entity.TheoreticalPracticeStudentQuestionBankEntity; import com.platform.business.model.entity.TheoreticalPracticeStudentQuestionBankEntity;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import io.swagger.annotations.ApiModelProperty;
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
@Data @Data
...@@ -12,4 +13,15 @@ public class TheoreticalPracticeStudentQuestionBankDTO extends TheoreticalPracti ...@@ -12,4 +13,15 @@ public class TheoreticalPracticeStudentQuestionBankDTO extends TheoreticalPracti
private Integer pageSize; private Integer pageSize;
/**
* 客户端为一次提交生成的唯一请求号。服务端以“学员+请求号”建立唯一约束,
* 网络超时重试时不会重复累计答题次数和学习时长。
*/
@ApiModelProperty("本次答题提交的幂等请求号,最长64字符")
private String requestId;
/** 学员在当前题目上的实际停留秒数,允许0到3600秒。 */
@ApiModelProperty("本题耗时秒数,范围0-3600")
private Integer durationSeconds;
} }
package com.platform.business.model.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
/**
* 理论练习不可变作答记录。
*
* <p>原题库表只保存每题最后一次答案,重新作答会覆盖旧值,无法用于累计统计。本表每次
* 有效提交新增一行,并保存知识点和判题结果快照;重新作答不会删除历史记录。</p>
*/
@Data
@TableName("theoretical_practice_answer_record")
public class TheoreticalPracticeAnswerRecordEntity {
@TableId(type = IdType.ASSIGN_ID)
private String id;
@TableField("practice_id")
private String practiceId;
@TableField("student_id")
private String studentId;
@TableField("question_id")
private String questionId;
@TableField("knowledge_point")
private String knowledgePoint;
@TableField("actual_choice")
private String actualChoice;
@TableField("is_correct")
private Boolean correct;
@TableField("duration_seconds")
private Integer durationSeconds;
@TableField("request_id")
private String requestId;
@TableField("answered_at")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date answeredAt;
}
package com.platform.business.model.vo;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import java.math.BigDecimal;
/** 二级统计页和个人详情共同使用的知识点统计项。 */
@Data
public class TheoreticalPracticeKnowledgeStatisticsVO {
private String knowledgePoint;
private Long answerCount;
private Long averageStudyDurationSeconds;
private BigDecimal accuracyRate;
private BigDecimal masteryRate;
/** 以下聚合原值仅供服务层统一计算比例,避免SQL零分母和舍入规则分散。 */
@JsonIgnore
private Long correctCount;
@JsonIgnore
private Long totalDurationSeconds;
@JsonIgnore
private Long assignedStudentCount;
@JsonIgnore
private Long questionAssignmentCount;
@JsonIgnore
private Long uniqueAnsweredQuestionCount;
}
package com.platform.business.model.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
/** “查看数据统计”二级页面的总体指标和知识点卡片数据。 */
@Data
public class TheoreticalPracticeStatisticsOverviewVO {
private String practiceId;
private String level;
private String className;
private Long assignedStudentCount;
private BigDecimal averageAnswerCount;
private Long averageStudyDurationSeconds;
private BigDecimal averageAccuracyRate;
private Long activeStudentCount;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date statisticsStartTime;
private List<TheoreticalPracticeKnowledgeStatisticsVO> knowledgePoints;
/** Mapper返回的聚合原值不会直接序列化,由服务层计算页面指标。 */
@JsonIgnore
private Long answerCount;
@JsonIgnore
private Long correctCount;
@JsonIgnore
private Long totalDurationSeconds;
}
package com.platform.business.model.vo;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.List;
/** 个人详情弹框数据,继承学员总指标并增加知识点能力列表。 */
@Data
@EqualsAndHashCode(callSuper = true)
public class TheoreticalPracticeStudentStatisticsDetailVO extends TheoreticalPracticeStudentStatisticsVO {
private List<TheoreticalPracticeKnowledgeStatisticsVO> knowledgePoints;
}
package com.platform.business.model.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
/** 二级页面“学员练习情况”的单行统计。 */
@Data
public class TheoreticalPracticeStudentStatisticsVO {
private String practiceId;
private String studentId;
private String studentName;
private String className;
private Long answerCount;
private Long studyDurationSeconds;
private BigDecimal accuracyRate;
private BigDecimal masteryRate;
private String statusCode;
private String statusLabel;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date lastAnswerTime;
@JsonIgnore
private Long correctCount;
@JsonIgnore
private Long uniqueAnsweredQuestionCount;
@JsonIgnore
private Long questionCount;
}
package com.platform.business.model.vo;
import lombok.Data;
/** 一级理论练习列表顶部的全局统计。 */
@Data
public class TheoreticalPracticeSummaryVO {
private Long totalCount;
private Long ongoingCount;
private Long endedCount;
}
...@@ -26,5 +26,12 @@ public class TheoreticalPracticeVO extends TheoreticalPracticeEntity { ...@@ -26,5 +26,12 @@ public class TheoreticalPracticeVO extends TheoreticalPracticeEntity {
@ApiModelProperty(value = "状态") @ApiModelProperty(value = "状态")
private String status; private String status;
/**
* 供前端筛选和样式判断使用的稳定状态码。保留status中文文案以兼容旧页面,
* 新页面应优先使用PENDING、ONGOING、ENDED三个状态码。
*/
@ApiModelProperty(value = "状态码:PENDING/ONGOING/ENDED")
private String statusCode;
} }
package com.platform.business.constant;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/** 理论练习状态、统计阈值和输入上限的统一定义。 */
public final class TheoreticalPracticeConstants {
public static final String STATUS_PENDING = "PENDING";
public static final String STATUS_ONGOING = "ONGOING";
public static final String STATUS_ENDED = "ENDED";
public static final String STUDENT_NOT_STARTED = "NOT_STARTED";
public static final String STUDENT_EXCELLENT = "EXCELLENT";
public static final String STUDENT_GOOD = "GOOD";
public static final String STUDENT_NEEDS_IMPROVEMENT = "NEEDS_IMPROVEMENT";
public static final int EXCELLENT_RATE = 80;
public static final int GOOD_RATE = 60;
public static final int MAX_ANSWER_DURATION_SECONDS = 3600;
public static final int MAX_REQUEST_ID_LENGTH = 64;
public static final int DEFAULT_PAGE_SIZE = 10;
public static final int MAX_PAGE_SIZE = 100;
/** 项目页面和数据库日期均按中国标准时间解释,避免部署主机时区改变状态边界。 */
public static final ZoneId BUSINESS_ZONE = ZoneId.of("Asia/Shanghai");
public static final Set<String> ALLOWED_STATUSES = new HashSet<>(Arrays.asList(
STATUS_PENDING, STATUS_ONGOING, STATUS_ENDED));
private TheoreticalPracticeConstants() {
}
}
package com.platform.business.controller; package com.platform.business.controller;
import com.platform.business.model.dto.TheoreticalPracticeDTO; import com.platform.business.model.dto.TheoreticalPracticeDTO;
import com.platform.business.model.dto.TheoreticalPracticeStatisticsQueryDTO;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.TheoreticalPracticeStatisticsOverviewVO;
import com.platform.business.model.vo.TheoreticalPracticeStudentStatisticsDetailVO;
import com.platform.business.model.vo.TheoreticalPracticeSummaryVO;
import com.platform.business.model.vo.TheoreticalPracticeVO; import com.platform.business.model.vo.TheoreticalPracticeVO;
import com.platform.business.service.AuthenticatedUserService;
import com.platform.business.service.TheoreticalPracticeService; import com.platform.business.service.TheoreticalPracticeService;
import com.platform.business.constant.TheoreticalPracticeConstants;
import com.platform.controller.BaseController; import com.platform.controller.BaseController;
import com.platform.model.resp.Result; import com.platform.model.resp.Result;
import com.platform.page.TableDataInfo; import com.platform.page.TableDataInfo;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/** /**
...@@ -19,30 +30,114 @@ import javax.annotation.Resource; ...@@ -19,30 +30,114 @@ import javax.annotation.Resource;
*/ */
@RestController @RestController
@RequestMapping("/theoretical/practice") @RequestMapping("/theoretical/practice")
@Api(tags = "管理员端-理论练习")
public class TheoreticalPracticeController extends BaseController { public class TheoreticalPracticeController extends BaseController {
@Resource @Resource
private TheoreticalPracticeService theoreticalPracticeService; private TheoreticalPracticeService theoreticalPracticeService;
@Resource
private AuthenticatedUserService authenticatedUserService;
@ApiOperation("理论练习分页,支持等级、状态和日期范围筛选")
@PostMapping("/page") @PostMapping("/page")
public TableDataInfo page(@RequestBody TheoreticalPracticeDTO theoreticalPracticeDTO) { public TableDataInfo page(@RequestBody TheoreticalPracticeDTO theoreticalPracticeDTO,
startPage(theoreticalPracticeDTO.getPageNum(), theoreticalPracticeDTO.getPageSize()); HttpServletRequest request) {
requireAdmin(request);
int pageNum = theoreticalPracticeDTO.getPageNum() == null
|| theoreticalPracticeDTO.getPageNum() < 1 ? 1 : theoreticalPracticeDTO.getPageNum();
int pageSize = theoreticalPracticeDTO.getPageSize() == null
|| theoreticalPracticeDTO.getPageSize() < 1
? TheoreticalPracticeConstants.DEFAULT_PAGE_SIZE
: Math.min(theoreticalPracticeDTO.getPageSize(),
TheoreticalPracticeConstants.MAX_PAGE_SIZE);
startPage(pageNum, pageSize);
return getDataTable(theoreticalPracticeService.page(theoreticalPracticeDTO)); return getDataTable(theoreticalPracticeService.page(theoreticalPracticeDTO));
} }
@ApiOperation("一级页面练习总数、进行中和已结束统计")
@GetMapping("/summary")
public Result<TheoreticalPracticeSummaryVO> summary(HttpServletRequest request) {
requireAdmin(request);
return Result.data(theoreticalPracticeService.summary());
}
@ApiOperation("查看数据统计-总体情况和知识点统计")
@GetMapping("/{practiceId}/statistics/overview")
public Result<TheoreticalPracticeStatisticsOverviewVO> statisticsOverview(
@PathVariable("practiceId") String practiceId,
HttpServletRequest request) {
requireAdmin(request);
return Result.data(theoreticalPracticeService.statisticsOverview(practiceId));
}
@ApiOperation("查看数据统计-学员练习情况分页")
@PostMapping("/{practiceId}/statistics/students/page")
public TableDataInfo studentStatistics(
@PathVariable("practiceId") String practiceId,
@RequestBody(required = false) TheoreticalPracticeStatisticsQueryDTO query,
HttpServletRequest request) {
requireAdmin(request);
TheoreticalPracticeStatisticsQueryDTO safe = query == null
? new TheoreticalPracticeStatisticsQueryDTO() : query;
int pageNum = safe.getPageNum() == null || safe.getPageNum() < 1 ? 1 : safe.getPageNum();
int pageSize = safe.getPageSize() == null || safe.getPageSize() < 1
? TheoreticalPracticeConstants.DEFAULT_PAGE_SIZE
: Math.min(safe.getPageSize(), TheoreticalPracticeConstants.MAX_PAGE_SIZE);
startPage(pageNum, pageSize);
return getDataTable(theoreticalPracticeService.studentStatistics(practiceId, safe));
}
@ApiOperation("查看数据统计-个人详情")
@GetMapping("/{practiceId}/statistics/students/{studentId}")
public Result<TheoreticalPracticeStudentStatisticsDetailVO> studentStatisticsDetail(
@PathVariable("practiceId") String practiceId,
@PathVariable("studentId") String studentId,
HttpServletRequest request) {
requireAdmin(request);
return Result.data(theoreticalPracticeService.studentStatisticsDetail(practiceId, studentId));
}
@ApiOperation("查看数据统计-导出个人Word报告")
@GetMapping("/{practiceId}/statistics/students/{studentId}/export")
public void exportStudentStatistics(
@PathVariable("practiceId") String practiceId,
@PathVariable("studentId") String studentId,
HttpServletRequest request,
HttpServletResponse response) {
requireAdmin(request);
theoreticalPracticeService.exportStudentStatistics(practiceId, studentId, response);
}
@ApiOperation("理论练习详情")
@GetMapping("/{id}") @GetMapping("/{id}")
public Result<TheoreticalPracticeVO> detail(@PathVariable String id) { public Result<TheoreticalPracticeVO> detail(@PathVariable String id,
HttpServletRequest request) {
requireAdmin(request);
return Result.data(theoreticalPracticeService.detail(id)); return Result.data(theoreticalPracticeService.detail(id));
} }
@ApiOperation("新增或编辑理论练习")
@PostMapping("/saveOrUpdate") @PostMapping("/saveOrUpdate")
public Result<Boolean> saveOrUpdateData(@RequestBody TheoreticalPracticeDTO theoreticalPracticeDTO) { public Result<Boolean> saveOrUpdateData(@RequestBody TheoreticalPracticeDTO theoreticalPracticeDTO,
HttpServletRequest request) {
requireAdmin(request);
return theoreticalPracticeService.saveOrUpdateData(theoreticalPracticeDTO); return theoreticalPracticeService.saveOrUpdateData(theoreticalPracticeDTO);
} }
@ApiOperation("手动关闭理论练习")
@PostMapping("/close") @PostMapping("/close")
public Result<Boolean> close(@RequestBody TheoreticalPracticeDTO theoreticalPracticeDTO) { public Result<Boolean> close(@RequestBody TheoreticalPracticeDTO theoreticalPracticeDTO,
HttpServletRequest request) {
requireAdmin(request);
return Result.data(theoreticalPracticeService.close(theoreticalPracticeDTO)); return Result.data(theoreticalPracticeService.close(theoreticalPracticeDTO));
} }
/** 管理端所有入口统一校验角色,避免统计与导出接口暴露全体学员数据。 */
private UserEntity requireAdmin(HttpServletRequest request) {
UserEntity user = authenticatedUserService.current(request);
authenticatedUserService.requireAdmin(user);
return user;
}
} }
...@@ -3,6 +3,8 @@ package com.platform.business.controller; ...@@ -3,6 +3,8 @@ package com.platform.business.controller;
import com.platform.business.model.dto.TheoreticalPracticeStudentQuestionBankDTO; import com.platform.business.model.dto.TheoreticalPracticeStudentQuestionBankDTO;
import com.platform.business.model.vo.TheoreticalPracticeStudentQuestionBankVO; import com.platform.business.model.vo.TheoreticalPracticeStudentQuestionBankVO;
import com.platform.business.service.TheoreticalPracticeStudentQuestionBankService; import com.platform.business.service.TheoreticalPracticeStudentQuestionBankService;
import com.platform.business.service.AuthenticatedUserService;
import com.platform.business.model.entity.UserEntity;
import com.platform.controller.BaseController; import com.platform.controller.BaseController;
import com.platform.model.resp.Result; import com.platform.model.resp.Result;
import com.platform.page.TableDataInfo; import com.platform.page.TableDataInfo;
...@@ -10,6 +12,7 @@ import io.swagger.annotations.ApiOperation; ...@@ -10,6 +12,7 @@ import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List; import java.util.List;
@RestController @RestController
...@@ -19,6 +22,9 @@ public class TheoreticalPracticeStudentQuestionBankController extends BaseContro ...@@ -19,6 +22,9 @@ public class TheoreticalPracticeStudentQuestionBankController extends BaseContro
@Resource @Resource
private TheoreticalPracticeStudentQuestionBankService theoreticalPracticeStudentQuestionBankService; private TheoreticalPracticeStudentQuestionBankService theoreticalPracticeStudentQuestionBankService;
@Resource
private AuthenticatedUserService authenticatedUserService;
@ApiOperation(value = "一级分页") @ApiOperation(value = "一级分页")
@PostMapping("/one/page") @PostMapping("/one/page")
...@@ -34,8 +40,13 @@ public class TheoreticalPracticeStudentQuestionBankController extends BaseContro ...@@ -34,8 +40,13 @@ public class TheoreticalPracticeStudentQuestionBankController extends BaseContro
@ApiOperation(value = "编辑") @ApiOperation(value = "编辑")
@PostMapping("/update") @PostMapping("/update")
public Result<Boolean> edit(@RequestBody TheoreticalPracticeStudentQuestionBankDTO theoreticalPracticeStudentQuestionBankDTO) { public Result<Boolean> edit(
return Result.data(theoreticalPracticeStudentQuestionBankService.edit(theoreticalPracticeStudentQuestionBankDTO)); @RequestBody TheoreticalPracticeStudentQuestionBankDTO theoreticalPracticeStudentQuestionBankDTO,
HttpServletRequest request) {
// 学员ID只从JWT解析,不能接受请求体中的studentId,否则可伪造他人作答数据。
UserEntity currentStudent = authenticatedUserService.current(request);
return Result.data(theoreticalPracticeStudentQuestionBankService.edit(
theoreticalPracticeStudentQuestionBankDTO, currentStudent.getId()));
} }
@ApiOperation(value = "题库总览") @ApiOperation(value = "题库总览")
......
package com.platform.business.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.platform.business.model.entity.TheoreticalPracticeAnswerRecordEntity;
import org.apache.ibatis.annotations.Mapper;
/** 理论练习作答历史持久层。 */
@Mapper
public interface TheoreticalPracticeAnswerRecordMapper
extends BaseMapper<TheoreticalPracticeAnswerRecordEntity> {
/**
* 幂等写入一条不可变作答记录。
*
* @return 1表示首次写入,0表示学员的同一requestId已经处理过
*/
int insertIdempotently(TheoreticalPracticeAnswerRecordEntity record);
/** 读取同一数据库连接上上一条INSERT的服务端影响行数,避免JDBC found-rows配置差异。 */
int previousAffectedRows();
}
...@@ -4,11 +4,16 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper; ...@@ -4,11 +4,16 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.platform.business.model.dto.TheoreticalPracticeDTO; import com.platform.business.model.dto.TheoreticalPracticeDTO;
import com.platform.business.model.entity.TheoreticalPracticeEntity; import com.platform.business.model.entity.TheoreticalPracticeEntity;
import com.platform.business.model.vo.TheoreticalPracticeVO; import com.platform.business.model.vo.TheoreticalPracticeVO;
import com.platform.business.model.vo.TheoreticalPracticeKnowledgeStatisticsVO;
import com.platform.business.model.vo.TheoreticalPracticeStatisticsOverviewVO;
import com.platform.business.model.vo.TheoreticalPracticeStudentStatisticsVO;
import com.platform.business.model.vo.TheoreticalPracticeSummaryVO;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
import java.util.List; import java.util.List;
import java.util.Date;
/** /**
* @author : wujipeng * @author : wujipeng
...@@ -18,8 +23,27 @@ import java.util.List; ...@@ -18,8 +23,27 @@ import java.util.List;
*/ */
@Mapper @Mapper
public interface TheoreticalPracticeMapper extends BaseMapper<TheoreticalPracticeEntity> { public interface TheoreticalPracticeMapper extends BaseMapper<TheoreticalPracticeEntity> {
List<TheoreticalPracticeVO> page(TheoreticalPracticeDTO theoreticalPracticeDTO); List<TheoreticalPracticeVO> page(@Param("query") TheoreticalPracticeDTO theoreticalPracticeDTO,
@Param("now") Date now);
TheoreticalPracticeVO detail(@Param("id") String id); TheoreticalPracticeVO detail(@Param("id") String id);
TheoreticalPracticeSummaryVO summary(@Param("now") Date now);
TheoreticalPracticeStatisticsOverviewVO statisticsOverview(@Param("practiceId") String practiceId);
List<TheoreticalPracticeKnowledgeStatisticsVO> knowledgeStatistics(
@Param("practiceId") String practiceId,
@Param("studentId") String studentId);
List<TheoreticalPracticeStudentStatisticsVO> studentStatistics(
@Param("practiceId") String practiceId,
@Param("keyword") String keyword,
@Param("studentId") String studentId);
/** 根据登录学员、题目和当前时间定位唯一开放的理论练习。 */
List<String> activePracticeIdsForAnswer(@Param("studentId") String studentId,
@Param("questionId") String questionId,
@Param("now") Date now);
} }
...@@ -4,8 +4,15 @@ import com.baomidou.mybatisplus.extension.service.IService; ...@@ -4,8 +4,15 @@ import com.baomidou.mybatisplus.extension.service.IService;
import com.platform.business.model.dto.TheoreticalPracticeDTO; import com.platform.business.model.dto.TheoreticalPracticeDTO;
import com.platform.business.model.entity.TheoreticalPracticeEntity; import com.platform.business.model.entity.TheoreticalPracticeEntity;
import com.platform.business.model.vo.TheoreticalPracticeVO; import com.platform.business.model.vo.TheoreticalPracticeVO;
import com.platform.business.model.vo.TheoreticalPracticeStatisticsOverviewVO;
import com.platform.business.model.vo.TheoreticalPracticeStudentStatisticsDetailVO;
import com.platform.business.model.vo.TheoreticalPracticeStudentStatisticsVO;
import com.platform.business.model.vo.TheoreticalPracticeSummaryVO;
import com.platform.business.model.dto.TheoreticalPracticeStatisticsQueryDTO;
import com.platform.model.resp.Result; import com.platform.model.resp.Result;
import javax.servlet.http.HttpServletResponse;
import java.util.List; import java.util.List;
/** /**
...@@ -23,4 +30,16 @@ public interface TheoreticalPracticeService extends IService<TheoreticalPractice ...@@ -23,4 +30,16 @@ public interface TheoreticalPracticeService extends IService<TheoreticalPractice
Boolean close(TheoreticalPracticeDTO theoreticalPracticeDTO); Boolean close(TheoreticalPracticeDTO theoreticalPracticeDTO);
TheoreticalPracticeSummaryVO summary();
TheoreticalPracticeStatisticsOverviewVO statisticsOverview(String practiceId);
List<TheoreticalPracticeStudentStatisticsVO> studentStatistics(
String practiceId, TheoreticalPracticeStatisticsQueryDTO query);
TheoreticalPracticeStudentStatisticsDetailVO studentStatisticsDetail(
String practiceId, String studentId);
void exportStudentStatistics(String practiceId, String studentId, HttpServletResponse response);
} }
...@@ -22,6 +22,10 @@ public interface TheoreticalPracticeStudentQuestionBankService extends IService< ...@@ -22,6 +22,10 @@ public interface TheoreticalPracticeStudentQuestionBankService extends IService<
Boolean reAnswer(TheoreticalPracticeStudentQuestionBankDTO theoreticalPracticeStudentQuestionBankDTO); Boolean reAnswer(TheoreticalPracticeStudentQuestionBankDTO theoreticalPracticeStudentQuestionBankDTO);
Boolean edit(TheoreticalPracticeStudentQuestionBankDTO theoreticalPracticeStudentQuestionBankDTO); /**
* 提交当前登录学员的一次答案,并在同一事务中更新题库当前状态和写入统计历史。
*/
Boolean edit(TheoreticalPracticeStudentQuestionBankDTO theoreticalPracticeStudentQuestionBankDTO,
String currentStudentId);
} }
...@@ -4,25 +4,48 @@ import cn.hutool.core.bean.BeanUtil; ...@@ -4,25 +4,48 @@ import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.business.constant.TheoreticalPracticeConstants;
import com.platform.business.mapper.TheoreticalPracticeMapper; import com.platform.business.mapper.TheoreticalPracticeMapper;
import com.platform.business.model.dto.TheoreticalPracticeDTO; import com.platform.business.model.dto.TheoreticalPracticeDTO;
import com.platform.business.model.dto.TheoreticalPracticeStatisticsQueryDTO;
import com.platform.business.model.entity.*; import com.platform.business.model.entity.*;
import com.platform.business.model.vo.TheoreticalPracticeKnowledgeStatisticsVO;
import com.platform.business.model.vo.TheoreticalPracticeStatisticsOverviewVO;
import com.platform.business.model.vo.TheoreticalPracticeStudentStatisticsDetailVO;
import com.platform.business.model.vo.TheoreticalPracticeStudentStatisticsVO;
import com.platform.business.model.vo.TheoreticalPracticeStudentVO; import com.platform.business.model.vo.TheoreticalPracticeStudentVO;
import com.platform.business.model.vo.TheoreticalPracticeSummaryVO;
import com.platform.business.model.vo.TheoreticalPracticeVO; import com.platform.business.model.vo.TheoreticalPracticeVO;
import com.platform.business.service.*; import com.platform.business.service.*;
import com.platform.business.utils.ChineseNumberUtils;
import com.platform.business.utils.JwtTokenUtil; import com.platform.business.utils.JwtTokenUtil;
import com.platform.exception.BusinessException; import com.platform.exception.BusinessException;
import com.platform.model.resp.Result; import com.platform.model.resp.Result;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
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.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
...@@ -50,19 +73,25 @@ public class TheoreticalPracticeServiceImpl extends ServiceImpl<TheoreticalPract ...@@ -50,19 +73,25 @@ public class TheoreticalPracticeServiceImpl extends ServiceImpl<TheoreticalPract
@Override @Override
public List<TheoreticalPracticeVO> page(TheoreticalPracticeDTO theoreticalPracticeDTO) { public List<TheoreticalPracticeVO> page(TheoreticalPracticeDTO theoreticalPracticeDTO) {
List<TheoreticalPracticeVO> result = baseMapper.page(theoreticalPracticeDTO); TheoreticalPracticeDTO safeQuery = normalizePageQuery(theoreticalPracticeDTO);
//判断状态 Date now = new Date();
List<TheoreticalPracticeVO> result = baseMapper.page(safeQuery, now);
// 中文状态继续兼容旧页面,同时补充稳定状态码供新筛选项和样式判断使用。
for (TheoreticalPracticeVO theoreticalPracticeVO : result) { for (TheoreticalPracticeVO theoreticalPracticeVO : result) {
if (theoreticalPracticeVO.getIsClose()) { if (Boolean.TRUE.equals(theoreticalPracticeVO.getIsClose())) {
theoreticalPracticeVO.setStatus("已手动关闭"); theoreticalPracticeVO.setStatus("已手动关闭");
theoreticalPracticeVO.setStatusCode(TheoreticalPracticeConstants.STATUS_ENDED);
continue; continue;
} }
if (theoreticalPracticeVO.getStartTime().getTime() > System.currentTimeMillis()) { if (theoreticalPracticeVO.getStartTime().after(now)) {
theoreticalPracticeVO.setStatus("未开放"); theoreticalPracticeVO.setStatus("未开放");
} else if (theoreticalPracticeVO.getEndTime().getTime() < System.currentTimeMillis()) { theoreticalPracticeVO.setStatusCode(TheoreticalPracticeConstants.STATUS_PENDING);
} else if (theoreticalPracticeVO.getEndTime().before(now)) {
theoreticalPracticeVO.setStatus("已结束"); theoreticalPracticeVO.setStatus("已结束");
theoreticalPracticeVO.setStatusCode(TheoreticalPracticeConstants.STATUS_ENDED);
} else { } else {
theoreticalPracticeVO.setStatus("已开放"); theoreticalPracticeVO.setStatus("已开放");
theoreticalPracticeVO.setStatusCode(TheoreticalPracticeConstants.STATUS_ONGOING);
} }
} }
return result; return result;
...@@ -172,4 +201,285 @@ public class TheoreticalPracticeServiceImpl extends ServiceImpl<TheoreticalPract ...@@ -172,4 +201,285 @@ public class TheoreticalPracticeServiceImpl extends ServiceImpl<TheoreticalPract
theoreticalPracticeDTO.setIsClose(true); theoreticalPracticeDTO.setIsClose(true);
return updateById(theoreticalPracticeDTO); return updateById(theoreticalPracticeDTO);
} }
@Override
@Transactional(readOnly = true)
public TheoreticalPracticeSummaryVO summary() {
TheoreticalPracticeSummaryVO summary = baseMapper.summary(new Date());
if (summary == null) {
summary = new TheoreticalPracticeSummaryVO();
summary.setTotalCount(0L);
summary.setOngoingCount(0L);
summary.setEndedCount(0L);
}
return summary;
}
@Override
@Transactional(readOnly = true)
public TheoreticalPracticeStatisticsOverviewVO statisticsOverview(String practiceId) {
requireText(practiceId, "练习ID不能为空");
TheoreticalPracticeStatisticsOverviewVO overview = baseMapper.statisticsOverview(practiceId);
if (overview == null) {
throw new BusinessException("理论练习不存在");
}
long studentCount = value(overview.getAssignedStudentCount());
long answerCount = value(overview.getAnswerCount());
overview.setAverageAnswerCount(average(answerCount, studentCount));
overview.setAverageStudyDurationSeconds(averageSeconds(
value(overview.getTotalDurationSeconds()), studentCount));
overview.setAverageAccuracyRate(rate(value(overview.getCorrectCount()), answerCount));
List<TheoreticalPracticeKnowledgeStatisticsVO> knowledgePoints =
baseMapper.knowledgeStatistics(practiceId, null);
applyKnowledgeRates(knowledgePoints, studentCount);
overview.setKnowledgePoints(knowledgePoints == null ? Collections.emptyList() : knowledgePoints);
return overview;
}
@Override
@Transactional(readOnly = true)
public List<TheoreticalPracticeStudentStatisticsVO> studentStatistics(
String practiceId, TheoreticalPracticeStatisticsQueryDTO query) {
requirePractice(practiceId);
String keyword = normalizeKeyword(query == null ? null : query.getKeyword());
List<TheoreticalPracticeStudentStatisticsVO> rows =
baseMapper.studentStatistics(practiceId, keyword, null);
if (rows == null) {
return Collections.emptyList();
}
rows.forEach(this::applyStudentRatesAndStatus);
return rows;
}
@Override
@Transactional(readOnly = true)
public TheoreticalPracticeStudentStatisticsDetailVO studentStatisticsDetail(
String practiceId, String studentId) {
requirePractice(practiceId);
requireText(studentId, "学员ID不能为空");
List<TheoreticalPracticeStudentStatisticsVO> rows =
baseMapper.studentStatistics(practiceId, null, studentId);
if (rows == null || rows.isEmpty()) {
throw new BusinessException("学员不在本期理论练习名单中");
}
TheoreticalPracticeStudentStatisticsVO row = rows.get(0);
applyStudentRatesAndStatus(row);
TheoreticalPracticeStudentStatisticsDetailVO detail =
BeanUtil.copyProperties(row, TheoreticalPracticeStudentStatisticsDetailVO.class);
List<TheoreticalPracticeKnowledgeStatisticsVO> knowledgePoints =
baseMapper.knowledgeStatistics(practiceId, studentId);
applyKnowledgeRates(knowledgePoints, 1L);
detail.setKnowledgePoints(knowledgePoints == null ? Collections.emptyList() : knowledgePoints);
return detail;
}
@Override
@Transactional(readOnly = true)
public void exportStudentStatistics(String practiceId, String studentId,
HttpServletResponse response) {
TheoreticalPracticeStudentStatisticsDetailVO detail =
studentStatisticsDetail(practiceId, studentId);
String safeName = detail.getStudentName() == null ? "学员" : detail.getStudentName();
String filename = safeName + "-理论练习个人报告.docx";
try (XWPFDocument document = buildStudentReport(detail);
OutputStream output = response.getOutputStream()) {
String encoded = URLEncoder.encode(filename, "UTF-8").replace("+", "%20");
response.setCharacterEncoding("UTF-8");
response.setContentType(
"application/vnd.openxmlformats-officedocument.wordprocessingml.document");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename*=UTF-8''" + encoded);
document.write(output);
output.flush();
} catch (IOException e) {
throw new BusinessException("导出理论练习个人报告失败");
}
}
/** 校验列表筛选并统一状态大小写,防止无效状态被静默当成“全部”。 */
private TheoreticalPracticeDTO normalizePageQuery(TheoreticalPracticeDTO query) {
TheoreticalPracticeDTO safe = query == null ? new TheoreticalPracticeDTO() : query;
if (StrUtil.isNotBlank(safe.getStatus())) {
String status = safe.getStatus().trim().toUpperCase(Locale.ROOT);
if (!TheoreticalPracticeConstants.ALLOWED_STATUSES.contains(status)) {
throw new BusinessException("练习状态只能是PENDING、ONGOING或ENDED");
}
safe.setStatus(status);
} else {
safe.setStatus(null);
}
if (safe.getFilterStartDate() != null && safe.getFilterEndDate() != null
&& safe.getFilterStartDate().after(safe.getFilterEndDate())) {
throw new BusinessException("筛选开始日期不能晚于结束日期");
}
return safe;
}
private void requirePractice(String practiceId) {
requireText(practiceId, "练习ID不能为空");
if (getById(practiceId) == null) {
throw new BusinessException("理论练习不存在");
}
}
private String normalizeKeyword(String keyword) {
if (StrUtil.isBlank(keyword)) {
return null;
}
String normalized = keyword.trim();
if (normalized.length() > 50) {
throw new BusinessException("学员姓名关键字不能超过50个字符");
}
return normalized;
}
/** 所有比例均采用HALF_UP保留两位小数,零分母统一返回0.00。 */
private BigDecimal rate(long numerator, long denominator) {
if (denominator <= 0) {
return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
}
return BigDecimal.valueOf(numerator)
.multiply(BigDecimal.valueOf(100))
.divide(BigDecimal.valueOf(denominator), 2, RoundingMode.HALF_UP);
}
private BigDecimal average(long total, long denominator) {
if (denominator <= 0) {
return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
}
return BigDecimal.valueOf(total)
.divide(BigDecimal.valueOf(denominator), 2, RoundingMode.HALF_UP);
}
private long averageSeconds(long totalSeconds, long denominator) {
if (denominator <= 0) {
return 0L;
}
return BigDecimal.valueOf(totalSeconds)
.divide(BigDecimal.valueOf(denominator), 0, RoundingMode.HALF_UP)
.longValue();
}
private void applyKnowledgeRates(List<TheoreticalPracticeKnowledgeStatisticsVO> items,
long assignedStudentCount) {
if (items == null) {
return;
}
for (TheoreticalPracticeKnowledgeStatisticsVO item : items) {
long answers = value(item.getAnswerCount());
item.setAnswerCount(answers);
item.setAverageStudyDurationSeconds(averageSeconds(
value(item.getTotalDurationSeconds()), assignedStudentCount));
item.setAccuracyRate(rate(value(item.getCorrectCount()), answers));
item.setMasteryRate(rate(value(item.getUniqueAnsweredQuestionCount()),
value(item.getQuestionAssignmentCount())));
}
}
private void applyStudentRatesAndStatus(TheoreticalPracticeStudentStatisticsVO row) {
long answers = value(row.getAnswerCount());
row.setAnswerCount(answers);
row.setStudyDurationSeconds(value(row.getStudyDurationSeconds()));
row.setAccuracyRate(rate(value(row.getCorrectCount()), answers));
row.setMasteryRate(rate(value(row.getUniqueAnsweredQuestionCount()),
value(row.getQuestionCount())));
if (answers == 0) {
row.setStatusCode(TheoreticalPracticeConstants.STUDENT_NOT_STARTED);
row.setStatusLabel("未开始");
} else if (row.getAccuracyRate().compareTo(
BigDecimal.valueOf(TheoreticalPracticeConstants.EXCELLENT_RATE)) >= 0) {
row.setStatusCode(TheoreticalPracticeConstants.STUDENT_EXCELLENT);
row.setStatusLabel("优秀");
} else if (row.getAccuracyRate().compareTo(
BigDecimal.valueOf(TheoreticalPracticeConstants.GOOD_RATE)) >= 0) {
row.setStatusCode(TheoreticalPracticeConstants.STUDENT_GOOD);
row.setStatusLabel("良好");
} else {
row.setStatusCode(TheoreticalPracticeConstants.STUDENT_NEEDS_IMPROVEMENT);
row.setStatusLabel("待加强");
}
}
/** 构建便于归档阅读的Word报告;雷达图由页面根据同一知识点数据动态绘制。 */
private XWPFDocument buildStudentReport(TheoreticalPracticeStudentStatisticsDetailVO detail) {
XWPFDocument document = new XWPFDocument();
XWPFParagraph title = document.createParagraph();
title.setAlignment(ParagraphAlignment.CENTER);
XWPFRun titleRun = title.createRun();
titleRun.setBold(true);
titleRun.setFontSize(18);
titleRun.setText("理论练习个人报告");
XWPFParagraph meta = document.createParagraph();
meta.setAlignment(ParagraphAlignment.CENTER);
meta.createRun().setText("学员:" + text(detail.getStudentName())
+ " 班级:" + text(detail.getClassName()));
XWPFTable summaryTable = document.createTable(4, 2);
setCells(summaryTable.getRow(0), "累计答题数", String.valueOf(value(detail.getAnswerCount())));
setCells(summaryTable.getRow(1), "累计学习时长", formatDuration(value(detail.getStudyDurationSeconds())));
setCells(summaryTable.getRow(2), "综合正确率", detail.getAccuracyRate() + "%");
setCells(summaryTable.getRow(3), "综合掌握度", detail.getMasteryRate() + "%");
XWPFParagraph section = document.createParagraph();
XWPFRun sectionRun = section.createRun();
sectionRun.setBold(true);
sectionRun.setFontSize(13);
sectionRun.setText("知识点能力明细");
List<TheoreticalPracticeKnowledgeStatisticsVO> points = detail.getKnowledgePoints();
XWPFTable table = document.createTable((points == null ? 0 : points.size()) + 1, 6);
setCells(table.getRow(0), "序号", "知识点", "答题数", "人均/个人时长", "正确率", "掌握度");
if (points != null) {
for (int i = 0; i < points.size(); i++) {
TheoreticalPracticeKnowledgeStatisticsVO point = points.get(i);
setCells(table.getRow(i + 1), String.valueOf(i + 1), text(point.getKnowledgePoint()),
String.valueOf(value(point.getAnswerCount())),
formatDuration(value(point.getAverageStudyDurationSeconds())),
point.getAccuracyRate() + "%", point.getMasteryRate() + "%");
}
}
XWPFParagraph footer = document.createParagraph();
footer.createRun().setText("数据更新于:" + (detail.getLastAnswerTime() == null
? "暂无作答记录"
: new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(detail.getLastAnswerTime())));
return document;
}
private void setCells(XWPFTableRow row, String... values) {
for (int i = 0; i < values.length; i++) {
XWPFTableCell cell = row.getCell(i);
cell.setText(values[i] == null ? "" : values[i]);
if (!cell.getParagraphs().isEmpty()) {
cell.getParagraphs().get(0).setAlignment(ParagraphAlignment.CENTER);
}
}
}
private String formatDuration(long seconds) {
long hours = seconds / 3600;
long minutes = (seconds % 3600) / 60;
long remainSeconds = seconds % 60;
return hours + "小时" + minutes + "分" + remainSeconds + "秒";
}
private String requireText(String value, String message) {
if (StrUtil.isBlank(value)) {
throw new BusinessException(message);
}
return value.trim();
}
private long value(Long value) {
return value == null ? 0L : value;
}
private String text(String value) {
return value == null ? "" : value;
}
} }
...@@ -2,10 +2,15 @@ package com.platform.business.service.impl; ...@@ -2,10 +2,15 @@ package com.platform.business.service.impl;
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageHelper;
import com.platform.business.constant.TheoreticalPracticeConstants;
import com.platform.business.mapper.TheoreticalPracticeAnswerRecordMapper;
import com.platform.business.mapper.TheoreticalPracticeMapper;
import com.platform.business.mapper.TheoreticalPracticeStudentQuestionBankMapper; import com.platform.business.mapper.TheoreticalPracticeStudentQuestionBankMapper;
import com.platform.business.model.dto.TheoreticalPracticeStudentQuestionBankDTO; import com.platform.business.model.dto.TheoreticalPracticeStudentQuestionBankDTO;
import com.platform.business.model.entity.TheoreticalPracticeAnswerRecordEntity;
import com.platform.business.model.entity.TheoreticalPracticeStudentQuestionBankEntity; import com.platform.business.model.entity.TheoreticalPracticeStudentQuestionBankEntity;
import com.platform.business.model.entity.UserEntity; import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.TheoreticalPracticeStudentQuestionBankVO; import com.platform.business.model.vo.TheoreticalPracticeStudentQuestionBankVO;
...@@ -13,8 +18,10 @@ import com.platform.business.service.TheoreticalPracticeStudentQuestionBankServi ...@@ -13,8 +18,10 @@ import com.platform.business.service.TheoreticalPracticeStudentQuestionBankServi
import com.platform.business.service.UserService; import com.platform.business.service.UserService;
import com.platform.business.utils.ChineseNumberUtils; import com.platform.business.utils.ChineseNumberUtils;
import com.platform.business.utils.JwtTokenUtil; import com.platform.business.utils.JwtTokenUtil;
import com.platform.exception.BusinessException;
import com.platform.utils.StringUtils; import com.platform.utils.StringUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import javax.annotation.Resource; import javax.annotation.Resource;
...@@ -23,6 +30,7 @@ import java.util.ArrayList; ...@@ -23,6 +30,7 @@ import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@Service @Service
...@@ -35,6 +43,10 @@ public class TheoreticalPracticeStudentQuestionBankServiceImpl extends ServiceIm ...@@ -35,6 +43,10 @@ public class TheoreticalPracticeStudentQuestionBankServiceImpl extends ServiceIm
private JwtTokenUtil jwtTokenUtil; private JwtTokenUtil jwtTokenUtil;
@Resource @Resource
private HttpServletRequest request; private HttpServletRequest request;
@Resource
private TheoreticalPracticeAnswerRecordMapper answerRecordMapper;
@Resource
private TheoreticalPracticeMapper theoreticalPracticeMapper;
@Override @Override
public List<String> groupByStudentId() { public List<String> groupByStudentId() {
...@@ -202,10 +214,89 @@ public class TheoreticalPracticeStudentQuestionBankServiceImpl extends ServiceIm ...@@ -202,10 +214,89 @@ public class TheoreticalPracticeStudentQuestionBankServiceImpl extends ServiceIm
} }
@Override @Override
public Boolean edit(TheoreticalPracticeStudentQuestionBankDTO theoreticalPracticeStudentQuestionBankDTO) { @Transactional(rollbackFor = Exception.class)
TheoreticalPracticeStudentQuestionBankEntity theoreticalPracticeStudentQuestionBank = getById(theoreticalPracticeStudentQuestionBankDTO.getId()); public Boolean edit(TheoreticalPracticeStudentQuestionBankDTO dto, String currentStudentId) {
//判断是否答对 validateAnswerRequest(dto, currentStudentId);
theoreticalPracticeStudentQuestionBankDTO.setResult(theoreticalPracticeStudentQuestionBank.getAnswer().equals(theoreticalPracticeStudentQuestionBankDTO.getActualChoice())); TheoreticalPracticeStudentQuestionBankEntity question = getById(dto.getId());
return updateById(theoreticalPracticeStudentQuestionBankDTO); if (question == null) {
throw new BusinessException("理论练习题目不存在");
}
if (!Objects.equals(question.getStudentId(), currentStudentId)) {
throw new BusinessException("只能提交当前登录学员自己的题目");
}
Date now = new Date();
List<String> activePracticeIds = theoreticalPracticeMapper.activePracticeIdsForAnswer(
currentStudentId, question.getId(), now);
if (activePracticeIds == null || activePracticeIds.isEmpty()) {
throw new BusinessException("当前没有可作答的理论练习,或题目不属于本期等级");
}
if (activePracticeIds.size() > 1) {
// 同一学员同一等级同时落入多个开放期会导致统计归属不确定,宁可拒绝也不串数据。
throw new BusinessException("当前存在多个重叠的理论练习,请联系管理员处理");
}
boolean correct = Objects.equals(question.getAnswer(), dto.getActualChoice());
TheoreticalPracticeAnswerRecordEntity record = new TheoreticalPracticeAnswerRecordEntity();
record.setId(IdWorker.getIdStr());
record.setPracticeId(activePracticeIds.get(0));
record.setStudentId(currentStudentId);
record.setQuestionId(question.getId());
record.setKnowledgePoint(question.getFirstLevelName());
record.setActualChoice(dto.getActualChoice());
record.setCorrect(correct);
record.setDurationSeconds(dto.getDurationSeconds());
record.setRequestId(dto.getRequestId().trim());
record.setAnsweredAt(now);
answerRecordMapper.insertIdempotently(record);
int affectedRows = answerRecordMapper.previousAffectedRows();
if (affectedRows == 0) {
// 首次请求已经完整提交;重试直接成功,不能再次累计或覆盖另一道题的当前状态。
return Boolean.TRUE;
}
// 只构造允许更新的三个字段,防止DTO继承实体后客户端越权修改答案、题干或学员ID。
TheoreticalPracticeStudentQuestionBankEntity update =
new TheoreticalPracticeStudentQuestionBankEntity();
update.setId(question.getId());
update.setActualChoice(dto.getActualChoice());
update.setResult(correct);
if (!updateById(update)) {
throw new BusinessException("保存答题结果失败,请稍后重试");
}
return Boolean.TRUE;
}
/** 对统计可信度有影响的字段全部由服务端严格校验,异常输入不会写入历史表。 */
private void validateAnswerRequest(TheoreticalPracticeStudentQuestionBankDTO dto,
String currentStudentId) {
if (dto == null) {
throw new BusinessException("答题内容不能为空");
}
if (currentStudentId == null || currentStudentId.trim().isEmpty()) {
throw new BusinessException("未获取到当前登录学员");
}
if (dto.getId() == null || dto.getId().trim().isEmpty()) {
throw new BusinessException("题目ID不能为空");
}
if (dto.getActualChoice() == null || dto.getActualChoice().trim().isEmpty()) {
throw new BusinessException("请选择答案后再提交");
}
if (dto.getActualChoice().length() > 1000) {
throw new BusinessException("答案内容不能超过1000个字符");
}
if (dto.getRequestId() == null || dto.getRequestId().trim().isEmpty()) {
throw new BusinessException("答题请求号不能为空");
}
if (dto.getRequestId().trim().length()
> TheoreticalPracticeConstants.MAX_REQUEST_ID_LENGTH) {
throw new BusinessException("答题请求号不能超过64个字符");
}
if (dto.getDurationSeconds() == null || dto.getDurationSeconds() < 0
|| dto.getDurationSeconds()
> TheoreticalPracticeConstants.MAX_ANSWER_DURATION_SECONDS) {
throw new BusinessException("本题耗时必须在0到3600秒之间");
}
} }
} }
<?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.TheoreticalPracticeAnswerRecordMapper">
<!--
ON DUPLICATE KEY只命中“学员+request_id”唯一索引。重复请求保持原记录不变,
affected rows为0,服务层据此跳过题库当前状态的第二次更新。
-->
<insert id="insertIdempotently">
INSERT INTO theoretical_practice_answer_record (
id, practice_id, student_id, question_id, knowledge_point,
actual_choice, is_correct, duration_seconds, request_id, answered_at
) VALUES (
#{id}, #{practiceId}, #{studentId}, #{questionId}, #{knowledgePoint},
#{actualChoice}, #{correct}, #{durationSeconds}, #{requestId}, #{answeredAt}
)
ON DUPLICATE KEY UPDATE id = id
</insert>
<select id="previousAffectedRows" resultType="java.lang.Integer">
select row_count()
</select>
</mapper>
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