feat:文件上传的功能开发

master
赵佳正 1 month ago
parent 79ecc277e2
commit 9723e00c3b

@ -0,0 +1,113 @@
package com.yau.digitalrmb.identity.application;
import cn.hutool.core.util.IdUtil;
import com.yau.digitalrmb.identity.infrastructure.persistence.entity.UserEntity;
import com.yau.digitalrmb.identity.infrastructure.persistence.mapper.UserMapper;
import com.yau.digitalrmb.identity.interfaces.dto.ZYUserInfo;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* 开放接口:批量把智云/平台下发的用户账号信息同步写入本系统 {@code sys_user}。
*
* <p>逻辑与上游 CrossTrainingPlatform 的自动同步保持一致:仅新增不存在的账号(按学号去重跳过已存在),
* 不做覆盖更新;分批次查询已存在学号、分批次插入,避免 N+1。
* 注意:上游那段“异步初始化学校业务数据”的代码依赖一堆本项目不存在的服务,这里不照搬。
*
* <p>密码按本系统约定用 BCrypt 哈希后落库(与 {@link LocalSsoAccountService} 一致),
* 入参密码为空时回退到默认口令 {@code 123qwe},而不是像上游那样明文存储。
*/
@Service
public class StudentInfoSyncService {
private static final int QUERY_BATCH_SIZE = 1000;
private static final int INSERT_BATCH_SIZE = 500;
private static final String DEFAULT_PASSWORD = "123qwe";
private final UserMapper userMapper;
private final PasswordEncoder passwordEncoder;
public StudentInfoSyncService(UserMapper userMapper, PasswordEncoder passwordEncoder) {
this.userMapper = userMapper;
this.passwordEncoder = passwordEncoder;
}
@Transactional
public String synchronizationStudentInfoByAuto(List<ZYUserInfo> zyUserInfoList) {
if (CollectionUtils.isEmpty(zyUserInfoList)) {
return "同步数据为空";
}
// ========== 性能优化1:批量查询已存在的学号,避免循环 N+1 查询 ==========
List<String> allStudentIds = zyUserInfoList.stream()
.map(ZYUserInfo::getUsername)
.filter(StringUtils::hasText)
.distinct()
.collect(Collectors.toList());
if (allStudentIds.isEmpty()) {
return "同步数据为空";
}
Set<String> existingStudentIds = new HashSet<>();
for (int i = 0; i < allStudentIds.size(); i += QUERY_BATCH_SIZE) {
List<String> subList = allStudentIds.subList(i, Math.min(i + QUERY_BATCH_SIZE, allStudentIds.size()));
List<String> existIds = userMapper.selectExistingStudentIds(subList);
if (!CollectionUtils.isEmpty(existIds)) {
existingStudentIds.addAll(existIds);
}
}
// ========== 性能优化2:内存中过滤,构建待插入用户列表 ==========
List<UserEntity> users = new ArrayList<>();
LocalDateTime now = LocalDateTime.now();
for (ZYUserInfo zyUserInfo : zyUserInfoList) {
String username = zyUserInfo.getUsername();
if (!StringUtils.hasText(username) || existingStudentIds.contains(username)) {
continue;
}
UserEntity stuUser = new UserEntity();
stuUser.setUserId(IdUtil.randomUUID());
stuUser.setZyUserId(zyUserInfo.getUserId() != null ? zyUserInfo.getUserId().toString() : null);
stuUser.setStudentId(username);
stuUser.setUserName(StringUtils.hasText(zyUserInfo.getName()) ? zyUserInfo.getName() : username);
String rawPassword = StringUtils.hasText(zyUserInfo.getPassword()) ? zyUserInfo.getPassword() : DEFAULT_PASSWORD;
stuUser.setPassword(passwordEncoder.encode(rawPassword));
stuUser.setRoleId(zyUserInfo.getRoleId() != null ? zyUserInfo.getRoleId() : 4);
stuUser.setClassId(zyUserInfo.getClassId() != null ? zyUserInfo.getClassId().toString() : null);
stuUser.setClassName(zyUserInfo.getClassName());
stuUser.setSchoolId(zyUserInfo.getSchoolId() != null ? zyUserInfo.getSchoolId().toString() : null);
stuUser.setSchoolName(zyUserInfo.getSchoolName());
stuUser.setPhone(zyUserInfo.getPhone());
stuUser.setCollegeId(zyUserInfo.getCollegeId() != null ? zyUserInfo.getCollegeId().toString() : null);
stuUser.setCollegeName(zyUserInfo.getCollegeName());
stuUser.setMajorId(zyUserInfo.getMajorId() != null ? zyUserInfo.getMajorId().toString() : null);
stuUser.setMajorName(zyUserInfo.getMajorName());
stuUser.setCreateTime(now);
users.add(stuUser);
}
if (users.isEmpty()) {
return "账号已全部存在";
}
// ========== 性能优化3:批量插入,避免循环 N+1 插入(每批 500 条) ==========
for (int i = 0; i < users.size(); i += INSERT_BATCH_SIZE) {
List<UserEntity> subList = users.subList(i, Math.min(i + INSERT_BATCH_SIZE, users.size()));
userMapper.insertBatch(subList);
}
return "自动同步学生信息成功!" + "同步" + users.size() + "条用户数据";
}
}

@ -2,11 +2,14 @@ package com.yau.digitalrmb.identity.infrastructure.persistence.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yau.digitalrmb.identity.infrastructure.persistence.entity.UserEntity;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
@Mapper
public interface UserMapper extends BaseMapper<UserEntity> {
@Select("SELECT user_id, student_id, password, user_name, class_id, class_name, phone, "
@ -20,4 +23,19 @@ public interface UserMapper extends BaseMapper<UserEntity> {
+ "WHERE user_id = #{userId} AND (is_deleted = 0 OR is_deleted IS NULL)")
int upgradeLegacyPassword(@Param("userId") String userId,
@Param("encodedPassword") String encodedPassword);
@Select("<script>SELECT student_id FROM sys_user WHERE student_id IN "
+ "<foreach collection='ids' item='id' open='(' separator=',' close=')'>#{id}</foreach> "
+ "AND (is_deleted = 0 OR is_deleted IS NULL)</script>")
List<String> selectExistingStudentIds(@Param("ids") List<String> ids);
@Insert("<script>INSERT INTO sys_user (user_id, student_id, password, user_name, class_id, class_name, "
+ "phone, school_name, school_id, college_id, college_name, major_id, major_name, "
+ "role_id, create_time, is_deleted, zy_user_id) VALUES "
+ "<foreach collection='list' item='u' separator=','>"
+ "(#{u.userId}, #{u.studentId}, #{u.password}, #{u.userName}, #{u.classId}, #{u.className}, "
+ "#{u.phone}, #{u.schoolName}, #{u.schoolId}, #{u.collegeId}, #{u.collegeName}, "
+ "#{u.majorId}, #{u.majorName}, #{u.roleId}, #{u.createTime}, 0, #{u.zyUserId})"
+ "</foreach></script>")
int insertBatch(@Param("list") List<UserEntity> list);
}

@ -0,0 +1,31 @@
package com.yau.digitalrmb.identity.interfaces.dto;
import lombok.Getter;
import lombok.Setter;
/**
* 智云/平台下发的用户同步信息(开放接口入参)。
*
* <p>字段命名与上游 CrossTrainingPlatform 保持一致,便于直接反序列化。其中
* {@code userId/schoolId/classId} 为整型,本系统 {@code sys_user} 对应列是字符串类型,
* 落库时统一转成字符串;{@code collegeId/majorId} 同理。
*/
@Getter
@Setter
public class ZYUserInfo {
private String username;
private String password;
private String name;
private Integer userId;
private Integer roleId;
private Integer schoolId;
private String schoolName;
private Integer classId;
private String className;
private String phone;
private Long collegeId;
private String collegeName;
private Long majorId;
private String majorName;
}

@ -0,0 +1,38 @@
package com.yau.digitalrmb.identity.interfaces.rest;
import com.yau.digitalrmb.identity.application.StudentInfoSyncService;
import com.yau.digitalrmb.identity.interfaces.dto.ZYUserInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 开放接口:批量同步学生/用户账号信息到本系统 {@code sys_user}。
*
* <p>该接口在 {@code SecurityConfig} 中配置为匿名可访问(对应上游的 {@code @AnonymousAccess}),
* 由智云/上游平台调用,批量下发账号数据。已存在的学号自动跳过,只新增不存在的账号。
*/
@RestController
@RequestMapping("/api/v1/user")
@Tag(name = "用户账号同步", description = "开放接口,批量把平台下发的用户账号信息写入 sys_user")
public class StudentInfoSyncController {
private final StudentInfoSyncService service;
public StudentInfoSyncController(StudentInfoSyncService service) {
this.service = service;
}
@PostMapping("synchronizationStudentInfoByAuto")
@Operation(summary = "开放接口,自动同步学生信息",
description = "批量把平台下发的用户账号信息写入 sys_user:已存在的学号跳过,只新增不存在的账号。"
+ "返回纯文本结果(同步数据为空 / 账号已全部存在 / 自动同步学生信息成功!同步N条用户数据)。")
public String synchronizationStudentInfoByAuto(@RequestBody List<ZYUserInfo> zyUserInfoList) {
return service.synchronizationStudentInfoByAuto(zyUserInfoList);
}
}

@ -52,6 +52,7 @@ public class SecurityConfig {
.authorizeRequests(authorize -> authorize
.antMatchers("/actuator/health", "/api/v1/auth/login", "/api/v1/auth/sso",
"/api/user/login",
"/api/v1/user/synchronizationStudentInfoByAuto",
"/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html",
"/doc.html", "/webjars/**", "/swagger-resources/**")
.permitAll()

@ -0,0 +1,21 @@
-- 单点登录账户落地改造:学校/学院/专业信息并入 sys_user 主表,弃用 platform_user_snapshot
--
-- 背景:SSO 登录原先会把用户信息写入 platform_user_snapshot 表,而该表
-- platform_user_id 列在存量库中被建成了 bigint,写入本系统 UUID 主键时报
-- "Data truncated for column 'platform_user_id'"。
-- 现改为直接把用户信息写进 sys_user 主表,不再使用快照表。
--
-- 适用范围:本项目已有的存量数据库(dev/prod)。
-- 注意 application-dev.yml 为 spring.sql.init.mode: never,schema.sql 不会自动执行到运行库,
-- 因此存量库必须手动执行本脚本。
-- 1) sys_user 增加学院/专业 4 列(若列已存在会报 Duplicate column,可忽略)
ALTER TABLE sys_user
ADD COLUMN college_id VARCHAR(64) NULL COMMENT '学院编号' AFTER school_id,
ADD COLUMN college_name VARCHAR(128) NULL COMMENT '学院名称' AFTER college_id,
ADD COLUMN major_id VARCHAR(64) NULL COMMENT '专业编号' AFTER college_name,
ADD COLUMN major_name VARCHAR(128) NULL COMMENT '专业名称' AFTER major_id;
-- 2) 删除已弃用的平台用户快照表(其数据不再被任何代码读写)
-- platform_user_snapshot 已从代码与 schema.sql 中移除。
DROP TABLE IF EXISTS platform_user_snapshot;

@ -0,0 +1,110 @@
package com.yau.digitalrmb.identity.interfaces.rest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
class StudentInfoSyncControllerTest {
@Autowired private MockMvc mockMvc;
@Autowired private JdbcTemplate jdbc;
private static final String BODY = "["
+ "{\"username\":\"stu-sync-1\",\"password\":\"pwd1\",\"name\":\"同步生一\",\"userId\":1001,"
+ "\"roleId\":4,\"schoolId\":2001,\"schoolName\":\"延安大学\",\"classId\":3001,\"className\":\"同步班1\","
+ "\"phone\":\"13800000001\",\"collegeId\":11,\"collegeName\":\"计算机学院\",\"majorId\":22,\"majorName\":\"软件工程\"},"
+ "{\"username\":\"stu-sync-2\",\"password\":\"pwd2\",\"name\":\"同步生二\",\"userId\":1002,"
+ "\"roleId\":4,\"schoolId\":2001,\"schoolName\":\"延安大学\",\"classId\":3001,\"className\":\"同步班1\","
+ "\"phone\":\"13800000002\",\"collegeId\":11,\"collegeName\":\"计算机学院\",\"majorId\":23,\"majorName\":\"网络工程\"}"
+ "]";
@BeforeEach
void seed() {
clean();
}
@AfterEach
void tearDown() {
clean();
}
@Test
void syncInsertsNewUsersWithCollegeAndMajor() throws Exception {
mockMvc.perform(post("/api/v1/user/synchronizationStudentInfoByAuto")
.contentType(org.springframework.http.MediaType.APPLICATION_JSON).content(BODY))
.andExpect(status().isOk())
.andExpect(content().string(containsString("自动同步学生信息成功!同步2条用户数据")));
Integer count = jdbc.queryForObject(
"SELECT COUNT(*) FROM sys_user WHERE student_id IN ('stu-sync-1','stu-sync-2')", Integer.class);
org.junit.jupiter.api.Assertions.assertEquals(2, count);
String college = jdbc.queryForObject(
"SELECT college_id FROM sys_user WHERE student_id='stu-sync-1'", String.class);
String major = jdbc.queryForObject(
"SELECT major_id FROM sys_user WHERE student_id='stu-sync-1'", String.class);
String school = jdbc.queryForObject(
"SELECT school_id FROM sys_user WHERE student_id='stu-sync-1'", String.class);
String password = jdbc.queryForObject(
"SELECT password FROM sys_user WHERE student_id='stu-sync-1'", String.class);
org.junit.jupiter.api.Assertions.assertEquals("11", college);
org.junit.jupiter.api.Assertions.assertEquals("22", major);
org.junit.jupiter.api.Assertions.assertEquals("2001", school);
org.junit.jupiter.api.Assertions.assertNotNull(password);
org.junit.jupiter.api.Assertions.assertTrue(password.startsWith("$2a$"),
"密码应经 BCrypt 哈希,而非明文");
}
@Test
void syncSkipsExistingAccounts() throws Exception {
// 第一次同步:新增 2 条
mockMvc.perform(post("/api/v1/user/synchronizationStudentInfoByAuto")
.contentType(org.springframework.http.MediaType.APPLICATION_JSON).content(BODY))
.andExpect(status().isOk())
.andExpect(content().string(containsString("同步2条用户数据")));
// 第二次同步:全部已存在,应跳过
mockMvc.perform(post("/api/v1/user/synchronizationStudentInfoByAuto")
.contentType(org.springframework.http.MediaType.APPLICATION_JSON).content(BODY))
.andExpect(status().isOk())
.andExpect(content().string(containsString("账号已全部存在")));
Integer count = jdbc.queryForObject(
"SELECT COUNT(*) FROM sys_user WHERE student_id IN ('stu-sync-1','stu-sync-2')", Integer.class);
org.junit.jupiter.api.Assertions.assertEquals(2, count);
}
@Test
void syncReturnsEmptyWhenListIsEmpty() throws Exception {
mockMvc.perform(post("/api/v1/user/synchronizationStudentInfoByAuto")
.contentType(org.springframework.http.MediaType.APPLICATION_JSON).content("[]"))
.andExpect(status().isOk())
.andExpect(content().string(containsString("同步数据为空")));
}
@Test
void syncIsAnonymousAccessible() throws Exception {
// 该接口在 SecurityConfig 中 permitAll,匿名即可调用(不携带 JWT)
mockMvc.perform(post("/api/v1/user/synchronizationStudentInfoByAuto")
.contentType(org.springframework.http.MediaType.APPLICATION_JSON).content("[]"))
.andExpect(status().isOk());
}
private void clean() {
jdbc.update("DELETE FROM sys_user WHERE student_id IN ('stu-sync-1','stu-sync-2')");
}
}

@ -6,13 +6,18 @@ import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.RequestPostProcessor;
import java.math.BigDecimal;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ -86,6 +91,87 @@ class TeacherExperimentReportControllerTest {
mockMvc.perform(get("/api/v1/experiment-reports/teacher")).andExpect(status().isUnauthorized());
}
@Test
void scoresUnscoredReportAndPersistsComment() throws Exception {
String body = "{\"id\":\"r-b\",\"score\":92.50,\"comment\":\"报告结构完整,分析到位\"}";
mockMvc.perform(post("/api/v1/experiment-reports/teacher/score")
.contentType(MediaType.APPLICATION_JSON).content(body).with(teacher()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(200))
.andExpect(jsonPath("$.data.id").value("r-b"))
.andExpect(jsonPath("$.data.teacherScore").value(92.50))
.andExpect(jsonPath("$.data.teacherComment").value("报告结构完整,分析到位"));
BigDecimal dbScore = jdbc.queryForObject(
"SELECT teacher_score FROM experiment_report WHERE id='r-b'", BigDecimal.class);
String dbComment = jdbc.queryForObject(
"SELECT teacher_comment FROM experiment_report WHERE id='r-b'", String.class);
assertEquals(0, new BigDecimal("92.50").compareTo(dbScore));
assertEquals("报告结构完整,分析到位", dbComment);
}
@Test
void overwritesExistingScore() throws Exception {
// r-a 种子已带 teacher_score=85.00,评分应覆盖而非拦截
String body = "{\"id\":\"r-a\",\"score\":78.00,\"comment\":\"重评\"}";
mockMvc.perform(post("/api/v1/experiment-reports/teacher/score")
.contentType(MediaType.APPLICATION_JSON).content(body).with(teacher()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(200))
.andExpect(jsonPath("$.data.teacherScore").value(78.00))
.andExpect(jsonPath("$.data.teacherComment").value("重评"));
}
@Test
void returns404WhenReportMissing() throws Exception {
String body = "{\"id\":\"r-missing\",\"score\":90.00}";
mockMvc.perform(post("/api/v1/experiment-reports/teacher/score")
.contentType(MediaType.APPLICATION_JSON).content(body).with(teacher()))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.code").value(404));
}
@Test
void returns403WhenReportBelongsToOtherSchool() throws Exception {
jdbc.update("INSERT INTO experiment_report (id,report_name,file_url,file_size,upload_time,teacher_score,"
+ "user_id,school_id,class_id,created_at,updated_at,deleted) "
+ "VALUES ('r-x','报告X.pdf','/x.pdf',1024,CURRENT_TIMESTAMP,NULL,?,?,?,"
+ "CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,FALSE)", STUDENT_B, "9999", "2072");
String body = "{\"id\":\"r-x\",\"score\":90.00}";
mockMvc.perform(post("/api/v1/experiment-reports/teacher/score")
.contentType(MediaType.APPLICATION_JSON).content(body).with(teacher()))
.andExpect(status().isForbidden())
.andExpect(jsonPath("$.code").value(403));
}
@Test
void rejectsScoreOutOfRange() throws Exception {
String body = "{\"id\":\"r-b\",\"score\":150.00}";
mockMvc.perform(post("/api/v1/experiment-reports/teacher/score")
.contentType(MediaType.APPLICATION_JSON).content(body).with(teacher()))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.code").value(400));
}
@Test
void rejectsCommentTooLong() throws Exception {
String longComment = new String(new char[501]).replace('\0', 'x');
String body = "{\"id\":\"r-b\",\"score\":90.00,\"comment\":\"" + longComment + "\"}";
mockMvc.perform(post("/api/v1/experiment-reports/teacher/score")
.contentType(MediaType.APPLICATION_JSON).content(body).with(teacher()))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.code").value(400));
}
@Test
void rejectsBlankId() throws Exception {
String body = "{\"id\":\"\",\"score\":90.00}";
mockMvc.perform(post("/api/v1/experiment-reports/teacher/score")
.contentType(MediaType.APPLICATION_JSON).content(body).with(teacher()))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.code").value(400));
}
private RequestPostProcessor teacher() {
return jwt().jwt(token -> token.subject(TEACHER).claim("userId", TEACHER)
.claim("preferred_username", "tea-1"));

Loading…
Cancel
Save