diff --git a/src/main/java/com/sztzjy/blockchainsmartclaim/config/PasswordEncoderConfig.java b/src/main/java/com/sztzjy/blockchainsmartclaim/config/PasswordEncoderConfig.java new file mode 100644 index 0000000..485dabf --- /dev/null +++ b/src/main/java/com/sztzjy/blockchainsmartclaim/config/PasswordEncoderConfig.java @@ -0,0 +1,23 @@ +package com.sztzjy.blockchainsmartclaim.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +/** + * 密码加密器配置。 + *

+ * 单独抽出成一个配置类,不放在 {@code WebSecurityConfig} 里:WebSecurityConfig 需要注入 + * AuthenticationFilter,而过滤器链上的组件(如 TrainingAccountSyncService)又需要 PasswordEncoder, + * 若 Bean 定义在 WebSecurityConfig 内部会形成 + * AuthenticationFilter → TrainingAccountSyncService → WebSecurityConfig → AuthenticationFilter 的循环依赖。 + */ +@Configuration +public class PasswordEncoderConfig { + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} diff --git a/src/main/java/com/sztzjy/blockchainsmartclaim/config/security/AuthenticationFilter.java b/src/main/java/com/sztzjy/blockchainsmartclaim/config/security/AuthenticationFilter.java index e3fcfea..36efdc7 100644 --- a/src/main/java/com/sztzjy/blockchainsmartclaim/config/security/AuthenticationFilter.java +++ b/src/main/java/com/sztzjy/blockchainsmartclaim/config/security/AuthenticationFilter.java @@ -3,6 +3,7 @@ package com.sztzjy.blockchainsmartclaim.config.security; import cn.hutool.extra.servlet.ServletUtil; import com.sztzjy.blockchainsmartclaim.config.Constant; import com.sztzjy.blockchainsmartclaim.config.exception.UnAuthorizedException; +import com.sztzjy.blockchainsmartclaim.service.TrainingAccountSyncService; import com.sztzjy.blockchainsmartclaim.util.RedisUtil; import io.jsonwebtoken.ExpiredJwtException; import io.jsonwebtoken.MalformedJwtException; @@ -39,14 +40,17 @@ public class AuthenticationFilter extends OncePerRequestFilter { private final RedisUtil redisUtil; + /** 外部平台 token 身份适配:userId 修正为本地 users_info 的 UUID,身份字段全量以本地表为准 */ + private final TrainingAccountSyncService trainingAccountSyncService; + // @Value("${item.name}") // private String itemName; @Autowired - public AuthenticationFilter(RedisUtil redisUtil) { + public AuthenticationFilter(RedisUtil redisUtil, TrainingAccountSyncService trainingAccountSyncService) { this.redisUtil = redisUtil; - + this.trainingAccountSyncService = trainingAccountSyncService; } @Override @@ -80,6 +84,11 @@ public class AuthenticationFilter extends OncePerRequestFilter { String token = request.getHeader(Constant.AUTHORIZATION); + // 兜底:请求头没带 token 时,尝试从 Cookie 读取(内嵌场景前端可能只把 token 存在 Cookie 里) + if (token == null || token.isEmpty() || "null".equalsIgnoreCase(token) || "undefined".equalsIgnoreCase(token)) { + token = tokenFromCookie(request); + } + // 如果未携带 token,直接放行 if (token == null || token.isEmpty() || "null".equalsIgnoreCase(token) || "undefined".equalsIgnoreCase(token)) { filterChain.doFilter(request, response); @@ -94,6 +103,10 @@ public class AuthenticationFilter extends OncePerRequestFilter { } currentUser = TokenProvider.getJWTUser(token); + + // 外部平台 token(如训练系统):userId 是外部数字 ID,这里按学号+学校映射为本地账号, + // 修正后的上下文(userId/班级/学校/角色)全部来自本系统 users_info 表 + currentUser = trainingAccountSyncService.resolve(currentUser); // String itemName = redisUtil.item(); // String redisKey = itemName + "-token:" + currentUser.getUserId(); @@ -158,9 +171,13 @@ public class AuthenticationFilter extends OncePerRequestFilter { response.setStatus(HttpStatus.UNAUTHORIZED.value()); response.getWriter().print("无效的Token签名"); } catch (UnAuthorizedException e) { + System.err.println("[AUTH-DEBUG] 401 业务拒绝: " + e.getMessage()); response.setStatus(HttpStatus.UNAUTHORIZED.value()); response.getWriter().print(e.getMessage()); } catch (Exception e) { + // 临时排查日志:401 时把真实异常打出来 + System.err.println("[AUTH-DEBUG] 401 原因: " + e.getClass().getName() + ": " + e.getMessage()); + e.printStackTrace(); response.setStatus(HttpStatus.UNAUTHORIZED.value()); response.getWriter().print("无效的Token"); } finally { @@ -186,11 +203,36 @@ public class AuthenticationFilter extends OncePerRequestFilter { "/videos/**" ); + /** + * 从 Cookie 中提取 token:优先 Blockchain-Token,其次 Admin-Token。 + * 仅在 Authorization 请求头缺失时调用。Cookie 里存的是裸 JWT,这里补上 Bearer 前缀。 + */ + private String tokenFromCookie(HttpServletRequest request) { + javax.servlet.http.Cookie[] cookies = request.getCookies(); + if (cookies == null) { + return null; + } + String fromCookie = null; + for (javax.servlet.http.Cookie cookie : cookies) { + String name = cookie.getName(); + if ("Blockchain-Token".equals(name) || "Admin-Token".equals(name)) { + String value = cookie.getValue(); + if (value != null && !value.isEmpty() && !"null".equalsIgnoreCase(value)) { + fromCookie = value; + if ("Blockchain-Token".equals(name)) { + break; // Blockchain-Token 优先 + } + } + } + } + if (fromCookie == null) { + return null; + } + return StringUtils.startsWithIgnoreCase(fromCookie, "Bearer ") ? fromCookie : "Bearer " + fromCookie; + } + /** * 判断请求路径是否是在排除之外 - * - * @param request / - * @return true-是排除的 */ private boolean isExclude(HttpServletRequest request) { String requestURI = request.getRequestURI(); diff --git a/src/main/java/com/sztzjy/blockchainsmartclaim/config/security/JwtUser.java b/src/main/java/com/sztzjy/blockchainsmartclaim/config/security/JwtUser.java index b4f2636..abc9ea3 100644 --- a/src/main/java/com/sztzjy/blockchainsmartclaim/config/security/JwtUser.java +++ b/src/main/java/com/sztzjy/blockchainsmartclaim/config/security/JwtUser.java @@ -38,6 +38,9 @@ public class JwtUser implements UserDetails { // private Long teamPracticalTaskId; private String bearerToken; + /** 是否本系统签发的 token:createToken 恒定写入 studentId claim,外部平台(训练系统等)token 无此字段 */ + private boolean localIssued; + @Override public Collection getAuthorities() { return null; diff --git a/src/main/java/com/sztzjy/blockchainsmartclaim/config/security/TokenProvider.java b/src/main/java/com/sztzjy/blockchainsmartclaim/config/security/TokenProvider.java index 39e3571..7b974bc 100644 --- a/src/main/java/com/sztzjy/blockchainsmartclaim/config/security/TokenProvider.java +++ b/src/main/java/com/sztzjy/blockchainsmartclaim/config/security/TokenProvider.java @@ -70,6 +70,8 @@ public class TokenProvider { // jwtUser.setUserCompanyId(claims.get("userCompanyId") == null ? null : Convert.toLong(claims.get("userCompanyId"))); // jwtUser.setTeamPracticalTaskId(claims.get("teamPracticalTaskId") == null ? null : Convert.toLong(claims.get("teamPracticalTaskId"))); jwtUser.setAuthorityCodes((List) claims.get("authorityCodes")); + // 本系统 createToken 恒定写入 studentId claim;外部平台 token 无此字段,用于区分票源 + jwtUser.setLocalIssued(claims.containsKey("studentId")); return jwtUser; } catch (ExpiredJwtException e1) { throw new ExpiredJwtException(null, null, "token过期"); diff --git a/src/main/java/com/sztzjy/blockchainsmartclaim/config/security/WebSecurityConfig.java b/src/main/java/com/sztzjy/blockchainsmartclaim/config/security/WebSecurityConfig.java index 296d5ef..650d111 100644 --- a/src/main/java/com/sztzjy/blockchainsmartclaim/config/security/WebSecurityConfig.java +++ b/src/main/java/com/sztzjy/blockchainsmartclaim/config/security/WebSecurityConfig.java @@ -15,8 +15,6 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.session.SessionRegistry; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.header.writers.StaticHeadersWriter; import org.springframework.web.method.HandlerMethod; @@ -35,10 +33,7 @@ import java.util.Set; @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { - @Bean - public PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); - } + // PasswordEncoder 已迁至 config/PasswordEncoderConfig,避免与 AuthenticationFilter 形成循环依赖 // @Autowired // private RedisUtil redisUtil; diff --git a/src/main/java/com/sztzjy/blockchainsmartclaim/controller/training/TrainingRecordController.java b/src/main/java/com/sztzjy/blockchainsmartclaim/controller/training/TrainingRecordController.java new file mode 100644 index 0000000..1543ba0 --- /dev/null +++ b/src/main/java/com/sztzjy/blockchainsmartclaim/controller/training/TrainingRecordController.java @@ -0,0 +1,222 @@ +package com.sztzjy.blockchainsmartclaim.controller.training; + +import com.sztzjy.blockchainsmartclaim.config.security.AuthContextHolder; +import com.sztzjy.blockchainsmartclaim.config.security.JwtUser; +import com.sztzjy.blockchainsmartclaim.entity.training.TrainingRecord; +import com.sztzjy.blockchainsmartclaim.entity.training.TrainingScore; +import com.sztzjy.blockchainsmartclaim.service.TrainingRecordService; +import com.sztzjy.blockchainsmartclaim.service.TrainingRecordService.TrainingSummary; +import com.sztzjy.blockchainsmartclaim.util.ResultDataEntity; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.Data; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +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.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +/** + * 实训任务数据接口:保存(写两张表)、查询、逻辑删除、综合实训得分查询。 + * 全程 4 个大模块、11 个任务,完成进度按任务数计算。 + * 用户身份统一从 token 解析,不接收前端传入的 userId。 + */ +@Api(tags = "实训任务数据") +@RestController +@RequestMapping("/api/training/record") +@RequiredArgsConstructor +public class TrainingRecordController { + + private final TrainingRecordService trainingRecordService; + + @ApiOperation("保存任务数据与得分(同时更新成绩表)") + @PostMapping("/save") + public ResultDataEntity save(@RequestBody SaveRequest request) { + String userId = currentUserId(); + if (userId == null) { + return new ResultDataEntity<>(HttpStatus.UNAUTHORIZED, "未登录或登录已失效"); + } + if (request == null || !StringUtils.hasText(request.getBigModule()) || !StringUtils.hasText(request.getModule())) { + return new ResultDataEntity<>(HttpStatus.UNPROCESSABLE_ENTITY, "bigModule 和 module 不能为空"); + } + if (!StringUtils.hasText(request.getTask())) { + return new ResultDataEntity<>(HttpStatus.UNPROCESSABLE_ENTITY, "task 不能为空(共 11 个任务,进度按任务细分)"); + } + if (request.getScore() == null || request.getScore() < 0) { + return new ResultDataEntity<>(HttpStatus.UNPROCESSABLE_ENTITY, "score 不能为空且不能为负数"); + } + if (request.getPassedPointCount() != null && request.getPassedPointCount() < 0) { + return new ResultDataEntity<>(HttpStatus.UNPROCESSABLE_ENTITY, "passedPointCount 不能为负数"); + } + if (!StringUtils.hasText(request.getDataJson())) { + return new ResultDataEntity<>(HttpStatus.UNPROCESSABLE_ENTITY, "dataJson 不能为空"); + } + + TrainingRecord record = trainingRecordService.save(userId, request.getBigModule(), + request.getModule(), request.getTask(), request.getScore(), + request.getPassedPointCount(), request.getDataJson()); + TrainingScore score = trainingRecordService.currentScore(userId, request.getModule()); + return new ResultDataEntity<>(HttpStatus.OK, SaveResponse.of(record, score)); + } + + @ApiOperation("查询某个任务的数据") + @GetMapping + public ResultDataEntity get(@RequestParam String bigModule, + @RequestParam String module, + @RequestParam String task) { + String userId = currentUserId(); + if (userId == null) { + return new ResultDataEntity<>(HttpStatus.UNAUTHORIZED, "未登录或登录已失效"); + } + if (!StringUtils.hasText(bigModule) || !StringUtils.hasText(module) || !StringUtils.hasText(task)) { + return new ResultDataEntity<>(HttpStatus.UNPROCESSABLE_ENTITY, "bigModule、module 和 task 不能为空"); + } + TrainingRecord record = trainingRecordService.get(userId, bigModule, module, task); + TrainingScore score = trainingRecordService.currentScore(userId, module); + return new ResultDataEntity<>(HttpStatus.OK, QueryResponse.of(record, score)); + } + + @ApiOperation("逻辑删除任务数据(重新实训);不传 task 时删除该模块下全部任务") + @DeleteMapping + public ResultDataEntity delete(@RequestParam String bigModule, + @RequestParam String module, + @RequestParam(required = false) String task) { + String userId = currentUserId(); + if (userId == null) { + return new ResultDataEntity<>(HttpStatus.UNAUTHORIZED, "未登录或登录已失效"); + } + if (!StringUtils.hasText(bigModule) || !StringUtils.hasText(module)) { + return new ResultDataEntity<>(HttpStatus.UNPROCESSABLE_ENTITY, "bigModule 和 module 不能为空"); + } + trainingRecordService.delete(userId, bigModule, module, task); + TrainingScore score = trainingRecordService.currentScore(userId, module); + DeleteResponse response = new DeleteResponse(); + response.setDeleted(true); + response.setProgress(score.getProgress()); + response.setCurrentScore(score.getCurrentScore()); + response.setTotalScore(score.getTotalScore()); + return new ResultDataEntity<>(HttpStatus.OK, response); + } + + @ApiOperation("综合实训得分查询:综合得分、完成进度、作答点通过数合计、成绩时间、各任务完成情况") + @GetMapping("/summary") + public ResultDataEntity summary(@RequestParam String module) { + String userId = currentUserId(); + if (userId == null) { + return new ResultDataEntity<>(HttpStatus.UNAUTHORIZED, "未登录或登录已失效"); + } + if (!StringUtils.hasText(module)) { + return new ResultDataEntity<>(HttpStatus.UNPROCESSABLE_ENTITY, "module 不能为空"); + } + return new ResultDataEntity<>(HttpStatus.OK, trainingRecordService.summary(userId, module)); + } + + @ApiOperation("区块链账本:当前用户的存证记录,按修改时间降序(可按大模块/模块过滤)") + @GetMapping("/chain") + public ResultDataEntity> chain( + @RequestParam(required = false) String bigModule, + @RequestParam(required = false) String module) { + String userId = currentUserId(); + if (userId == null) { + return new ResultDataEntity<>(HttpStatus.UNAUTHORIZED, "未登录或登录已失效"); + } + JwtUser user = AuthContextHolder.get(); + String operator = user == null || !StringUtils.hasText(user.getName()) + ? userId : user.getName(); + return new ResultDataEntity<>(HttpStatus.OK, + trainingRecordService.chain(userId, bigModule, module, operator)); + } + + private String currentUserId() { + JwtUser user = AuthContextHolder.get(); + if (user == null || !StringUtils.hasText(user.getUserId())) { + return null; + } + return user.getUserId(); + } + + @Data + public static class SaveRequest { + /** 大模块标识 */ + private String bigModule; + /** 模块标识 */ + private String module; + /** 任务标识(共 11 个任务,进度按任务细分) */ + private String task; + /** 任务得分,前端判分后传入 */ + private Integer score; + /** 作答点通过数,前端传入(只存数据表,不参与成绩表计算) */ + private Integer passedPointCount; + /** 任务业务数据,JSON 字符串 */ + private String dataJson; + } + + @Data + public static class SaveResponse { + private String recordId; + private String bigModule; + private String module; + private String task; + private Integer score; + /** 当前任务累计通过的作答点数 */ + private Integer passedPointCount; + /** 本次生成的区块哈希(SHA-256 存证) */ + private String blockHash; + /** 完成进度 0-100(按 11 个任务计算) */ + private Integer progress; + /** 该模块综合实训得分 */ + private Integer currentScore; + private Integer totalScore; + /** 是否已全部完成(进度 100) */ + private Boolean completed; + + static SaveResponse of(TrainingRecord record, TrainingScore score) { + SaveResponse response = new SaveResponse(); + response.recordId = record.getId(); + response.bigModule = record.getBigModule(); + response.module = record.getModule(); + response.task = record.getTask(); + response.score = record.getScore(); + response.passedPointCount = record.getPassedPointCount(); + response.blockHash = record.getBlockHash(); + response.progress = score.getProgress(); + response.currentScore = score.getCurrentScore(); + response.totalScore = score.getTotalScore(); + response.completed = score.getProgress() != null && score.getProgress() >= 100; + return response; + } + } + + @Data + public static class QueryResponse { + /** 任务数据,未提交过时为 null */ + private TrainingRecord record; + private Integer progress; + private Integer currentScore; + private Integer totalScore; + + static QueryResponse of(TrainingRecord record, TrainingScore score) { + QueryResponse response = new QueryResponse(); + response.record = record; + response.progress = score.getProgress(); + response.currentScore = score.getCurrentScore(); + response.totalScore = score.getTotalScore(); + return response; + } + } + + @Data + public static class DeleteResponse { + private Boolean deleted; + private Integer progress; + private Integer currentScore; + private Integer totalScore; + } +} diff --git a/src/main/java/com/sztzjy/blockchainsmartclaim/entity/training/TrainingRecord.java b/src/main/java/com/sztzjy/blockchainsmartclaim/entity/training/TrainingRecord.java new file mode 100644 index 0000000..1ac0ef0 --- /dev/null +++ b/src/main/java/com/sztzjy/blockchainsmartclaim/entity/training/TrainingRecord.java @@ -0,0 +1,69 @@ +package com.sztzjy.blockchainsmartclaim.entity.training; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import com.fasterxml.jackson.annotation.JsonFormat; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; +import java.time.LocalDateTime; + +/** + * 实训模块数据:一个用户的一个(大模块 + 小模块)对应一条记录。 + * 重复提交同一模块时覆盖原记录,不新增行,保证进度不会重复累加。 + */ +@Data +@TableName("training_record") +@ApiModel(description = "实训模块数据") +public class TrainingRecord implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty("主键,UUID") + @TableId(value = "id", type = IdType.ASSIGN_UUID) + private String id; + + @ApiModelProperty("用户ID,从 token 解析") + private String userId; + + @ApiModelProperty("大模块标识") + private String bigModule; + + @ApiModelProperty("模块标识") + private String module; + + @ApiModelProperty("任务标识,共 11 个任务,进度按任务细分") + private String task; + + @ApiModelProperty("该模块得分") + private Integer score; + + @ApiModelProperty("作答点通过数,前端传入(仅本表存储,不参与成绩表计算)") + private Integer passedPointCount; + + @ApiModelProperty("区块哈希:SHA-256(动作+经办人+数据+时间戳+前区块哈希),每次提交/更新重算") + private String blockHash; + + @ApiModelProperty("模块业务数据,JSON 字符串") + private String dataJson; + + @ApiModelProperty("逻辑删除:0=正常,1=已删除") + @TableLogic(value = "0", delval = "1") + private Integer isDel; + + @ApiModelProperty("创建时间") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + @TableField(fill = FieldFill.INSERT) + private LocalDateTime createTime; + + @ApiModelProperty("修改时间") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + @TableField(fill = FieldFill.INSERT_UPDATE) + private LocalDateTime updateTime; +} diff --git a/src/main/java/com/sztzjy/blockchainsmartclaim/entity/training/TrainingScore.java b/src/main/java/com/sztzjy/blockchainsmartclaim/entity/training/TrainingScore.java new file mode 100644 index 0000000..6a0309d --- /dev/null +++ b/src/main/java/com/sztzjy/blockchainsmartclaim/entity/training/TrainingScore.java @@ -0,0 +1,57 @@ +package com.sztzjy.blockchainsmartclaim.entity.training; + +import com.baomidou.mybatisplus.annotation.FieldFill; +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 io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; +import java.time.LocalDateTime; + +/** + * 实训成绩与进度:一个用户的一个模块一行,随任务提交/删除实时重算。 + */ +@Data +@TableName("training_score") +@ApiModel(description = "实训成绩与完成进度") +public class TrainingScore implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty("主键,UUID") + @TableId(value = "id", type = IdType.ASSIGN_UUID) + private String id; + + @ApiModelProperty("用户ID") + private String userId; + + @ApiModelProperty("模块标识,userId + module 定位一行") + private String module; + + @ApiModelProperty("综合实训得分(该模块下各任务得分合计)") + private Integer currentScore; + + @ApiModelProperty("总满分") + private Integer totalScore; + + @ApiModelProperty("完成进度 0-100,按 11 个任务计算") + private Integer progress; + + @ApiModelProperty("逻辑删除:0=正常,1=已删除(手工管理,不使用 @TableLogic,便于恢复行)") + private Integer isDel; + + @ApiModelProperty("创建时间") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + @TableField(fill = FieldFill.INSERT) + private LocalDateTime createTime; + + @ApiModelProperty("修改时间") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + @TableField(fill = FieldFill.INSERT_UPDATE) + private LocalDateTime updateTime; +} diff --git a/src/main/java/com/sztzjy/blockchainsmartclaim/mapper/TrainingRecordMapper.java b/src/main/java/com/sztzjy/blockchainsmartclaim/mapper/TrainingRecordMapper.java new file mode 100644 index 0000000..c65b5de --- /dev/null +++ b/src/main/java/com/sztzjy/blockchainsmartclaim/mapper/TrainingRecordMapper.java @@ -0,0 +1,9 @@ +package com.sztzjy.blockchainsmartclaim.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sztzjy.blockchainsmartclaim.entity.training.TrainingRecord; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface TrainingRecordMapper extends BaseMapper { +} diff --git a/src/main/java/com/sztzjy/blockchainsmartclaim/mapper/TrainingScoreMapper.java b/src/main/java/com/sztzjy/blockchainsmartclaim/mapper/TrainingScoreMapper.java new file mode 100644 index 0000000..49d036f --- /dev/null +++ b/src/main/java/com/sztzjy/blockchainsmartclaim/mapper/TrainingScoreMapper.java @@ -0,0 +1,9 @@ +package com.sztzjy.blockchainsmartclaim.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.sztzjy.blockchainsmartclaim.entity.training.TrainingScore; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface TrainingScoreMapper extends BaseMapper { +} diff --git a/src/main/java/com/sztzjy/blockchainsmartclaim/service/TrainingAccountSyncService.java b/src/main/java/com/sztzjy/blockchainsmartclaim/service/TrainingAccountSyncService.java new file mode 100644 index 0000000..ce9d5b3 --- /dev/null +++ b/src/main/java/com/sztzjy/blockchainsmartclaim/service/TrainingAccountSyncService.java @@ -0,0 +1,166 @@ +package com.sztzjy.blockchainsmartclaim.service; + +import com.sztzjy.blockchainsmartclaim.config.exception.UnAuthorizedException; +import com.sztzjy.blockchainsmartclaim.entity.UsersInfo; +import com.sztzjy.blockchainsmartclaim.entity.UsersInfoExample; +import com.sztzjy.blockchainsmartclaim.mapper.UsersInfoMapper; +import com.sztzjy.blockchainsmartclaim.config.security.JwtUser; +import com.sztzjy.blockchainsmartclaim.util.UuidUtil; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; + +import java.util.Date; +import java.util.List; + +/** + * 外部平台 token 身份适配:训练系统等外部平台与本系统共用天择平台密钥, + * token 可直接验签解析,但其 userId 是外部系统的数字 ID,与本系统 users_info 的 UUID 不一致。 + *

+ * 本服务负责把外部身份映射为本地身份:按学号查 users_info(学号 + 学校一致才认), + * 查到即用本地数据,查不到则自动建档;解析后的请求上下文(userId、班级、学校、角色等) + * 全部以本地表为准,避免外部 userId 引发数据错乱。 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class TrainingAccountSyncService { + + /** 外部账号自动建档时的默认登录密码 */ + private static final String DEFAULT_PASSWORD = "123qwe"; + + private final UsersInfoMapper usersInfoMapper; + private final PasswordEncoder passwordEncoder; + private final ScenarioGroupProvisionService scenarioGroupProvisionService; + private final PlatformTransactionManager transactionManager; + + /** + * 把解析后的 JwtUser 修正为本地身份: + * - 本系统签发的 token(createToken 恒定带 studentId claim):按 userId 主键查 users_info, + * 查到则用本地记录重建上下文(身份字段以库为准);查不到(如管理端账号)保持原样; + * - 外部平台 token(无 studentId claim):按学号查 users_info,查到即用本地数据, + * 查不到则自动建档。 + * 注意:外部 token 的 schoolId 与本地库是两套 ID 体系,不参与强校验,仅记告警日志。 + */ + public JwtUser resolve(JwtUser external) { + if (external == null) { + return null; + } + + if (external.isLocalIssued()) { + // 本系统 token:userId 即 users_info 主键(管理端账号不在 users_info,查不到就走原逻辑) + UsersInfo local = usersInfoMapper.selectByPrimaryKey(external.getUserId()); + if (local == null) { + return external; + } + if (Boolean.TRUE.equals(local.getIsDeleted())) { + throw new UnAuthorizedException("本地账号已停用"); + } + return buildLocalJwtUser(local, external.getBearerToken()); + } + + // 外部平台 token:按学号映射本地账号 + if (!StringUtils.hasText(external.getUsername())) { + return external; + } + UsersInfo local = syncExternalAccount(external); + return buildLocalJwtUser(local, external.getBearerToken()); + } + + /** + * 按学号查本地账号:学号是平台内唯一标识(本人手机号格式),命中即认领; + * 学号不存在则自动建档。schoolId 只做告警不做拦截——外部平台与本地库的学校 ID 体系不同。 + */ + private UsersInfo syncExternalAccount(JwtUser external) { + UsersInfoExample example = new UsersInfoExample(); + example.createCriteria().andStudentIdEqualTo(external.getUsername()); + List matches = usersInfoMapper.selectByExample(example); + if (matches != null && matches.size() > 1) { + throw new UnAuthorizedException("本地存在重复账号,请联系管理员"); + } + + UsersInfo student = CollectionUtils.isEmpty(matches) ? null : matches.get(0); + if (student != null) { + if (Boolean.TRUE.equals(student.getIsDeleted())) { + throw new UnAuthorizedException("本地账号已停用"); + } + // 学校 ID 体系不同(外部 1287954432 vs 本地 232 等),不一致仅告警,不拦截 + if (StringUtils.hasText(student.getSchoolId()) + && !student.getSchoolId().equals(String.valueOf(external.getSchoolId()))) { + log.warn("external token schoolId mismatch, studentId={}, localSchoolId={}, tokenSchoolId={}(继续使用本地档案)", + student.getStudentId(), student.getSchoolId(), external.getSchoolId()); + } + return student; + } + + // 学号不存在:自动建档(用户 + 演练小组/业务角色 原子提交) + return new TransactionTemplate(transactionManager).execute(status -> createExternalStudent(external)); + } + + private UsersInfo createExternalStudent(JwtUser external) { + UsersInfo student = new UsersInfo(); + student.setUserId(UuidUtil.simpleUuid()); + student.setStudentId(external.getUsername()); + student.setUserName(StringUtils.hasText(external.getName()) ? external.getName() : external.getUsername()); + student.setPassword(passwordEncoder.encode(DEFAULT_PASSWORD)); + student.setRoleId((byte) (external.getRoleId() > 0 ? external.getRoleId() : 4)); + student.setSchoolId(String.valueOf(external.getSchoolId())); + student.setSchoolName(external.getSchoolName() == null ? "" : external.getSchoolName()); + student.setClassId(String.valueOf(external.getClassId())); + student.setClassName(external.getClassName() == null ? "" : external.getClassName()); + student.setCreateTime(new Date()); + student.setIsDeleted(false); + usersInfoMapper.insertSelective(student); + // 登录即开通:专属演练小组 + 全部业务角色(失败不阻断建档,角色按空处理) + try { + scenarioGroupProvisionService.ensureUserScenarioGroup(student.getUserId(), student.getUserName()); + } catch (RuntimeException e) { + log.warn("external account created but scenario group provision failed, userId={}", student.getUserId(), e); + } + log.info("external account auto-provisioned, studentId={}, schoolId={}, localUserId={}", + student.getStudentId(), student.getSchoolId(), student.getUserId()); + return student; + } + + /** + * 用本地 users_info 记录构建请求上下文:身份字段全部以本地表为准。 + */ + private JwtUser buildLocalJwtUser(UsersInfo student, String bearerToken) { + JwtUser jwtUser = new JwtUser(); + jwtUser.setUserId(student.getUserId()); + jwtUser.setUsername(student.getStudentId()); + jwtUser.setStudentId(student.getStudentId()); + jwtUser.setName(StringUtils.hasText(student.getUserName()) ? student.getUserName() : student.getStudentId()); + jwtUser.setRoleId(student.getRoleId() == null ? 4 : student.getRoleId()); + jwtUser.setClassId(parseInt(student.getClassId())); + jwtUser.setClassName(student.getClassName() == null ? "" : student.getClassName()); + jwtUser.setSchoolId(parseInt(student.getSchoolId())); + jwtUser.setSchoolName(student.getSchoolName() == null ? "" : student.getSchoolName()); + jwtUser.setAuthorityCodes(safeRoleCodes(student.getUserId())); + jwtUser.setBearerToken(bearerToken); + return jwtUser; + } + + private List safeRoleCodes(String userId) { + try { + List codes = scenarioGroupProvisionService.currentUserRoleCodes(userId); + return codes == null ? java.util.Collections.emptyList() : codes; + } catch (RuntimeException e) { + log.warn("load business roles failed, userId={}", userId, e); + return java.util.Collections.emptyList(); + } + } + + private int parseInt(String value) { + try { + return StringUtils.hasText(value) ? Integer.parseInt(value) : 0; + } catch (NumberFormatException e) { + return 0; + } + } +} diff --git a/src/main/java/com/sztzjy/blockchainsmartclaim/service/TrainingRecordService.java b/src/main/java/com/sztzjy/blockchainsmartclaim/service/TrainingRecordService.java new file mode 100644 index 0000000..93407d2 --- /dev/null +++ b/src/main/java/com/sztzjy/blockchainsmartclaim/service/TrainingRecordService.java @@ -0,0 +1,162 @@ +package com.sztzjy.blockchainsmartclaim.service; + +import com.sztzjy.blockchainsmartclaim.entity.training.TrainingRecord; +import com.sztzjy.blockchainsmartclaim.entity.training.TrainingScore; + +import java.util.List; + +/** + * 实训任务数据与成绩进度。 + *

+ * 规则:前端判分后把任务数据 + 得分提交上来,一个(bigModule, module, task)只保留一条有效记录; + * 全程共 4 个大模块、11 个任务,完成进度按任务数计算:完成数 / 11 × 100%。 + */ +public interface TrainingRecordService { + + /** + * 保存(或覆盖)某个任务的数据与得分,并重算成绩表。 + * 同一用户 + 同一 bigModule + 同一 module + 同一 task 已有未删除记录时修改该记录(不新增行), + * 得分取历史最高分,作答点通过数取历史最大值,业务数据取最新一次提交。 + * 作答点通过数只落在数据表,不参与成绩表计算。 + */ + TrainingRecord save(String userId, String bigModule, String module, String task, + Integer score, Integer passedPointCount, String dataJson); + + /** + * 查询某个任务的有效记录,不存在返回 null。 + */ + TrainingRecord get(String userId, String bigModule, String module, String task); + + /** + * 逻辑删除某个任务(或整个模块)的记录(重新实训用),并重算成绩表。 + * task 为空时删除该模块下全部任务。 + * + * @return 重算后的成绩行 + */ + TrainingScore delete(String userId, String bigModule, String module, String task); + + /** + * 综合实训得分查询:按 module 定位成绩行,返回综合得分、完成进度、 + * 作答点通过数合计(数据表累加)、成绩记录时间,以及 11 个任务的完成状态列表。 + */ + TrainingSummary summary(String userId, String module); + + /** + * 区块链账本:当前用户的存证记录(每条 = 一个任务的最新区块), + * 按修改时间降序返回;prevBlockHash 为按时间推算的前区块哈希(首条为 64 个 0)。 + * + * @param bigModule 可选,过滤大模块 + * @param module 可选,过滤模块 + * @param operator 经办人显示名(取自登录上下文) + */ + List chain(String userId, String bigModule, String module, String operator); + + /** + * 区块链账本单条记录(对应前端「区块链账本」面板的一行)。 + */ + class ChainEntry { + + /** 大模块标识 */ + private String bigModule; + /** 模块标识 */ + private String module; + /** 任务标识 */ + private String task; + /** 存证动作,如「实训任务提交:insurance/投保信息处理/保费测算」 */ + private String action; + /** 经办人(本地用户姓名) */ + private String operator; + /** 区块数据(任务业务数据 JSON 字符串) */ + private String data; + /** 前区块哈希(按时间推算;最早一块为 64 个 0) */ + private String prevBlockHash; + /** 本区块哈希(SHA-256) */ + private String blockHash; + /** 上链时间(该记录的修改时间,yyyy-MM-dd HH:mm:ss) */ + private String blockTime; + + public String getBigModule() { return bigModule; } + public void setBigModule(String bigModule) { this.bigModule = bigModule; } + public String getModule() { return module; } + public void setModule(String module) { this.module = module; } + public String getTask() { return task; } + public void setTask(String task) { this.task = task; } + public String getAction() { return action; } + public void setAction(String action) { this.action = action; } + public String getOperator() { return operator; } + public void setOperator(String operator) { this.operator = operator; } + public String getData() { return data; } + public void setData(String data) { this.data = data; } + public String getPrevBlockHash() { return prevBlockHash; } + public void setPrevBlockHash(String prevBlockHash) { this.prevBlockHash = prevBlockHash; } + public String getBlockHash() { return blockHash; } + public void setBlockHash(String blockHash) { this.blockHash = blockHash; } + public String getBlockTime() { return blockTime; } + public void setBlockTime(String blockTime) { this.blockTime = blockTime; } + } + + /** + * 查询当前用户某模块成绩;没有则返回全 0 的空成绩(不落库)。 + */ + TrainingScore currentScore(String userId, String module); + + /** + * 综合实训得分查询结果。 + */ + class TrainingSummary { + + /** 综合实训得分(该模块成绩行的分数) */ + private Integer currentScore; + /** 总满分 */ + private Integer totalScore; + /** 完成进度 0-100(按 11 个任务计算) */ + private Integer progress; + /** 作答点通过数合计(该模块数据表累加) */ + private Integer passedPointTotal; + /** 实训成绩记录时间(成绩表创建时间) */ + private String scoreTime; + /** 各任务完成情况列表 */ + private List tasks; + + public Integer getCurrentScore() { return currentScore; } + public void setCurrentScore(Integer currentScore) { this.currentScore = currentScore; } + public Integer getTotalScore() { return totalScore; } + public void setTotalScore(Integer totalScore) { this.totalScore = totalScore; } + public Integer getProgress() { return progress; } + public void setProgress(Integer progress) { this.progress = progress; } + public Integer getPassedPointTotal() { return passedPointTotal; } + public void setPassedPointTotal(Integer passedPointTotal) { this.passedPointTotal = passedPointTotal; } + public String getScoreTime() { return scoreTime; } + public void setScoreTime(String scoreTime) { this.scoreTime = scoreTime; } + public List getTasks() { return tasks; } + public void setTasks(List tasks) { this.tasks = tasks; } + } + + /** + * 单个任务的完成状态(对应前端「各模块完成情况」表格的一行)。 + */ + class TaskStatus { + + /** 模块名,如「投保信息处理」 */ + private String module; + /** 任务名,如「销售对话与需求挖掘」 */ + private String task; + /** 状态:true=通过,false=未通过 */ + private Boolean passed; + /** 该任务成绩(历史最高分),未完成时为 null */ + private Integer score; + /** 上链动作(当前无,返回「—」) */ + private String chainAction; + + public String getModule() { return module; } + public void setModule(String module) { this.module = module; } + public String getTask() { return task; } + public void setTask(String task) { this.task = task; } + public Boolean getPassed() { return passed; } + public void setPassed(Boolean passed) { this.passed = passed; } + public Integer getScore() { return score; } + public void setScore(Integer score) { this.score = score; } + public String getChainAction() { return chainAction; } + public void setChainAction(String chainAction) { this.chainAction = chainAction; } + } +} diff --git a/src/main/java/com/sztzjy/blockchainsmartclaim/service/impl/TrainingRecordServiceImpl.java b/src/main/java/com/sztzjy/blockchainsmartclaim/service/impl/TrainingRecordServiceImpl.java new file mode 100644 index 0000000..67bb197 --- /dev/null +++ b/src/main/java/com/sztzjy/blockchainsmartclaim/service/impl/TrainingRecordServiceImpl.java @@ -0,0 +1,353 @@ +package com.sztzjy.blockchainsmartclaim.service.impl; + +import cn.hutool.crypto.digest.DigestUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.sztzjy.blockchainsmartclaim.entity.training.TrainingRecord; +import com.sztzjy.blockchainsmartclaim.entity.training.TrainingScore; +import com.sztzjy.blockchainsmartclaim.mapper.TrainingRecordMapper; +import com.sztzjy.blockchainsmartclaim.mapper.TrainingScoreMapper; +import com.sztzjy.blockchainsmartclaim.service.TrainingRecordService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +@Service +@RequiredArgsConstructor +public class TrainingRecordServiceImpl implements TrainingRecordService { + + /** 时间格式化 */ + private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + /** + * 任务字典:仅保留「模块二 · 核保」「模块四 · 续保」两个模块,共 5 个任务。 + * key = 模块名(前端展示用),value = 该模块下的任务名列表(与前端保存时传的 task 值保持一致)。 + * 进度 = 已完成任务数 / 字典内任务总数 × 100。 + */ + private static final Map> TASK_DICTIONARY = new LinkedHashMap>() {{ + put("核保", Arrays.asList("单证核验", "风险评估", "出具核保结论")); + put("续保", Arrays.asList("续保资格评估(4个客户)", "速达续保方案")); + }}; + + /** 需要展示的任务全集:任务名 → 所属模块名(任务名全局唯一,作为匹配键) */ + private static final Map TASK_MODULE_MAP = new LinkedHashMap() {{ + TASK_DICTIONARY.forEach((moduleName, tasks) -> + tasks.forEach(task -> put(task, moduleName))); + }}; + + /** 总任务数:字典内任务总数(当前 5 个),全部完成 = 100%。 */ + private static final int TOTAL_TASK_COUNT = TASK_MODULE_MAP.size(); + /** 每个任务满分 100;总满分 = 任务数 × 100(当前 500)。 */ + private static final int TOTAL_SCORE = TOTAL_TASK_COUNT * 100; + + /** 创世前区块哈希:首条存证没有上一块,用 64 个 0。 */ + private static final String GENESIS_PREV_HASH = "0000000000000000000000000000000000000000000000000000000000000000"; + + private final TrainingRecordMapper trainingRecordMapper; + private final TrainingScoreMapper trainingScoreMapper; + + @Override + public TrainingRecord save(String userId, String bigModule, String module, String task, + Integer score, Integer passedPointCount, String dataJson) { + // 先取链上最新区块哈希作为本块的前区块哈希(每次提交都会产生新区块) + String prevHash = findLatestBlockHash(userId); + String blockHash = buildBlockHash(bigModule, module, task, userId, dataJson, prevHash); + + TrainingRecord existing = findRecord(userId, bigModule, module, task); + if (existing != null) { + // 同一任务重复提交:修改原记录(不新增行),成绩保留历史最高分,数据取最新一次 + int previousScore = existing.getScore() == null ? 0 : existing.getScore(); + existing.setScore(Math.max(previousScore, score)); + // 作答点通过数只增不减,取历史最大值;该字段不参与成绩表计算 + int previousPassed = existing.getPassedPointCount() == null ? 0 : existing.getPassedPointCount(); + existing.setPassedPointCount(Math.max(previousPassed, passedPointCount == null ? 0 : passedPointCount)); + existing.setDataJson(dataJson); + // 每次更新都重算并覆盖区块哈希(新区块基于当前链尾) + existing.setBlockHash(blockHash); + trainingRecordMapper.updateById(existing); + refreshScore(userId); + return existing; + } + TrainingRecord record = new TrainingRecord(); + record.setUserId(userId); + record.setBigModule(bigModule); + record.setModule(module); + record.setTask(task); + record.setScore(score); + record.setPassedPointCount(passedPointCount); + record.setBlockHash(blockHash); + record.setDataJson(dataJson); + record.setIsDel(0); + trainingRecordMapper.insert(record); + refreshScore(userId); + return record; + } + + @Override + public TrainingRecord get(String userId, String bigModule, String module, String task) { + return findRecord(userId, bigModule, module, task); + } + + @Override + public TrainingScore delete(String userId, String bigModule, String module, String task) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(TrainingRecord::getUserId, userId) + .eq(TrainingRecord::getBigModule, bigModule) + .eq(TrainingRecord::getModule, module); + if (StringUtils.hasText(task)) { + // 只重做单个任务 + wrapper.eq(TrainingRecord::getTask, task); + } + // @TableLogic:delete 实际执行 update ... set is_del = 1,保留审计痕迹 + trainingRecordMapper.delete(wrapper); + refreshScore(userId); + return findScore(userId, module); + } + + @Override + public TrainingSummary summary(String userId, String module) { + TrainingSummary summary = new TrainingSummary(); + + // 该模块的成绩行(可能被逻辑删除 / 不存在) + TrainingScore scoreRow = findScore(userId, module); + summary.setCurrentScore(scoreRow == null || scoreRow.getCurrentScore() == null ? 0 : scoreRow.getCurrentScore()); + summary.setTotalScore(TOTAL_SCORE); + + // 完成进度:按字典内 5 个任务计算(成绩行里存的也是这个值) + List validRecords = findValidRecords(userId); + int completed = countCompletedTasks(validRecords); + summary.setProgress(Math.min(completed * 100 / TOTAL_TASK_COUNT, 100)); + + // 作答点通过数合计:该模块数据表累加得到 + int passedTotal = 0; + for (TrainingRecord record : validRecords) { + if (module.equals(record.getModule()) && record.getPassedPointCount() != null) { + passedTotal += record.getPassedPointCount(); + } + } + summary.setPassedPointTotal(passedTotal); + + // 实训成绩记录时间:成绩表的创建时间 + summary.setScoreTime(scoreRow == null || scoreRow.getCreateTime() == null + ? null : TIME_FORMATTER.format(scoreRow.getCreateTime())); + + // 任务完成情况列表:核保/续保 2 模块 5 个任务全量返回(未做过的「未通过」、0 分) + summary.setTasks(buildTaskStatusList(validRecords)); + return summary; + } + + @Override + public List chain(String userId, String bigModule, String module, String operator) { + // 升序遍历以便推算前区块哈希(每条的前块 = 时间上紧邻的上一条当前哈希) + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(TrainingRecord::getUserId, userId) + .isNotNull(TrainingRecord::getBlockHash) + .orderByAsc(TrainingRecord::getUpdateTime); + if (StringUtils.hasText(bigModule)) { + wrapper.eq(TrainingRecord::getBigModule, bigModule); + } + if (StringUtils.hasText(module)) { + wrapper.eq(TrainingRecord::getModule, module); + } + List ascending = trainingRecordMapper.selectList(wrapper); + + List entries = new ArrayList<>(); + String prevHash = GENESIS_PREV_HASH; + for (TrainingRecord record : ascending) { + ChainEntry entry = new ChainEntry(); + entry.setBigModule(record.getBigModule()); + entry.setModule(record.getModule()); + entry.setTask(record.getTask()); + entry.setAction("实训任务提交:" + record.getBigModule() + "/" + record.getModule() + "/" + record.getTask()); + entry.setOperator(operator); + entry.setData(record.getDataJson()); + entry.setPrevBlockHash(prevHash); + entry.setBlockHash(record.getBlockHash()); + entry.setBlockTime(record.getUpdateTime() == null ? null : TIME_FORMATTER.format(record.getUpdateTime())); + entries.add(entry); + prevHash = record.getBlockHash(); + } + // 按修改时间降序输出(最新区块在前) + java.util.Collections.reverse(entries); + return entries; + } + + @Override + public TrainingScore currentScore(String userId, String module) { + TrainingScore score = findScore(userId, module); + if (score != null) { + return score; + } + TrainingScore empty = new TrainingScore(); + empty.setUserId(userId); + empty.setModule(module); + empty.setCurrentScore(0); + empty.setTotalScore(TOTAL_SCORE); + empty.setProgress(countCompletedTasks(findValidRecords(userId)) * 100 / TOTAL_TASK_COUNT); + empty.setIsDel(0); + return empty; + } + + /** + * 取该用户链上最新区块的哈希(按更新时间倒序的第一条有效记录); + * 没有任何记录时返回创世前区块哈希(64 个 0)。 + */ + private String findLatestBlockHash(String userId) { + TrainingRecord latest = trainingRecordMapper.selectOne(new LambdaQueryWrapper() + .eq(TrainingRecord::getUserId, userId) + .isNotNull(TrainingRecord::getBlockHash) + .orderByDesc(TrainingRecord::getUpdateTime) + .last("limit 1")); + return latest == null || latest.getBlockHash() == null ? GENESIS_PREV_HASH : latest.getBlockHash(); + } + + /** + * 生成区块哈希:SHA-256(动作 + 经办人 + 数据 + 时间戳 + 前区块哈希)。 + * 动作 = 「实训任务提交:大模块/模块/任务」;经办人 = token 中的 userId;数据 = dataJson。 + */ + private String buildBlockHash(String bigModule, String module, String task, String userId, + String dataJson, String prevHash) { + String action = "实训任务提交:" + bigModule + "/" + module + "/" + task; + String timestamp = TIME_FORMATTER.format(java.time.LocalDateTime.now()); + String input = action + userId + dataJson + timestamp + prevHash; + return DigestUtil.sha256Hex(input); + } + + private TrainingRecord findRecord(String userId, String bigModule, String module, String task) { return trainingRecordMapper.selectOne(new LambdaQueryWrapper() + .eq(TrainingRecord::getUserId, userId) + .eq(TrainingRecord::getBigModule, bigModule) + .eq(TrainingRecord::getModule, module) + .eq(TrainingRecord::getTask, task) + .orderByDesc(TrainingRecord::getCreateTime) + .last("limit 1")); + } + + private List findValidRecords(String userId) { + // @TableLogic 自动过滤 is_del = 1 + return trainingRecordMapper.selectList(new LambdaQueryWrapper() + .eq(TrainingRecord::getUserId, userId) + .isNotNull(TrainingRecord::getScore)); + } + + private TrainingScore findScore(String userId, String module) { + // 成绩行的 is_del 为手工管理,这里只取正常行 + return trainingScoreMapper.selectOne(new LambdaQueryWrapper() + .eq(TrainingScore::getUserId, userId) + .eq(TrainingScore::getModule, module) + .eq(TrainingScore::getIsDel, 0) + .last("limit 1")); + } + + /** + * 统计已完成的任务数:只统计字典内(需展示)的任务,按任务名去重。 + */ + private int countCompletedTasks(List validRecords) { + Set completed = new HashSet<>(); + for (TrainingRecord record : validRecords) { + if (TASK_MODULE_MAP.containsKey(record.getTask())) { + completed.add(record.getTask()); + } + } + return completed.size(); + } + + /** + * 构建需展示任务的完成情况列表(按任务字典顺序,未做过的也返回): + * 已完成的标「通过」并带得分,未做过的标「未通过」、分数 0。 + * 按任务名匹配(任务名全局唯一),不依赖前端 bigModule/module 的取值约定。 + */ + private List buildTaskStatusList(List validRecords) { + // 任务名 -> 得分(同任务多条时取最高) + Map scoreByTask = new HashMap<>(); + for (TrainingRecord record : validRecords) { + int score = record.getScore() == null ? 0 : record.getScore(); + scoreByTask.merge(record.getTask(), score, Math::max); + } + + List tasks = new ArrayList<>(); + for (Map.Entry> entry : TASK_DICTIONARY.entrySet()) { + String moduleName = entry.getKey(); + for (String taskName : entry.getValue()) { + Integer score = scoreByTask.get(taskName); + TaskStatus status = new TaskStatus(); + status.setModule(moduleName); + status.setTask(taskName); + status.setPassed(score != null); + // 未做题也返回 0 分(不返回 null,便于前端直接展示) + status.setScore(score == null ? 0 : score); + status.setChainAction("—"); + tasks.add(status); + } + } + return tasks; + } + + /** + * 按有效记录重算成绩表(按模块一行): + * - progress:全局口径,字典内任务完成数 / 任务总数 × 100,封顶 100; + * - current_score:该模块下各任务得分之和(封顶总满分); + * - 该模块下已无有效任务时,对应成绩行逻辑删除。 + */ + private void refreshScore(String userId) { + List validRecords = findValidRecords(userId); + + // 全局进度 + int progress = Math.min(countCompletedTasks(validRecords) * 100 / TOTAL_TASK_COUNT, 100); + + // 按模块分组求和 + Map scoreByModule = new HashMap<>(); + for (TrainingRecord record : validRecords) { + String key = record.getModule(); + scoreByModule.merge(key, record.getScore() == null ? 0 : record.getScore(), Integer::sum); + } + + // 已有的成绩行(含被逻辑删除的,便于同唯一键恢复) + List allRows = trainingScoreMapper.selectList( + new LambdaQueryWrapper() + .eq(TrainingScore::getUserId, userId)); + Map rowByModule = new HashMap<>(); + for (TrainingScore row : allRows) { + rowByModule.put(row.getModule(), row); + } + + // 更新 / 恢复有任务记录的模块行 + for (Map.Entry entry : scoreByModule.entrySet()) { + String module = entry.getKey(); + int moduleScore = Math.min(entry.getValue(), TOTAL_SCORE); + TrainingScore row = rowByModule.get(module); + if (row == null) { + row = new TrainingScore(); + row.setUserId(userId); + row.setModule(module); + row.setCurrentScore(moduleScore); + row.setTotalScore(TOTAL_SCORE); + row.setProgress(progress); + row.setIsDel(0); + trainingScoreMapper.insert(row); + } else { + row.setCurrentScore(moduleScore); + row.setTotalScore(TOTAL_SCORE); + row.setProgress(progress); + row.setIsDel(0); + trainingScoreMapper.updateById(row); + } + } + + // 无有效任务的模块行:逻辑删除(手工 set is_del = 1) + for (TrainingScore row : allRows) { + if (!scoreByModule.containsKey(row.getModule()) && (row.getIsDel() == null || row.getIsDel() == 0)) { + row.setIsDel(1); + trainingScoreMapper.updateById(row); + } + } + } +}