fix: validate default task keys and tighten class task publication

main
chenyuan 1 month ago
parent a392ebdad4
commit 2950728cbe

@ -0,0 +1,100 @@
-- Reconcile verified legacy default catalogs; based on the 2026-10-16 migrations.
-- Scope: platform/school defaults only. Teaching-class publications and student answers are excluded.
-- Apply through database_migrate.py, which creates a backup, verifies results, and controls the transaction.
START TRANSACTION;
DELETE FROM task_allocation WHERE class_id='SCHOOL_DEFAULT:100';
INSERT INTO task_allocation (id,class_id,school_id,module,disabled_status,sort)
SELECT UUID(),'SCHOOL_DEFAULT:100','100',task_key,CASE WHEN task_key IN ('new-product-survey','product-development-factors','product-development-process') THEN 0 ELSE 1 END,sort
FROM training_task WHERE enabled=1;
DELETE FROM task_allocation WHERE class_id='SCHOOL_DEFAULT:1005';
INSERT INTO task_allocation (id,class_id,school_id,module,disabled_status,sort)
SELECT UUID(),'SCHOOL_DEFAULT:1005','1005',task_key,CASE WHEN task_key IN ('new-product-survey','product-development-factors','product-development-process') THEN 0 ELSE 1 END,sort
FROM training_task WHERE enabled=1;
DELETE FROM task_allocation WHERE class_id='SCHOOL_DEFAULT:1016';
INSERT INTO task_allocation (id,class_id,school_id,module,disabled_status,sort)
SELECT UUID(),'SCHOOL_DEFAULT:1016','1016',task_key,CASE WHEN task_key IN ('new-product-survey','product-development-factors','product-development-process') THEN 0 ELSE 1 END,sort
FROM training_task WHERE enabled=1;
DELETE FROM task_allocation WHERE class_id='SCHOOL_DEFAULT:1017';
INSERT INTO task_allocation (id,class_id,school_id,module,disabled_status,sort)
SELECT UUID(),'SCHOOL_DEFAULT:1017','1017',task_key,CASE WHEN task_key IN ('new-product-survey','product-development-factors','product-development-process') THEN 0 ELSE 1 END,sort
FROM training_task WHERE enabled=1;
DELETE FROM task_allocation WHERE class_id='SCHOOL_DEFAULT:151';
INSERT INTO task_allocation (id,class_id,school_id,module,disabled_status,sort)
SELECT UUID(),'SCHOOL_DEFAULT:151','151',task_key,CASE WHEN task_key IN ('new-product-survey','product-development-factors','product-development-process') THEN 0 ELSE 1 END,sort
FROM training_task WHERE enabled=1;
DELETE FROM task_allocation WHERE class_id='SCHOOL_DEFAULT:232';
INSERT INTO task_allocation (id,class_id,school_id,module,disabled_status,sort)
SELECT UUID(),'SCHOOL_DEFAULT:232','232',task_key,CASE WHEN task_key IN ('new-product-survey','product-development-factors','product-development-process') THEN 0 ELSE 1 END,sort
FROM training_task WHERE enabled=1;
DELETE FROM task_allocation WHERE class_id='SCHOOL_DEFAULT:266';
INSERT INTO task_allocation (id,class_id,school_id,module,disabled_status,sort)
SELECT UUID(),'SCHOOL_DEFAULT:266','266',task_key,CASE WHEN task_key IN ('new-product-survey','product-development-factors','product-development-process') THEN 0 ELSE 1 END,sort
FROM training_task WHERE enabled=1;
DELETE FROM task_allocation WHERE class_id='SCHOOL_DEFAULT:87';
INSERT INTO task_allocation (id,class_id,school_id,module,disabled_status,sort)
SELECT UUID(),'SCHOOL_DEFAULT:87','87',task_key,CASE WHEN task_key IN ('new-product-survey','product-development-factors','product-development-process') THEN 0 ELSE 1 END,sort
FROM training_task WHERE enabled=1;
DELETE FROM task_allocation WHERE class_id='SCHOOL_DEFAULT:959';
INSERT INTO task_allocation (id,class_id,school_id,module,disabled_status,sort)
SELECT UUID(),'SCHOOL_DEFAULT:959','959',task_key,CASE WHEN task_key IN ('new-product-survey','product-development-factors','product-development-process') THEN 0 ELSE 1 END,sort
FROM training_task WHERE enabled=1;
DELETE FROM task_allocation WHERE class_id='SCHOOL_DEFAULT:978';
INSERT INTO task_allocation (id,class_id,school_id,module,disabled_status,sort)
SELECT UUID(),'SCHOOL_DEFAULT:978','978',task_key,CASE WHEN task_key IN ('new-product-survey','product-development-factors','product-development-process') THEN 0 ELSE 1 END,sort
FROM training_task WHERE enabled=1;
DELETE FROM task_allocation WHERE class_id='SCHOOL_DEFAULT:979';
INSERT INTO task_allocation (id,class_id,school_id,module,disabled_status,sort)
SELECT UUID(),'SCHOOL_DEFAULT:979','979',task_key,CASE WHEN task_key IN ('new-product-survey','product-development-factors','product-development-process') THEN 0 ELSE 1 END,sort
FROM training_task WHERE enabled=1;
DELETE FROM task_allocation WHERE class_id='SCHOOL_DEFAULT:982';
INSERT INTO task_allocation (id,class_id,school_id,module,disabled_status,sort)
SELECT UUID(),'SCHOOL_DEFAULT:982','982',task_key,CASE WHEN task_key IN ('new-product-survey','product-development-factors','product-development-process') THEN 0 ELSE 1 END,sort
FROM training_task WHERE enabled=1;
DELETE FROM task_allocation WHERE class_id='SCHOOL_DEFAULT:984';
INSERT INTO task_allocation (id,class_id,school_id,module,disabled_status,sort)
SELECT UUID(),'SCHOOL_DEFAULT:984','984',task_key,CASE WHEN task_key IN ('new-product-survey','product-development-factors','product-development-process') THEN 0 ELSE 1 END,sort
FROM training_task WHERE enabled=1;
DELETE FROM task_allocation WHERE class_id='SCHOOL_DEFAULT:987';
INSERT INTO task_allocation (id,class_id,school_id,module,disabled_status,sort)
SELECT UUID(),'SCHOOL_DEFAULT:987','987',task_key,CASE WHEN task_key IN ('new-product-survey','product-development-factors','product-development-process') THEN 0 ELSE 1 END,sort
FROM training_task WHERE enabled=1;
DELETE FROM task_allocation WHERE class_id='SCHOOL_DEFAULT:994';
INSERT INTO task_allocation (id,class_id,school_id,module,disabled_status,sort)
SELECT UUID(),'SCHOOL_DEFAULT:994','994',task_key,CASE WHEN task_key IN ('new-product-survey','product-development-factors','product-development-process') THEN 0 ELSE 1 END,sort
FROM training_task WHERE enabled=1;
UPDATE task_allocation
SET disabled_status=CASE WHEN module IN ('new-product-survey','product-development-factors','product-development-process') THEN 0 ELSE 1 END
WHERE (class_id='999999999' OR class_id LIKE 'SCHOOL_DEFAULT:%') AND module<>'__TEACHING_CLASS_TASK_PUBLICATION__';
COMMIT;

@ -17,6 +17,7 @@ import com.sztzjy.linkCommerce.service.TrainingTaskService;
import com.sztzjy.linkCommerce.util.ResultEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.annotation.Transactional;
@ -93,16 +94,19 @@ public class TaskAllocationController {
@PostMapping("/selectTaskAllocationByStudentUserId")
@ApiOperation("学生端-根据当前教学班查询任务分配")
@AnonymousAccess
public ResultEntity<List<TaskAllocation>> selectTaskAllocationByStudentUserId(@RequestParam String userId,
public ResultEntity<List<TaskAllocation>> selectTaskAllocationByStudentUserId(@RequestParam(required = false) String userId,
HttpServletRequest request) {
JwtUser currentUser = currentStudent(request);
if (currentUser != null && studentTeachingClassResolver != null) {
return selectTaskAllocationByClassId(studentTeachingClassResolver.resolveRequired(currentUser));
if (currentUser == null) {
return new ResultEntity<>(HttpStatus.FORBIDDEN, "仅学生可查询本人任务分配");
}
String currentStudentId = currentUser.getUserId();
TeachingClassStudent member = teachingClassStudentMapper == null
? null
: teachingClassStudentMapper.selectActiveByStudentUserId(userId);
? null : teachingClassStudentMapper.selectActiveByStudentUserId(currentStudentId);
if (studentTeachingClassResolver != null) {
String teachingClassId = studentTeachingClassResolver.resolveRequired(currentUser);
return selectTaskAllocationByClassId(teachingClassId);
}
if (member == null || member.getTeachingClassId() == null) {
return new ResultEntity<>(HttpStatus.OK, "当前学生未分配在读教学班", Collections.emptyList());
}
@ -120,20 +124,22 @@ public class TaskAllocationController {
@PostMapping("/updateTaskAllocationByClassId")
@ApiOperation("编辑任务分配")
@AnonymousAccess
@Transactional
public ResultEntity updateTaskAllocationByClassId(@RequestBody List<TaskAllocation> taskAllocationList,
@RequestParam String classId,
@RequestParam String schoolId,
@RequestParam(required = false) String userId) {
@RequestParam(required = false) String schoolId,
@RequestParam(required = false) String userId,
HttpServletRequest request) {
if ("999999999".equals(schoolId) || "999999999".equals(classId)) {
return new ResultEntity<>(HttpStatus.BAD_REQUEST, "超管数据无法修改");
}
JwtUser operator = TokenProvider.getJWTUser(request);
SchoolClass schoolClass = schoolClassMapper.selectByPrimaryKey(classId);
if (schoolClass == null
|| userId == null
if (operator == null || operator.getRoleId() != 3
|| schoolClass == null
|| !"TEACHING".equals(schoolClass.getClassType())
|| !userId.equals(schoolClass.getCreatedBy())) {
|| !StringUtils.equals(operator.getUserId(), schoolClass.getCreatedBy())
|| !StringUtils.equals(operator.getSchoolId(), schoolClass.getSchoolId())) {
return new ResultEntity<>(HttpStatus.BAD_REQUEST, "只能分配自己创建教学班的任务");
}
if (taskAllocationList == null) {

@ -22,6 +22,7 @@ import com.sztzjy.linkCommerce.service.ImportService;
import com.sztzjy.linkCommerce.service.SchoolService;
import com.sztzjy.linkCommerce.service.StudentTeachingClassResolver;
import com.sztzjy.linkCommerce.service.SchoolProductConfigService;
import com.sztzjy.linkCommerce.service.TrainingTaskService;
import com.sztzjy.linkCommerce.service.UserInfoService;
import com.sztzjy.linkCommerce.service.ValidateService;
import com.sztzjy.linkCommerce.util.*;
@ -72,6 +73,10 @@ public class UserController {
ImportService importService;
@Autowired(required = false)
StudentTeachingClassResolver studentTeachingClassResolver;
@Autowired(required = false)
TaskAllocationMapper taskAllocationMapper;
@Autowired(required = false)
TrainingTaskService trainingTaskService;
@PostMapping("/addSchool")
@ -376,6 +381,7 @@ public class UserController {
@PostMapping("/addSchoolClass")
@ApiOperation("班级管理-添加班级")
@AnonymousAccess
@Transactional(rollbackFor = Exception.class)
public ResultEntity addSchoolClass(@ApiParam("学校ID") @RequestParam String schoolId,
@ApiParam("院系ID") @RequestParam(required = false) String schoolFacultyId,
@ApiParam("专业ID") @RequestParam(required = false) String schoolMajorId,
@ -440,6 +446,7 @@ public class UserController {
int insert = schoolClassMapper.insert(schoolClass);
if (insert == 1) {
initializeTeachingClassTaskAllocation(schoolClass);
createTeachingClassMembersFromSourceClasses(schoolClass);
return new ResultEntity<>(HttpStatus.OK, "新增班级成功");
} else {
@ -1427,6 +1434,7 @@ public class UserController {
@PostMapping("/uploadTeachingClassByStudentMembers")
@ApiOperation("教学班-导入名单创建教学班")
@AnonymousAccess
@Transactional(rollbackFor = Exception.class)
public ResultEntity uploadTeachingClassByStudentMembers(@RequestParam MultipartFile file,
@RequestParam String schoolId,
@RequestParam String schoolFacultyId,
@ -1588,12 +1596,59 @@ public class UserController {
return new ResultEntity<>(HttpStatus.BAD_REQUEST, "新增班级失败");
}
initializeTeachingClassTaskAllocation(teachingClass);
for (Userinfo student : importedStudents) {
upsertActiveTeachingClassMember(teachingClass.getSchoolClassId(), student, student.getSchoolClassId(), "IMPORT_CREATE");
}
return new ResultEntity<>(HttpStatus.OK, "导入创建教学班成功");
}
/**
* 新建教学班时落库发布配置,默认只开放第一个项目的前三个实训。
* 任务分配是教学班维度的数据,不能依赖学生端读取时的临时兜底。
*/
private void initializeTeachingClassTaskAllocation(SchoolClass teachingClass) {
if (taskAllocationMapper == null || teachingClass == null
|| !"TEACHING".equals(teachingClass.getClassType())
|| StringUtils.isBlank(teachingClass.getSchoolClassId())) {
return;
}
Set<String> defaultTaskKeys = trainingTaskService == null
? Collections.emptySet() : trainingTaskService.getDefaultPublishedTaskKeys();
if (defaultTaskKeys == null || defaultTaskKeys.isEmpty()) {
return;
}
TaskAllocationExample existingExample = new TaskAllocationExample();
existingExample.createCriteria().andClassIdEqualTo(teachingClass.getSchoolClassId());
if (taskAllocationMapper.countByExample(existingExample) > 0) {
return;
}
TaskAllocation marker = new TaskAllocation();
marker.setId(UUID.randomUUID().toString());
marker.setClassId(teachingClass.getSchoolClassId());
marker.setSchoolId(teachingClass.getSchoolId());
marker.setModule(TaskAllocation.PUBLICATION_MARKER);
marker.setDisabledStatus((byte) 1);
marker.setSort(0);
taskAllocationMapper.insert(marker);
int sort = 1;
for (String taskKey : defaultTaskKeys) {
if (StringUtils.isBlank(taskKey)) {
continue;
}
TaskAllocation allocation = new TaskAllocation();
allocation.setId(UUID.randomUUID().toString());
allocation.setClassId(teachingClass.getSchoolClassId());
allocation.setSchoolId(teachingClass.getSchoolId());
allocation.setModule(taskKey);
allocation.setDisabledStatus((byte) 0);
allocation.setSort(sort++);
taskAllocationMapper.insert(allocation);
}
}
//微信绑定*****
//导入 ***** 创建资金账户
@PostMapping("/uploadStudentUserInfo")
@ -2321,9 +2376,10 @@ public class UserController {
if (isPlatformAdmin(operator)) {
return true;
}
// 教师维护教学班名单模式只限制行政组织结构和名单维护方,
// 不应阻止同校管理型教师维护教师账号。
return isTeacherAdmin(operator)
&& StringUtils.equals(operator.getSchoolId(), schoolId)
&& !isTeacherRosterMode(schoolId);
&& StringUtils.equals(operator.getSchoolId(), schoolId);
}
private boolean canManageFaculty(String operatorId, String schoolId) {

@ -4,6 +4,7 @@ import com.sztzjy.linkCommerce.entity.SchoolClass;
import com.sztzjy.linkCommerce.entity.SchoolDefaultTaskInitialization;
import com.sztzjy.linkCommerce.entity.TaskAllocation;
import com.sztzjy.linkCommerce.entity.TaskAllocationExample;
import com.sztzjy.linkCommerce.entity.TrainingTask;
import com.sztzjy.linkCommerce.mapper.SchoolClassMapper;
import com.sztzjy.linkCommerce.mapper.SchoolDefaultTaskInitializationMapper;
import com.sztzjy.linkCommerce.mapper.TaskAllocationMapper;
@ -14,9 +15,12 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
@ -31,7 +35,7 @@ public class SchoolDefaultTaskServiceImpl implements SchoolDefaultTaskService {
SchoolClassMapper schoolClassMapper;
@Autowired(required = false)
SchoolDefaultTaskInitializationMapper initializationMapper;
@Autowired(required = false)
@Autowired
TrainingTaskService trainingTaskService;
@Autowired(required = false)
@Qualifier("asyncTaskExecutor")
@ -95,15 +99,19 @@ public class SchoolDefaultTaskServiceImpl implements SchoolDefaultTaskService {
}
@Override
@Transactional(rollbackFor = Exception.class)
public void replaceSchoolDefault(String schoolId, List<TaskAllocation> tasks) {
if (StringUtils.isBlank(schoolId)) {
throw new IllegalArgumentException("学校不能为空");
}
// Validate the complete request before deleting anything: an old browser tab
// may still submit display names from before the task-key migration.
List<TaskAllocation> validated = validateTaskKeys(tasks);
String classId = schoolDefaultClassId(schoolId);
TaskAllocationExample example = new TaskAllocationExample();
example.createCriteria().andClassIdEqualTo(classId);
taskAllocationMapper.deleteByExample(example);
for (TaskAllocation task : tasks == null ? Collections.<TaskAllocation>emptyList() : tasks) {
for (TaskAllocation task : validated) {
task.setId(UUID.randomUUID().toString());
task.setClassId(classId);
task.setSchoolId(schoolId);
@ -113,28 +121,55 @@ public class SchoolDefaultTaskServiceImpl implements SchoolDefaultTaskService {
@Override
public void initializeSchoolDefault(String schoolId) {
if (StringUtils.isBlank(schoolId) || hasSchoolDefault(schoolId)) {
if (StringUtils.isBlank(schoolId)) {
markReady(schoolId);
return;
}
List<TaskAllocation> existing = getSchoolDefault(schoolId);
if (!existing.isEmpty()) {
validateTaskKeys(existing);
markReady(schoolId);
return;
}
List<TaskAllocation> platformTasks = listByClassId(PLATFORM_DEFAULT_CLASS_ID);
List<TaskAllocation> platformTasks = validateTaskKeys(listByClassId(PLATFORM_DEFAULT_CLASS_ID));
if (platformTasks.isEmpty()) {
throw new IllegalStateException("平台基线实训任务为空");
}
Set<String> defaultOpenTaskKeys = defaultOpenTaskKeys();
for (TaskAllocation source : platformTasks) {
TaskAllocation copy = new TaskAllocation();
for (TaskAllocation copy : platformTasks) {
copy.setId(UUID.randomUUID().toString());
copy.setClassId(schoolDefaultClassId(schoolId));
copy.setSchoolId(schoolId);
copy.setModule(source.getModule());
copy.setDisabledStatus(resolveInitialDisabledStatus(source, defaultOpenTaskKeys));
copy.setSort(source.getSort());
copy.setDisabledStatus(resolveInitialDisabledStatus(copy, defaultOpenTaskKeys));
taskAllocationMapper.insert(copy);
}
markReady(schoolId);
}
private List<TaskAllocation> validateTaskKeys(List<TaskAllocation> tasks) {
Set<String> validKeys = new HashSet<>();
for (TrainingTask task : trainingTaskService.listDefaults(null, null, false)) {
validKeys.add(task.getTaskKey());
}
List<TaskAllocation> validated = new ArrayList<>();
for (TaskAllocation task : tasks == null ? Collections.<TaskAllocation>emptyList() : tasks) {
String taskKey = task == null ? "" : StringUtils.trimToEmpty(task.getModule());
// Publication markers describe teaching-class state, not default tasks.
if (TaskAllocation.PUBLICATION_MARKER.equals(taskKey)) {
continue;
}
if (StringUtils.isBlank(taskKey) || !validKeys.contains(taskKey)) {
throw new IllegalArgumentException("默认实训任务标识无效,请刷新页面;旧任务数据需先完成任务标识迁移");
}
TaskAllocation copy = new TaskAllocation();
copy.setModule(taskKey);
copy.setDisabledStatus(task.getDisabledStatus());
copy.setSort(task.getSort());
validated.add(copy);
}
return validated;
}
/**
* 学校默认任务只默认开放第一个项目的前三个任务(与教学班未配置时的学生端一致),
* 其余任务保留完整目录但置为停用,学校管理员可在默认实训任务配置页手动放开。
@ -147,9 +182,7 @@ public class SchoolDefaultTaskServiceImpl implements SchoolDefaultTaskService {
}
private Set<String> defaultOpenTaskKeys() {
return trainingTaskService == null
? Collections.emptySet()
: trainingTaskService.getDefaultPublishedTaskKeys();
return trainingTaskService.getDefaultPublishedTaskKeys();
}
private void initializeInBackground(String schoolId) {
@ -161,12 +194,6 @@ public class SchoolDefaultTaskServiceImpl implements SchoolDefaultTaskService {
}
}
private boolean hasSchoolDefault(String schoolId) {
TaskAllocationExample example = new TaskAllocationExample();
example.createCriteria().andClassIdEqualTo(schoolDefaultClassId(schoolId));
return taskAllocationMapper.countByExample(example) > 0;
}
private List<TaskAllocation> listByClassId(String classId) {
if (taskAllocationMapper == null || StringUtils.isBlank(classId)) {
return Collections.emptyList();

@ -14,6 +14,7 @@ import com.sztzjy.linkCommerce.mapper.TrainingTaskClassConfigMapper;
import com.sztzjy.linkCommerce.mapper.TrainingTaskMapper;
import com.sztzjy.linkCommerce.service.StudentTrainingAnswerService;
import com.sztzjy.linkCommerce.service.TrainingKnowledgeService;
import com.sztzjy.linkCommerce.service.TrainingTaskService;
import com.sztzjy.linkCommerce.training.knowledge.EffectiveTrainingTaskContent;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
@ -41,6 +42,9 @@ public class StudentTrainingAnswerServiceImpl implements StudentTrainingAnswerSe
@Autowired
public TrainingTaskMapper trainingTaskMapper;
@Autowired
public TrainingTaskService trainingTaskService;
@Autowired
public TeachingClassStudentMapper teachingClassStudentMapper;
@ -65,7 +69,7 @@ public class StudentTrainingAnswerServiceImpl implements StudentTrainingAnswerSe
ensureStudentTrainingAnswerTable();
requireStudent(user);
requireNotDemo(user);
TrainingTask task = resolveTask(taskKey);
TrainingTask task = resolveTask(taskKey, user);
String resolvedTeachingClassId = resolveTeachingClassId(user.getUserId(), teachingClassId);
return studentTrainingAnswerMapper.selectByStudentClassAndTask(
user.getUserId(), resolvedTeachingClassId, task.getId());
@ -77,7 +81,7 @@ public class StudentTrainingAnswerServiceImpl implements StudentTrainingAnswerSe
ensureStudentTrainingAnswerTable();
requireStudent(user);
requireNotDemo(user);
TrainingTask task = resolveTask(taskKey);
TrainingTask task = resolveTask(taskKey, user);
String resolvedTeachingClassId = resolveTeachingClassId(user.getUserId(),
answer == null ? null : answer.getTeachingClassId());
StudentTrainingAnswer existing = studentTrainingAnswerMapper.selectByStudentClassAndTask(
@ -124,7 +128,7 @@ public class StudentTrainingAnswerServiceImpl implements StudentTrainingAnswerSe
ensureStudentTrainingAnswerTable();
requireStudent(user);
requireNotDemo(user);
TrainingTask task = resolveTask(taskKey);
TrainingTask task = resolveTask(taskKey, user);
String resolvedTeachingClassId = resolveTeachingClassId(user.getUserId(), teachingClassId);
studentTrainingAnswerMapper.deleteByStudentClassAndTask(user.getUserId(), resolvedTeachingClassId, task.getId());
if (jdbcTemplate != null) {
@ -144,14 +148,14 @@ public class StudentTrainingAnswerServiceImpl implements StudentTrainingAnswerSe
}
}
private TrainingTask resolveTask(String taskKey) {
private TrainingTask resolveTask(String taskKey, JwtUser user) {
String normalizedTaskKey = StringUtils.trimToEmpty(taskKey);
if (StringUtils.isBlank(normalizedTaskKey)) {
throw new ServiceException(HttpStatus.BAD_REQUEST, "Training task key is required");
}
TrainingTask task = trainingTaskMapper.selectByTaskKey(normalizedTaskKey);
TrainingTask task = trainingTaskService.getStudentTaskByTaskKey(normalizedTaskKey, user);
if (task == null) {
throw new ServiceException(HttpStatus.BAD_REQUEST, "Training task does not exist");
throw new ServiceException(HttpStatus.FORBIDDEN, "该实训任务暂未对当前教学班开放");
}
return task;
}

@ -262,8 +262,6 @@ public class TrainingTaskServiceImpl implements TrainingTaskService {
requireOwnedTeachingClass(teachingClassId, operatorId);
ensureDefaultTasks(null);
String normalizedTaskKey = StringUtils.trimToEmpty(taskKey);
List<TrainingTask> defaults = trainingTaskMapper.selectList(null, null, null);
ensureClassTasksInitialized(teachingClassId, defaults, operatorId);
TrainingTask defaultTask = trainingTaskMapper.selectByTaskKey(normalizedTaskKey);
TrainingTaskClassConfig classTask = trainingTaskClassConfigMapper.selectByTeachingClassAndTaskKey(teachingClassId, normalizedTaskKey);
if (classTask != null) {
@ -281,7 +279,6 @@ public class TrainingTaskServiceImpl implements TrainingTaskService {
TrainingTask builtInTask = requireBuiltInTask(normalizedTaskKey);
TrainingTask defaultTask = trainingTaskMapper.selectByTaskKey(normalizedTaskKey);
TrainingTask baseTask = defaultTask == null ? builtInTask : defaultTask;
ensureClassTasksInitialized(teachingClassId, trainingTaskMapper.selectList(null, null, null), operatorId);
if (task == null) {
throw new IllegalArgumentException("Training task cannot be null");
}
@ -327,15 +324,26 @@ public class TrainingTaskServiceImpl implements TrainingTaskService {
requireOwnedTeachingClass(teachingClassId, operatorId);
ensureDefaultTasks(null);
String normalizedTaskKey = StringUtils.trimToEmpty(taskKey);
ensureClassTasksInitialized(teachingClassId, trainingTaskMapper.selectList(null, null, null), operatorId);
TrainingTaskClassConfig config = trainingTaskClassConfigMapper
.selectByTeachingClassAndTaskKey(teachingClassId, normalizedTaskKey);
if (config == null) {
throw new IllegalArgumentException("Training task not found");
TrainingTask defaultTask = trainingTaskMapper.selectByTaskKey(normalizedTaskKey);
if (defaultTask == null) {
throw new IllegalArgumentException("Training task not found");
}
config = toConfig(teachingClassId, defaultTask, operatorId);
config.setId(UUID.randomUUID().toString());
config.setCreateTime(new Date());
}
config.setReferenceAnswerEnabled(Boolean.TRUE.equals(enabled));
config.setUpdateTime(new Date());
trainingTaskClassConfigMapper.updateByPrimaryKeySelective(config);
if (StringUtils.isBlank(config.getId())) {
trainingTaskClassConfigMapper.insertSelective(config);
} else if (trainingTaskClassConfigMapper.selectByPrimaryKey(config.getId()) == null) {
trainingTaskClassConfigMapper.insertSelective(config);
} else {
trainingTaskClassConfigMapper.updateByPrimaryKeySelective(config);
}
TrainingTaskClassConfig saved = trainingTaskClassConfigMapper.selectByPrimaryKey(config.getId());
return toTask(saved == null ? config : saved);
}
@ -494,6 +502,7 @@ public class TrainingTaskServiceImpl implements TrainingTaskService {
@Override
public Set<String> getDefaultPublishedTaskKeys() {
ensureDefaultTasks(null);
List<TrainingTask> defaults = sortTasks(trainingTaskMapper.selectList(null, null, null));
Set<String> taskKeys = new LinkedHashSet<>();
if (defaults == null) {
@ -581,45 +590,6 @@ public class TrainingTaskServiceImpl implements TrainingTaskService {
return membership == null ? null : membership.getTeachingClassId();
}
private List<TrainingTaskClassConfig> ensureClassTasksInitialized(String teachingClassId, List<TrainingTask> defaults, String operatorId) {
if (StringUtils.isBlank(teachingClassId) || trainingTaskClassConfigMapper == null) {
return new ArrayList<>();
}
ensureTrainingTaskClassConfigTable();
List<TrainingTask> sourceTasks = defaults == null || defaults.isEmpty() ? defaultTasks() : defaults;
List<TrainingTaskClassConfig> existing = trainingTaskClassConfigMapper.selectListByTeachingClass(teachingClassId, null);
Map<String, TrainingTaskClassConfig> existingByKey = new LinkedHashMap<>();
if (existing != null) {
for (TrainingTaskClassConfig config : existing) {
if (config != null && StringUtils.isNotBlank(config.getTaskKey())) {
existingByKey.put(config.getTaskKey(), config);
}
}
}
String creator = resolveClassTaskCreator(teachingClassId, operatorId);
boolean inserted = false;
for (TrainingTask task : sourceTasks) {
if (task == null || StringUtils.isBlank(task.getTaskKey()) || existingByKey.containsKey(task.getTaskKey())) {
continue;
}
TrainingTaskClassConfig config = toConfig(teachingClassId, task, creator);
Date now = new Date();
config.setId(UUID.randomUUID().toString());
config.setCreateTime(now);
config.setUpdateTime(now);
trainingTaskClassConfigMapper.insertSelective(config);
existingByKey.put(config.getTaskKey(), config);
inserted = true;
}
if (inserted) {
List<TrainingTaskClassConfig> refreshed = trainingTaskClassConfigMapper.selectListByTeachingClass(teachingClassId, null);
if (refreshed != null) {
return refreshed;
}
}
return new ArrayList<>(existingByKey.values());
}
private void synchronizeClassTaskDefaults(TrainingTask previousTask, TrainingTask updatedTask) {
if (schoolClassMapper == null || trainingTaskClassConfigMapper == null
|| previousTask == null || updatedTask == null) {
@ -727,17 +697,6 @@ public class TrainingTaskServiceImpl implements TrainingTaskService {
&& !StringUtils.equals(StringUtils.defaultString(previousDefaultValue), StringUtils.defaultString(updatedDefaultValue));
}
private String resolveClassTaskCreator(String teachingClassId, String operatorId) {
if (StringUtils.isNotBlank(operatorId)) {
return operatorId;
}
if (schoolClassMapper == null) {
return null;
}
SchoolClass schoolClass = schoolClassMapper.selectByPrimaryKey(StringUtils.trimToEmpty(teachingClassId));
return schoolClass == null ? null : schoolClass.getCreatedBy();
}
private List<TrainingTask> toTasks(List<TrainingTaskClassConfig> configs) {
if (configs == null) {
return new ArrayList<>();
@ -843,6 +802,7 @@ public class TrainingTaskServiceImpl implements TrainingTaskService {
config.setAiManualUrl(task.getAiManualUrl());
config.setReferenceAnswerName(task.getReferenceAnswerName());
config.setReferenceAnswerUrl(task.getReferenceAnswerUrl());
config.setReferenceAnswerEnabled(task.getReferenceAnswerEnabled());
config.setSort(task.getSort());
config.setEnabled(task.getEnabled());
config.setCreatedBy(operatorId);

@ -2,6 +2,7 @@ package com.sztzjy.linkCommerce.service.impl;
import com.sztzjy.linkCommerce.entity.SchoolClass;
import com.sztzjy.linkCommerce.entity.TaskAllocation;
import com.sztzjy.linkCommerce.entity.TrainingTask;
import com.sztzjy.linkCommerce.mapper.SchoolClassMapper;
import com.sztzjy.linkCommerce.mapper.SchoolDefaultTaskInitializationMapper;
import com.sztzjy.linkCommerce.mapper.TaskAllocationMapper;
@ -18,11 +19,95 @@ import java.util.List;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
class SchoolDefaultTaskServiceImplTest {
@Test
void savingStaleChineseNamesRejectsEntireBatchBeforeDeletingExistingDefaults() {
TaskAllocationMapper mapper = mock(TaskAllocationMapper.class);
SchoolDefaultTaskServiceImpl service = serviceWithCatalog(mapper, "new-product-survey");
assertThrows(IllegalArgumentException.class, () -> service.replaceSchoolDefault("school-1",
Arrays.asList(task("new-product-survey"), task("新产品调查与分析"))));
verifyNoInteractions(mapper);
}
@Test
void savingUnknownEnglishKeyRejectsEntireBatchBeforeDeletingExistingDefaults() {
TaskAllocationMapper mapper = mock(TaskAllocationMapper.class);
SchoolDefaultTaskServiceImpl service = serviceWithCatalog(mapper, "new-product-survey");
assertThrows(IllegalArgumentException.class, () -> service.replaceSchoolDefault("school-1",
Collections.singletonList(task("unknown-task"))));
verifyNoInteractions(mapper);
}
@Test
void savingValidKeysKeepsSelectionAndNormalizesKeysWithoutStoringPublicationMarker() {
TaskAllocationMapper mapper = mock(TaskAllocationMapper.class);
SchoolDefaultTaskServiceImpl service = serviceWithCatalog(mapper,
"new-product-survey", "product-development-factors");
TaskAllocation disabled = baselineTask("product-development-factors", (byte) 1);
disabled.setSort(2);
service.replaceSchoolDefault("school-1", Arrays.asList(
task(" new-product-survey "), disabled, task(TaskAllocation.PUBLICATION_MARKER)));
ArgumentCaptor<TaskAllocation> saved = ArgumentCaptor.forClass(TaskAllocation.class);
verify(mapper).deleteByExample(any());
verify(mapper, times(2)).insert(saved.capture());
assertEquals("new-product-survey", saved.getAllValues().get(0).getModule());
assertEquals("product-development-factors", saved.getAllValues().get(1).getModule());
assertEquals((byte) 1, saved.getAllValues().get(1).getDisabledStatus());
assertEquals(2, saved.getAllValues().get(1).getSort());
assertEquals("SCHOOL_DEFAULT:school-1", saved.getAllValues().get(0).getClassId());
assertEquals("school-1", saved.getAllValues().get(0).getSchoolId());
}
@Test
void initializationRejectsInvalidPlatformKeysBeforeCopyingAnyTasks() {
TaskAllocationMapper mapper = mock(TaskAllocationMapper.class);
SchoolDefaultTaskServiceImpl service = serviceWithCatalog(mapper, "new-product-survey");
when(mapper.selectByExample(any())).thenReturn(Collections.emptyList(),
Arrays.asList(task("new-product-survey"), task("旧中文任务名称")));
assertThrows(IllegalArgumentException.class, () -> service.initializeSchoolDefault("school-1"));
verify(mapper, never()).insert(any());
}
@Test
void initializationRejectsInvalidExistingSchoolDefaultsInsteadOfMarkingReady() {
TaskAllocationMapper mapper = mock(TaskAllocationMapper.class);
SchoolDefaultTaskServiceImpl service = serviceWithCatalog(mapper, "new-product-survey");
SchoolDefaultTaskInitializationMapper statuses = mock(SchoolDefaultTaskInitializationMapper.class);
service.initializationMapper = statuses;
when(mapper.selectByExample(any())).thenReturn(Collections.singletonList(task("旧中文任务名称")));
assertThrows(IllegalArgumentException.class, () -> service.initializeSchoolDefault("school-1"));
verify(mapper, never()).insert(any());
verifyNoInteractions(statuses);
}
private SchoolDefaultTaskServiceImpl serviceWithCatalog(TaskAllocationMapper mapper, String... keys) {
SchoolDefaultTaskServiceImpl service = new SchoolDefaultTaskServiceImpl();
service.taskAllocationMapper = mapper;
service.trainingTaskService = mock(TrainingTaskService.class);
List<TrainingTask> catalog = Arrays.stream(keys).map(key -> {
TrainingTask task = new TrainingTask();
task.setTaskKey(key);
return task;
}).collect(java.util.stream.Collectors.toList());
when(service.trainingTaskService.listDefaults(null, null, false)).thenReturn(catalog);
return service;
}
@Test
void resolvesSchoolDefaultBeforePlatformDefaultWhenTeachingClassHasNoConfiguration() {
TaskAllocationMapper taskMapper = mock(TaskAllocationMapper.class);
@ -48,9 +133,8 @@ class SchoolDefaultTaskServiceImplTest {
@Test
void initializationDoesNotOverwriteExistingSchoolDefaultTasks() {
TaskAllocationMapper taskMapper = mock(TaskAllocationMapper.class);
SchoolDefaultTaskServiceImpl service = new SchoolDefaultTaskServiceImpl();
ReflectionTestUtils.setField(service, "taskAllocationMapper", taskMapper);
when(taskMapper.countByExample(any())).thenReturn(1L);
SchoolDefaultTaskServiceImpl service = serviceWithCatalog(taskMapper, "new-product-survey");
when(taskMapper.selectByExample(any())).thenReturn(Collections.singletonList(task("new-product-survey")));
service.initializeSchoolDefault("school-1");
@ -76,19 +160,18 @@ class SchoolDefaultTaskServiceImplTest {
@Test
void initializationOpensOnlyFirstProjectFirstThreeTasksAndDisablesRest() {
TaskAllocationMapper taskMapper = mock(TaskAllocationMapper.class);
TrainingTaskService trainingTaskService = mock(TrainingTaskService.class);
SchoolDefaultTaskServiceImpl service = new SchoolDefaultTaskServiceImpl();
ReflectionTestUtils.setField(service, "taskAllocationMapper", taskMapper);
ReflectionTestUtils.setField(service, "trainingTaskService", trainingTaskService);
SchoolDefaultTaskServiceImpl service = serviceWithCatalog(taskMapper,
"task-1", "task-2", "task-3", "task-4", "task-5", "comprehensive-case-training");
TrainingTaskService trainingTaskService = service.trainingTaskService;
when(taskMapper.countByExample(any())).thenReturn(0L);
when(taskMapper.selectByExample(any())).thenReturn(Arrays.asList(
when(taskMapper.selectByExample(any())).thenReturn(Collections.emptyList(), Arrays.asList(
baselineTask("task-1", (byte) 0),
baselineTask("task-2", (byte) 0),
baselineTask("task-3", (byte) 0),
baselineTask("task-4", (byte) 0),
baselineTask("task-5", (byte) 0),
baselineTask("comprehensive-case-training", (byte) 1)));
baselineTask("comprehensive-case-training", (byte) 1),
baselineTask(TaskAllocation.PUBLICATION_MARKER, (byte) 1)));
Set<String> defaultOpen = new LinkedHashSet<>(Arrays.asList("task-1", "task-2", "task-3"));
when(trainingTaskService.getDefaultPublishedTaskKeys()).thenReturn(defaultOpen);
@ -109,11 +192,10 @@ class SchoolDefaultTaskServiceImplTest {
@Test
void initializationFallsBackToBaselineStatusWhenDefaultOpenKeysUnavailable() {
TaskAllocationMapper taskMapper = mock(TaskAllocationMapper.class);
SchoolDefaultTaskServiceImpl service = new SchoolDefaultTaskServiceImpl();
ReflectionTestUtils.setField(service, "taskAllocationMapper", taskMapper);
SchoolDefaultTaskServiceImpl service = serviceWithCatalog(taskMapper, "task-1");
when(service.trainingTaskService.getDefaultPublishedTaskKeys()).thenReturn(Collections.emptySet());
when(taskMapper.countByExample(any())).thenReturn(0L);
when(taskMapper.selectByExample(any())).thenReturn(Collections.singletonList(
when(taskMapper.selectByExample(any())).thenReturn(Collections.emptyList(), Collections.singletonList(
baselineTask("task-1", (byte) 0)));
service.initializeSchoolDefault("school-1");

Loading…
Cancel
Save