Commit 3f40cfa8 authored by wujipeng's avatar wujipeng
Browse files

教师端-教学管理-教案管理

parent 7ada3155
package com.platform.business.model.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Date;
/** 教师端教案分页查询条件;教师 ID 由服务端单独传入 Mapper,不暴露给客户端。 */
@Data
public class TeachingPlanQueryDTO {
@ApiModelProperty("页码,默认 1")
private Integer pageNum;
@ApiModelProperty("每页数量,默认 10,最大 100")
private Integer pageSize;
@ApiModelProperty("标题或课程名称模糊查询关键字")
private String keyword;
@ApiModelProperty("ALL/DRAFT/PENDING/APPROVED/REJECTED")
private String status;
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
@ApiModelProperty("授课日期范围开始值,包含当天")
private Date startDate;
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
@ApiModelProperty("授课日期范围结束值,包含当天")
private Date endDate;
}
package com.platform.business.model.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Date;
/** 新增或编辑教案的结构化请求;状态及教师归属均不能由本请求修改。 */
@Data
public class TeachingPlanSaveDTO {
@ApiModelProperty(value = "教案标题,最多 200 个字符", required = true)
private String title;
@ApiModelProperty(value = "课程名称,最多 200 个字符", required = true)
private String courseName;
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
@ApiModelProperty(value = "授课日期", required = true)
private Date teachingDate;
@ApiModelProperty(value = "正整数课时", required = true)
private Integer classHours;
@ApiModelProperty(value = "教学目标", required = true)
private String teachingObjectives;
@ApiModelProperty(value = "教学内容", required = true)
private String teachingContent;
@ApiModelProperty(value = "教学重点", required = true)
private String keyPoints;
@ApiModelProperty(value = "教学难点", required = true)
private String difficultPoints;
@ApiModelProperty(value = "教学方法", required = true)
private String teachingMethods;
@ApiModelProperty(value = "教学过程", required = true)
private String teachingProcess;
@ApiModelProperty("课后总结,可为空")
private String afterClassSummary;
}
package com.platform.business.model.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/** 教案状态变更请求;具体可达状态由服务端状态机校验。 */
@Data
public class TeachingPlanStatusDTO {
@ApiModelProperty(value = "目标状态:DRAFT/PENDING/APPROVED/REJECTED", required = true)
private String status;
}
package com.platform.business.model.entity;
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 lombok.Data;
import java.util.Date;
/**
* 教案附件关联实体。
*
* <p>实际文件元数据保存在 {@code bs_file},本表只保存教案归属、文件 ID 和
* 上传时的文件大小,便于执行附件数量限制及数据权限校验。</p>
*/
@Data
@TableName("teaching_plan_attachment")
public class TeachingPlanAttachmentEntity {
/** 附件关联主键。 */
@TableId(value = "id", type = IdType.ASSIGN_ID)
private String id;
/** 所属教案 ID。 */
@TableField("plan_id")
private String planId;
/** 通用文件表 bs_file 的主键。 */
@TableField("file_id")
private Integer fileId;
/** 文件大小,单位为字节。 */
@TableField("file_size")
private Long fileSize;
/** 逻辑删除标记:0 正常,1 删除。 */
@TableLogic(value = "0", delval = "1")
@TableField("del_flag")
private Integer delFlag;
/** 关联创建时间。 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField(value = "create_time", fill = FieldFill.INSERT)
private Date createTime;
/** 关联更新时间。 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
}
package com.platform.business.model.entity;
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 lombok.Data;
import java.util.Date;
/**
* 教师教案主表实体。
*
* <p>教案使用教师手工录入的课程名称、授课日期和课时,不与排课表绑定;
* {@code teacherId} 始终由服务端登录态写入,客户端无权指定数据归属。</p>
*/
@Data
@TableName("teaching_plan")
public class TeachingPlanEntity {
/** 教案主键,使用 MyBatis-Plus 雪花算法生成字符串 ID。 */
@TableId(value = "id", type = IdType.ASSIGN_ID)
private String id;
/** 教案所属教师用户 ID,只能由服务端从 JWT 登录用户中取得。 */
@TableField("teacher_id")
private String teacherId;
/** 教案标题。 */
private String title;
/** 教师手工填写的课程名称,不关联 class_subject。 */
@TableField("course_name")
private String courseName;
/** 计划授课日期,仅记录日期,不记录具体排课时段。 */
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
@TableField("teaching_date")
private Date teachingDate;
/** 计划课时,必须为正整数。 */
@TableField("class_hours")
private Integer classHours;
/** 教学目标。 */
@TableField("teaching_objectives")
private String teachingObjectives;
/** 教学内容。 */
@TableField("teaching_content")
private String teachingContent;
/** 教学重点。 */
@TableField("key_points")
private String keyPoints;
/** 教学难点。 */
@TableField("difficult_points")
private String difficultPoints;
/** 教学方法。 */
@TableField("teaching_methods")
private String teachingMethods;
/** 教学过程。 */
@TableField("teaching_process")
private String teachingProcess;
/** 课后总结,可在草稿阶段留空。 */
@TableField("after_class_summary")
private String afterClassSummary;
/** 审核展示状态:DRAFT、PENDING、APPROVED、REJECTED。 */
private String status;
/** 逻辑删除标记:0 正常,1 删除。 */
@TableLogic(value = "0", delval = "1")
@TableField("del_flag")
private Integer delFlag;
/** 创建时间,由项目统一元数据处理器自动填充。 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField(value = "create_time", fill = FieldFill.INSERT)
private Date createTime;
/** 最后更新时间,由项目统一元数据处理器自动填充。 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
}
package com.platform.business.model.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
/** 教案附件展示对象,不返回服务器磁盘物理路径。 */
@Data
public class TeachingPlanAttachmentVO {
private String id;
/** 所属教案 ID;列表批量装配附件时用于分组。 */
private String planId;
private Integer fileId;
private String fileName;
private Long fileSize;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
}
package com.platform.business.model.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
import java.util.List;
/** 教案列表与详情统一返回对象,包含结构化正文和有效附件。 */
@Data
public class TeachingPlanVO {
private String id;
private String teacherId;
private String teacherName;
private String title;
private String courseName;
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date teachingDate;
private Integer classHours;
private String teachingObjectives;
private String teachingContent;
private String keyPoints;
private String difficultPoints;
private String teachingMethods;
private String teachingProcess;
private String afterClassSummary;
private String status;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
/** 当前未逻辑删除且文件仍有效的附件集合。 */
private List<TeachingPlanAttachmentVO> attachments;
}
package com.platform.business.constant;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/** 教案状态、正文及附件的统一业务边界。 */
public final class TeachingPlanConstants {
public static final String STATUS_ALL = "ALL";
public static final String STATUS_DRAFT = "DRAFT";
public static final String STATUS_PENDING = "PENDING";
public static final String STATUS_APPROVED = "APPROVED";
public static final String STATUS_REJECTED = "REJECTED";
/** 标题和课程名称对应数据库 VARCHAR(200)。 */
public static final int MAX_SHORT_TEXT_LENGTH = 200;
/** 单个结构化正文的安全上限,防止异常请求占用过多数据库空间。 */
public static final int MAX_CONTENT_LENGTH = 20000;
public static final int MAX_ATTACHMENT_COUNT = 10;
public static final long MAX_ATTACHMENT_SIZE = 50L * 1024 * 1024;
public static final Set<String> STATUSES = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
STATUS_DRAFT, STATUS_PENDING, STATUS_APPROVED, STATUS_REJECTED
)));
public static final Set<String> ATTACHMENT_EXTENSIONS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
"pdf", "doc", "docx", "ppt", "pptx"
)));
private TeachingPlanConstants() {
}
/**
* 判断状态流转是否合法。状态机只允许草稿提交、待审核通过或驳回、驳回退回草稿。
*/
public static boolean canTransition(String currentStatus, String targetStatus) {
if (STATUS_DRAFT.equals(currentStatus)) {
return STATUS_PENDING.equals(targetStatus);
}
if (STATUS_PENDING.equals(currentStatus)) {
return STATUS_APPROVED.equals(targetStatus) || STATUS_REJECTED.equals(targetStatus);
}
return STATUS_REJECTED.equals(currentStatus) && STATUS_DRAFT.equals(targetStatus);
}
}
package com.platform.business.controller;
import com.platform.business.model.dto.TeachingPlanQueryDTO;
import com.platform.business.model.dto.TeachingPlanSaveDTO;
import com.platform.business.model.dto.TeachingPlanStatusDTO;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.TeachingPlanAttachmentVO;
import com.platform.business.model.vo.TeachingPlanVO;
import com.platform.business.service.AuthenticatedUserService;
import com.platform.business.service.TeachingPlanService;
import com.platform.controller.BaseController;
import com.platform.model.resp.Result;
import com.platform.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
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 org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* 教师端“教学管理-教案管理”接口。
*
* <p>控制器不会接收 teacherId。每次请求都从 Authorization 令牌取得当前用户并校验
* “教师”角色,随后只把可信的用户 ID 交给服务层进行二次数据归属校验。</p>
*/
@Api(tags = "教师端-教案管理")
@RestController
@RequestMapping("/teaching/plan/teacher")
public class TeachingPlanController extends BaseController {
@Resource
private TeachingPlanService teachingPlanService;
@Resource
private AuthenticatedUserService authenticatedUserService;
@ApiOperation("分页查询当前教师的教案")
@PostMapping("/page")
public TableDataInfo page(@RequestBody(required = false) TeachingPlanQueryDTO query,
HttpServletRequest request) {
TeachingPlanQueryDTO safeQuery = query == null ? new TeachingPlanQueryDTO() : query;
normalizePage(safeQuery);
UserEntity teacher = currentTeacher(request);
startPage(safeQuery.getPageNum(), safeQuery.getPageSize());
return getDataTable(teachingPlanService.list(safeQuery, teacher.getId()));
}
@ApiOperation("查看当前教师的教案详情")
@GetMapping("/{id}")
public Result<TeachingPlanVO> detail(@PathVariable String id, HttpServletRequest request) {
return Result.data(teachingPlanService.detail(id, currentTeacher(request).getId()));
}
@ApiOperation("新增当前教师的教案草稿")
@PostMapping
public Result<TeachingPlanVO> create(@RequestBody TeachingPlanSaveDTO body,
HttpServletRequest request) {
return Result.data(teachingPlanService.create(body, currentTeacher(request).getId()));
}
@ApiOperation("编辑当前教师的教案草稿")
@PutMapping("/{id}")
public Result<TeachingPlanVO> update(@PathVariable String id,
@RequestBody TeachingPlanSaveDTO body,
HttpServletRequest request) {
return Result.data(teachingPlanService.update(id, body, currentTeacher(request).getId()));
}
@ApiOperation("逻辑删除当前教师的教案草稿")
@DeleteMapping("/{id}")
public Result<Boolean> delete(@PathVariable String id, HttpServletRequest request) {
return Result.data(teachingPlanService.delete(id, currentTeacher(request).getId()));
}
@ApiOperation("按标准状态机修改当前教师的教案状态")
@PutMapping("/{id}/status")
public Result<TeachingPlanVO> updateStatus(@PathVariable String id,
@RequestBody TeachingPlanStatusDTO body,
HttpServletRequest request) {
return Result.data(teachingPlanService.updateStatus(id, body, currentTeacher(request).getId()));
}
@ApiOperation("为当前教师的教案草稿批量上传附件")
@PostMapping("/{id}/attachments")
public Result<List<TeachingPlanAttachmentVO>> uploadAttachments(
@PathVariable String id,
@RequestParam("files") List<MultipartFile> files,
HttpServletRequest request) {
return Result.data(teachingPlanService.uploadAttachments(
id, files, currentTeacher(request).getId()));
}
@ApiOperation("删除当前教师的教案草稿附件")
@DeleteMapping("/{id}/attachments/{attachmentId}")
public Result<Boolean> deleteAttachment(@PathVariable String id,
@PathVariable String attachmentId,
HttpServletRequest request) {
return Result.data(teachingPlanService.deleteAttachment(
id, attachmentId, currentTeacher(request).getId()));
}
@ApiOperation("下载当前教师有权访问的教案附件")
@GetMapping("/{id}/attachments/{attachmentId}/download")
public void downloadAttachment(@PathVariable String id,
@PathVariable String attachmentId,
HttpServletRequest request) {
teachingPlanService.downloadAttachment(id, attachmentId, currentTeacher(request).getId());
}
/** 统一分页默认值并限制单次最大查询量。 */
void normalizePage(TeachingPlanQueryDTO query) {
int pageNum = query.getPageNum() == null || query.getPageNum() < 1 ? 1 : query.getPageNum();
int pageSize = query.getPageSize() == null || query.getPageSize() < 1 ? 10 : query.getPageSize();
query.setPageNum(pageNum);
query.setPageSize(Math.min(pageSize, 100));
}
/** 解析登录用户并校验教师角色,避免普通用户直接调用教师端路由。 */
private UserEntity currentTeacher(HttpServletRequest request) {
UserEntity user = authenticatedUserService.current(request);
authenticatedUserService.requireTeacher(user);
return user;
}
}
package com.platform.business.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.platform.business.model.entity.TeachingPlanAttachmentEntity;
import com.platform.business.model.vo.TeachingPlanAttachmentVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/** 教案附件关系数据访问接口。 */
@Mapper
public interface TeachingPlanAttachmentMapper extends BaseMapper<TeachingPlanAttachmentEntity> {
/** 批量查询多个教案的有效附件,用于避免列表逐条查询产生 N+1 问题。 */
List<TeachingPlanAttachmentVO> selectByPlanIds(@Param("planIds") List<String> planIds);
/** 查询单个有效附件关系;教案归属由调用方先行校验。 */
TeachingPlanAttachmentEntity selectActive(@Param("planId") String planId,
@Param("attachmentId") String attachmentId);
/** 统计教案当前有效附件数量。 */
int countActive(@Param("planId") String planId);
/** 查询教案全部有效文件 ID,用于删除教案时同步逻辑删除文件元数据。 */
List<Integer> selectFileIds(@Param("planId") String planId);
/** 逻辑删除单个有效附件关系。 */
int deleteActive(@Param("planId") String planId,
@Param("attachmentId") String attachmentId);
/** 逻辑删除指定教案下的全部附件关系。 */
int deleteByPlanId(@Param("planId") String planId);
}
package com.platform.business.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.platform.business.model.dto.TeachingPlanQueryDTO;
import com.platform.business.model.entity.TeachingPlanEntity;
import com.platform.business.model.vo.TeachingPlanVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/** 教案主表数据访问接口,所有自定义查询均显式带入当前教师 ID。 */
@Mapper
public interface TeachingPlanMapper extends BaseMapper<TeachingPlanEntity> {
/** 查询当前教师自己的教案列表,分页由 Controller 中的 PageHelper 提供。 */
List<TeachingPlanVO> selectTeacherList(@Param("teacherId") String teacherId,
@Param("query") TeachingPlanQueryDTO query);
/** 查询当前教师自己的单条教案详情,不满足归属条件时返回 null。 */
TeachingPlanVO selectTeacherDetail(@Param("id") String id,
@Param("teacherId") String teacherId);
/**
* 上传附件前锁定教案主记录,使同一教案的并发批量上传串行执行,
* 从而确保“最多 10 个附件”的计数限制不会被并发请求绕过。
*/
TeachingPlanEntity selectTeacherPlanForUpdate(@Param("id") String id,
@Param("teacherId") String teacherId);
/** 仅更新仍属于当前教师且仍为草稿的教案正文。 */
int updateDraft(@Param("plan") TeachingPlanEntity plan,
@Param("teacherId") String teacherId);
/** 按预期原状态更新目标状态,实现并发安全的状态机。 */
int updateStatus(@Param("id") String id,
@Param("teacherId") String teacherId,
@Param("currentStatus") String currentStatus,
@Param("targetStatus") String targetStatus);
/** 仅逻辑删除仍属于当前教师且仍为草稿的教案。 */
int deleteDraft(@Param("id") String id,
@Param("teacherId") String teacherId);
}
package com.platform.business.service;
import com.platform.business.model.dto.TeachingPlanQueryDTO;
import com.platform.business.model.dto.TeachingPlanSaveDTO;
import com.platform.business.model.dto.TeachingPlanStatusDTO;
import com.platform.business.model.vo.TeachingPlanAttachmentVO;
import com.platform.business.model.vo.TeachingPlanVO;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
/** 教师端教案管理业务接口。所有方法都要求显式传入服务端解析出的当前教师 ID。 */
public interface TeachingPlanService {
List<TeachingPlanVO> list(TeachingPlanQueryDTO query, String teacherId);
TeachingPlanVO detail(String id, String teacherId);
TeachingPlanVO create(TeachingPlanSaveDTO request, String teacherId);
TeachingPlanVO update(String id, TeachingPlanSaveDTO request, String teacherId);
boolean delete(String id, String teacherId);
TeachingPlanVO updateStatus(String id, TeachingPlanStatusDTO request, String teacherId);
List<TeachingPlanAttachmentVO> uploadAttachments(String id, List<MultipartFile> files,
String teacherId);
boolean deleteAttachment(String id, String attachmentId, String teacherId);
void downloadAttachment(String id, String attachmentId, String teacherId);
}
package com.platform.business.service.impl;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.platform.business.constant.TeachingPlanConstants;
import com.platform.business.mapper.TeachingPlanAttachmentMapper;
import com.platform.business.mapper.TeachingPlanMapper;
import com.platform.business.model.dto.TeachingPlanQueryDTO;
import com.platform.business.model.dto.TeachingPlanSaveDTO;
import com.platform.business.model.dto.TeachingPlanStatusDTO;
import com.platform.business.model.entity.BsFileEntity;
import com.platform.business.model.entity.TeachingPlanAttachmentEntity;
import com.platform.business.model.entity.TeachingPlanEntity;
import com.platform.business.model.vo.TeachingPlanAttachmentVO;
import com.platform.business.model.vo.TeachingPlanVO;
import com.platform.business.service.BsFileService;
import com.platform.business.service.TeachingPlanService;
import com.platform.exception.BusinessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* 教师端教案管理核心业务实现。
*
* <p>服务层不信任客户端提交的数据归属:每个入口都使用 JWT 解析得到的教师 ID,
* 并在查询或更新 SQL 中再次携带该 ID。正文、附件和状态各自还有独立的状态限制,
* 防止通过绕过前端按钮修改其他教师数据或已锁定教案。</p>
*/
@Service
public class TeachingPlanServiceImpl implements TeachingPlanService {
@Resource
private TeachingPlanMapper teachingPlanMapper;
@Resource
private TeachingPlanAttachmentMapper attachmentMapper;
@Resource
private BsFileService bsFileService;
@Override
public List<TeachingPlanVO> list(TeachingPlanQueryDTO query, String teacherId) {
requireTeacherId(teacherId);
TeachingPlanQueryDTO safeQuery = query == null ? new TeachingPlanQueryDTO() : query;
normalizeQuery(safeQuery);
List<TeachingPlanVO> plans = teachingPlanMapper.selectTeacherList(teacherId, safeQuery);
fillAttachments(plans);
return plans;
}
@Override
public TeachingPlanVO detail(String id, String teacherId) {
requireId(id, "教案ID不能为空");
requireTeacherId(teacherId);
TeachingPlanVO plan = teachingPlanMapper.selectTeacherDetail(id, teacherId);
if (plan == null) {
// 对不存在和无权限使用同一提示,避免通过接口枚举其他教师的教案 ID。
throw new BusinessException("教案不存在或无权访问");
}
fillAttachments(Collections.singletonList(plan));
return plan;
}
@Override
@Transactional(rollbackFor = Exception.class)
public TeachingPlanVO create(TeachingPlanSaveDTO request, String teacherId) {
requireTeacherId(teacherId);
validateAndNormalizeSaveRequest(request);
TeachingPlanEntity plan = toEntity(request);
plan.setId(IdWorker.getIdStr());
plan.setTeacherId(teacherId);
// 新建教案只能从草稿开始,客户端无法跳过正文校验直接创建已审核数据。
plan.setStatus(TeachingPlanConstants.STATUS_DRAFT);
plan.setDelFlag(0);
if (teachingPlanMapper.insert(plan) != 1) {
throw new BusinessException("教案创建失败");
}
return detail(plan.getId(), teacherId);
}
@Override
@Transactional(rollbackFor = Exception.class)
public TeachingPlanVO update(String id, TeachingPlanSaveDTO request, String teacherId) {
requireId(id, "教案ID不能为空");
requireTeacherId(teacherId);
validateAndNormalizeSaveRequest(request);
TeachingPlanEntity current = requireOwnedPlan(id, teacherId);
requireDraft(current, "只有草稿状态的教案可以编辑");
TeachingPlanEntity update = toEntity(request);
update.setId(id);
// SQL 同时限制 teacher_id、DRAFT 和 del_flag,处理校验后发生的并发状态变化。
if (teachingPlanMapper.updateDraft(update, teacherId) != 1) {
throw new BusinessException("教案状态已变化,请刷新后重试");
}
return detail(id, teacherId);
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean delete(String id, String teacherId) {
requireId(id, "教案ID不能为空");
requireTeacherId(teacherId);
// 锁定主记录,使删除不会与同一教案的附件上传、删除或状态变更交叉执行。
TeachingPlanEntity plan = lockOwnedPlan(id, teacherId);
requireDraft(plan, "只有草稿状态的教案可以删除");
List<Integer> fileIds = attachmentMapper.selectFileIds(id);
if (teachingPlanMapper.deleteDraft(id, teacherId) != 1) {
throw new BusinessException("教案状态已变化,请刷新后重试");
}
attachmentMapper.deleteByPlanId(id);
// 与项目现有文件删除策略保持一致:只逻辑删除 bs_file,磁盘物理文件继续保留。
for (Integer fileId : fileIds) {
BsFileEntity file = bsFileService.getById(fileId);
if (file != null && !bsFileService.removeById(fileId)) {
throw new BusinessException("教案附件删除失败");
}
}
return true;
}
@Override
@Transactional(rollbackFor = Exception.class)
public TeachingPlanVO updateStatus(String id, TeachingPlanStatusDTO request, String teacherId) {
requireId(id, "教案ID不能为空");
requireTeacherId(teacherId);
if (request == null || !StringUtils.hasText(request.getStatus())) {
throw new BusinessException("目标状态不能为空");
}
String targetStatus = request.getStatus().trim().toUpperCase(Locale.ROOT);
if (!TeachingPlanConstants.STATUSES.contains(targetStatus)) {
throw new BusinessException("教案状态只能是 DRAFT、PENDING、APPROVED 或 REJECTED");
}
TeachingPlanEntity current = requireOwnedPlan(id, teacherId);
if (!TeachingPlanConstants.canTransition(current.getStatus(), targetStatus)) {
throw new BusinessException("不允许从 " + current.getStatus() + " 变更为 " + targetStatus);
}
// 原状态进入 WHERE 条件;两个并发状态请求最多只有一个能够成功。
if (teachingPlanMapper.updateStatus(id, teacherId, current.getStatus(), targetStatus) != 1) {
throw new BusinessException("教案状态已变化,请刷新后重试");
}
return detail(id, teacherId);
}
@Override
@Transactional(rollbackFor = Exception.class)
public List<TeachingPlanAttachmentVO> uploadAttachments(String id, List<MultipartFile> files,
String teacherId) {
requireId(id, "教案ID不能为空");
requireTeacherId(teacherId);
validateAttachmentFiles(files);
// 行锁确保并发上传请求不能同时通过附件总数检查。
TeachingPlanEntity plan = lockOwnedPlan(id, teacherId);
requireDraft(plan, "只有草稿状态的教案可以上传附件");
int existingCount = attachmentMapper.countActive(id);
if (existingCount + files.size() > TeachingPlanConstants.MAX_ATTACHMENT_COUNT) {
throw new BusinessException("每份教案最多上传10个附件");
}
List<TeachingPlanAttachmentVO> uploaded = new ArrayList<>();
for (MultipartFile file : files) {
BsFileEntity storedFile = bsFileService.uploadFile(file);
TeachingPlanAttachmentEntity attachment = new TeachingPlanAttachmentEntity();
attachment.setId(IdWorker.getIdStr());
attachment.setPlanId(id);
attachment.setFileId(storedFile.getId());
attachment.setFileSize(file.getSize());
attachment.setDelFlag(0);
attachment.setCreateTime(new Date());
attachment.setUpdateTime(attachment.getCreateTime());
if (attachmentMapper.insert(attachment) != 1) {
throw new BusinessException("教案附件关系保存失败");
}
uploaded.add(toAttachmentVO(attachment, storedFile.getFileName()));
}
return uploaded;
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean deleteAttachment(String id, String attachmentId, String teacherId) {
requireId(id, "教案ID不能为空");
requireId(attachmentId, "附件ID不能为空");
requireTeacherId(teacherId);
TeachingPlanEntity plan = lockOwnedPlan(id, teacherId);
requireDraft(plan, "只有草稿状态的教案可以删除附件");
TeachingPlanAttachmentEntity attachment = requireAttachment(id, attachmentId);
if (attachmentMapper.deleteActive(id, attachmentId) != 1) {
throw new BusinessException("附件状态已变化,请刷新后重试");
}
BsFileEntity file = bsFileService.getById(attachment.getFileId());
if (file != null && !bsFileService.removeById(attachment.getFileId())) {
throw new BusinessException("附件文件删除失败");
}
return true;
}
@Override
public void downloadAttachment(String id, String attachmentId, String teacherId) {
requireId(id, "教案ID不能为空");
requireId(attachmentId, "附件ID不能为空");
requireTeacherId(teacherId);
// 先验证教案属于当前教师,再验证附件确实属于该教案,不能只凭 fileId 下载。
requireOwnedPlan(id, teacherId);
TeachingPlanAttachmentEntity attachment = requireAttachment(id, attachmentId);
bsFileService.downloadFile(attachment.getFileId());
}
/** 将附件一次性批量装配到列表结果,避免分页结果中出现逐条查询。 */
private void fillAttachments(List<TeachingPlanVO> plans) {
if (plans == null || plans.isEmpty()) {
return;
}
List<String> planIds = new ArrayList<>();
for (TeachingPlanVO plan : plans) {
planIds.add(plan.getId());
plan.setAttachments(new ArrayList<>());
}
List<TeachingPlanAttachmentVO> attachments = attachmentMapper.selectByPlanIds(planIds);
Map<String, List<TeachingPlanAttachmentVO>> grouped = new HashMap<>();
for (TeachingPlanAttachmentVO attachment : attachments) {
grouped.computeIfAbsent(attachment.getPlanId(), key -> new ArrayList<>()).add(attachment);
}
for (TeachingPlanVO plan : plans) {
List<TeachingPlanAttachmentVO> planAttachments = grouped.get(plan.getId());
if (planAttachments != null) {
plan.setAttachments(planAttachments);
}
}
}
/** 查询有效教案并校验归属,统一返回不暴露资源存在性的错误。 */
private TeachingPlanEntity requireOwnedPlan(String id, String teacherId) {
TeachingPlanEntity plan = teachingPlanMapper.selectById(id);
if (plan == null || !teacherId.equals(plan.getTeacherId())) {
throw new BusinessException("教案不存在或无权访问");
}
return plan;
}
/** 在当前事务内锁定本人教案;返回 null 同样按无权限处理。 */
private TeachingPlanEntity lockOwnedPlan(String id, String teacherId) {
TeachingPlanEntity plan = teachingPlanMapper.selectTeacherPlanForUpdate(id, teacherId);
if (plan == null) {
throw new BusinessException("教案不存在或无权访问");
}
return plan;
}
private TeachingPlanAttachmentEntity requireAttachment(String planId, String attachmentId) {
TeachingPlanAttachmentEntity attachment = attachmentMapper.selectActive(planId, attachmentId);
if (attachment == null) {
throw new BusinessException("附件不存在或不属于当前教案");
}
return attachment;
}
private void requireDraft(TeachingPlanEntity plan, String message) {
if (!TeachingPlanConstants.STATUS_DRAFT.equals(plan.getStatus())) {
throw new BusinessException(message);
}
}
/** 规范化列表筛选值并验证日期区间。 */
private void normalizeQuery(TeachingPlanQueryDTO query) {
query.setKeyword(trimToNull(query.getKeyword()));
String status = trimToNull(query.getStatus());
status = status == null ? TeachingPlanConstants.STATUS_ALL : status.toUpperCase(Locale.ROOT);
if (!TeachingPlanConstants.STATUS_ALL.equals(status)
&& !TeachingPlanConstants.STATUSES.contains(status)) {
throw new BusinessException("筛选状态只能是 ALL、DRAFT、PENDING、APPROVED 或 REJECTED");
}
query.setStatus(status);
if (query.getStartDate() != null && query.getEndDate() != null
&& query.getStartDate().after(query.getEndDate())) {
throw new BusinessException("授课日期开始值不能晚于结束值");
}
}
/** 校验并原地清洗结构化教案字段,保证新增和编辑使用完全相同的规则。 */
private void validateAndNormalizeSaveRequest(TeachingPlanSaveDTO request) {
if (request == null) {
throw new BusinessException("教案内容不能为空");
}
request.setTitle(requireText(request.getTitle(), "教案标题",
TeachingPlanConstants.MAX_SHORT_TEXT_LENGTH));
request.setCourseName(requireText(request.getCourseName(), "课程名称",
TeachingPlanConstants.MAX_SHORT_TEXT_LENGTH));
if (request.getTeachingDate() == null) {
throw new BusinessException("授课日期不能为空");
}
if (request.getClassHours() == null || request.getClassHours() <= 0) {
throw new BusinessException("课时必须为正整数");
}
request.setTeachingObjectives(requireText(request.getTeachingObjectives(), "教学目标",
TeachingPlanConstants.MAX_CONTENT_LENGTH));
request.setTeachingContent(requireText(request.getTeachingContent(), "教学内容",
TeachingPlanConstants.MAX_CONTENT_LENGTH));
request.setKeyPoints(requireText(request.getKeyPoints(), "教学重点",
TeachingPlanConstants.MAX_CONTENT_LENGTH));
request.setDifficultPoints(requireText(request.getDifficultPoints(), "教学难点",
TeachingPlanConstants.MAX_CONTENT_LENGTH));
request.setTeachingMethods(requireText(request.getTeachingMethods(), "教学方法",
TeachingPlanConstants.MAX_CONTENT_LENGTH));
request.setTeachingProcess(requireText(request.getTeachingProcess(), "教学过程",
TeachingPlanConstants.MAX_CONTENT_LENGTH));
String summary = trimToNull(request.getAfterClassSummary());
if (summary != null && summary.length() > TeachingPlanConstants.MAX_CONTENT_LENGTH) {
throw new BusinessException("课后总结不能超过20000个字符");
}
request.setAfterClassSummary(summary);
}
/** 上传落盘前先完整校验整个批次,减少部分文件成功后才发现参数错误的情况。 */
private void validateAttachmentFiles(List<MultipartFile> files) {
if (files == null || files.isEmpty()) {
throw new BusinessException("至少需要上传一个附件");
}
if (files.size() > TeachingPlanConstants.MAX_ATTACHMENT_COUNT) {
throw new BusinessException("单次最多上传10个附件");
}
for (MultipartFile file : files) {
if (file == null || file.isEmpty()) {
throw new BusinessException("附件不能为空");
}
if (file.getSize() > TeachingPlanConstants.MAX_ATTACHMENT_SIZE) {
throw new BusinessException("单个附件不能超过50MB");
}
String extension = extension(file.getOriginalFilename());
if (!TeachingPlanConstants.ATTACHMENT_EXTENSIONS.contains(extension)) {
throw new BusinessException("附件只支持 PDF、DOC、DOCX、PPT 或 PPTX");
}
}
}
private TeachingPlanEntity toEntity(TeachingPlanSaveDTO request) {
TeachingPlanEntity plan = new TeachingPlanEntity();
plan.setTitle(request.getTitle());
plan.setCourseName(request.getCourseName());
plan.setTeachingDate(request.getTeachingDate());
plan.setClassHours(request.getClassHours());
plan.setTeachingObjectives(request.getTeachingObjectives());
plan.setTeachingContent(request.getTeachingContent());
plan.setKeyPoints(request.getKeyPoints());
plan.setDifficultPoints(request.getDifficultPoints());
plan.setTeachingMethods(request.getTeachingMethods());
plan.setTeachingProcess(request.getTeachingProcess());
plan.setAfterClassSummary(request.getAfterClassSummary());
return plan;
}
private TeachingPlanAttachmentVO toAttachmentVO(TeachingPlanAttachmentEntity attachment,
String fileName) {
TeachingPlanAttachmentVO vo = new TeachingPlanAttachmentVO();
vo.setId(attachment.getId());
vo.setPlanId(attachment.getPlanId());
vo.setFileId(attachment.getFileId());
vo.setFileName(fileName);
vo.setFileSize(attachment.getFileSize());
vo.setCreateTime(attachment.getCreateTime());
return vo;
}
private String requireText(String value, String fieldName, int maxLength) {
String normalized = trimToNull(value);
if (normalized == null) {
throw new BusinessException(fieldName + "不能为空");
}
if (normalized.length() > maxLength) {
throw new BusinessException(fieldName + "不能超过" + maxLength + "个字符");
}
return normalized;
}
private String trimToNull(String value) {
if (value == null) {
return null;
}
String trimmed = value.trim();
return trimmed.isEmpty() ? null : trimmed;
}
private String extension(String filename) {
if (!StringUtils.hasText(filename)) {
return "";
}
String normalized = filename.trim();
int dot = normalized.lastIndexOf('.');
if (dot < 0 || dot == normalized.length() - 1) {
return "";
}
return normalized.substring(dot + 1).toLowerCase(Locale.ROOT);
}
private void requireTeacherId(String teacherId) {
if (!StringUtils.hasText(teacherId)) {
throw new BusinessException("无法获取当前教师身份");
}
}
private void requireId(String id, String message) {
if (!StringUtils.hasText(id)) {
throw new BusinessException(message);
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.platform.business.mapper.TeachingPlanAttachmentMapper">
<!-- 只返回有效关系及有效文件,且刻意不查询 bs_file.url,避免泄露磁盘路径。 -->
<select id="selectByPlanIds" resultType="com.platform.business.model.vo.TeachingPlanAttachmentVO">
SELECT
a.id,
a.plan_id AS planId,
a.file_id AS fileId,
f.file_name AS fileName,
a.file_size AS fileSize,
a.create_time AS createTime
FROM teaching_plan_attachment a
INNER JOIN bs_file f ON f.id = a.file_id AND f.del_flag = 0
WHERE a.del_flag = 0
AND a.plan_id IN
<foreach collection="planIds" item="planId" open="(" separator="," close=")">
#{planId}
</foreach>
ORDER BY a.create_time ASC, a.id ASC
</select>
<select id="selectActive" resultType="com.platform.business.model.entity.TeachingPlanAttachmentEntity">
SELECT *
FROM teaching_plan_attachment
WHERE id = #{attachmentId}
AND plan_id = #{planId}
AND del_flag = 0
</select>
<select id="countActive" resultType="java.lang.Integer">
SELECT COUNT(1)
FROM teaching_plan_attachment
WHERE plan_id = #{planId}
AND del_flag = 0
</select>
<select id="selectFileIds" resultType="java.lang.Integer">
SELECT file_id
FROM teaching_plan_attachment
WHERE plan_id = #{planId}
AND del_flag = 0
</select>
<update id="deleteActive">
UPDATE teaching_plan_attachment
SET del_flag = 1,
update_time = CURRENT_TIMESTAMP
WHERE id = #{attachmentId}
AND plan_id = #{planId}
AND del_flag = 0
</update>
<update id="deleteByPlanId">
UPDATE teaching_plan_attachment
SET del_flag = 1,
update_time = CURRENT_TIMESTAMP
WHERE plan_id = #{planId}
AND del_flag = 0
</update>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.platform.business.mapper.TeachingPlanMapper">
<!-- 教案列表与详情共用字段;教师姓名实时关联 user 表,不在教案表内保存冗余快照。 -->
<sql id="planColumns">
p.id,
p.teacher_id AS teacherId,
u.nick_name AS teacherName,
p.title,
p.course_name AS courseName,
p.teaching_date AS teachingDate,
p.class_hours AS classHours,
p.teaching_objectives AS teachingObjectives,
p.teaching_content AS teachingContent,
p.key_points AS keyPoints,
p.difficult_points AS difficultPoints,
p.teaching_methods AS teachingMethods,
p.teaching_process AS teachingProcess,
p.after_class_summary AS afterClassSummary,
p.status,
p.create_time AS createTime,
p.update_time AS updateTime
</sql>
<select id="selectTeacherList" resultType="com.platform.business.model.vo.TeachingPlanVO">
SELECT <include refid="planColumns"/>
FROM teaching_plan p
LEFT JOIN user u ON u.id = p.teacher_id
WHERE p.teacher_id = #{teacherId}
AND p.del_flag = 0
<if test="query.keyword != null and query.keyword != ''">
AND (p.title LIKE CONCAT('%', #{query.keyword}, '%')
OR p.course_name LIKE CONCAT('%', #{query.keyword}, '%'))
</if>
<if test="query.status != null and query.status != '' and query.status != 'ALL'">
AND p.status = #{query.status}
</if>
<if test="query.startDate != null">
AND p.teaching_date <![CDATA[>=]]> #{query.startDate}
</if>
<if test="query.endDate != null">
AND p.teaching_date <![CDATA[<=]]> #{query.endDate}
</if>
ORDER BY p.update_time DESC, p.id DESC
</select>
<select id="selectTeacherDetail" resultType="com.platform.business.model.vo.TeachingPlanVO">
SELECT <include refid="planColumns"/>
FROM teaching_plan p
LEFT JOIN user u ON u.id = p.teacher_id
WHERE p.id = #{id}
AND p.teacher_id = #{teacherId}
AND p.del_flag = 0
</select>
<!-- 行锁仅在事务中使用,用于串行化同一教案的附件数量检查和状态变化。 -->
<select id="selectTeacherPlanForUpdate"
resultType="com.platform.business.model.entity.TeachingPlanEntity">
SELECT *
FROM teaching_plan
WHERE id = #{id}
AND teacher_id = #{teacherId}
AND del_flag = 0
FOR UPDATE
</select>
<!-- WHERE 中再次限制 DRAFT,避免校验后状态被另一请求修改造成越权更新。 -->
<update id="updateDraft">
UPDATE teaching_plan
SET title = #{plan.title},
course_name = #{plan.courseName},
teaching_date = #{plan.teachingDate},
class_hours = #{plan.classHours},
teaching_objectives = #{plan.teachingObjectives},
teaching_content = #{plan.teachingContent},
key_points = #{plan.keyPoints},
difficult_points = #{plan.difficultPoints},
teaching_methods = #{plan.teachingMethods},
teaching_process = #{plan.teachingProcess},
after_class_summary = #{plan.afterClassSummary},
update_time = CURRENT_TIMESTAMP
WHERE id = #{plan.id}
AND teacher_id = #{teacherId}
AND status = 'DRAFT'
AND del_flag = 0
</update>
<!-- 原状态和目标状态同时入参,服务层校验状态机后由该条件更新保证并发安全。 -->
<update id="updateStatus">
UPDATE teaching_plan
SET status = #{targetStatus},
update_time = CURRENT_TIMESTAMP
WHERE id = #{id}
AND teacher_id = #{teacherId}
AND status = #{currentStatus}
AND del_flag = 0
</update>
<update id="deleteDraft">
UPDATE teaching_plan
SET del_flag = 1,
update_time = CURRENT_TIMESTAMP
WHERE id = #{id}
AND teacher_id = #{teacherId}
AND status = 'DRAFT'
AND del_flag = 0
</update>
</mapper>
-- 教师端“教学管理-教案管理”表结构(MySQL 5.7+/8.0)。
--
-- 脚本使用 IF NOT EXISTS,可在不同环境重复执行。项目采用逻辑删除,因此不配置级联外键;
-- 业务服务会在同一事务内维护教案、附件关系和 bs_file 文件元数据的一致性。
CREATE TABLE IF NOT EXISTS teaching_plan (
id VARCHAR(32) NOT NULL COMMENT '教案ID',
teacher_id VARCHAR(64) NOT NULL COMMENT '所属教师用户ID',
title VARCHAR(200) NOT NULL COMMENT '教案标题',
course_name VARCHAR(200) NOT NULL COMMENT '手工填写的课程名称',
teaching_date DATE NOT NULL COMMENT '授课日期',
class_hours INT NOT NULL COMMENT '正整数课时',
teaching_objectives MEDIUMTEXT NOT NULL COMMENT '教学目标',
teaching_content MEDIUMTEXT NOT NULL COMMENT '教学内容',
key_points MEDIUMTEXT NOT NULL COMMENT '教学重点',
difficult_points MEDIUMTEXT NOT NULL COMMENT '教学难点',
teaching_methods MEDIUMTEXT NOT NULL COMMENT '教学方法',
teaching_process MEDIUMTEXT NOT NULL COMMENT '教学过程',
after_class_summary MEDIUMTEXT NULL COMMENT '课后总结',
status VARCHAR(16) NOT NULL DEFAULT 'DRAFT' COMMENT 'DRAFT/PENDING/APPROVED/REJECTED',
del_flag TINYINT NOT NULL DEFAULT 0 COMMENT '逻辑删除:0正常,1删除',
create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (id),
KEY idx_teaching_plan_teacher_status (teacher_id, del_flag, status),
KEY idx_teaching_plan_teacher_date (teacher_id, del_flag, teaching_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='教师教案';
CREATE TABLE IF NOT EXISTS teaching_plan_attachment (
id VARCHAR(32) NOT NULL COMMENT '附件关联ID',
plan_id VARCHAR(32) NOT NULL COMMENT '教案ID',
file_id INT NOT NULL COMMENT 'bs_file文件ID',
file_size BIGINT NOT NULL COMMENT '文件大小(字节)',
del_flag TINYINT NOT NULL DEFAULT 0 COMMENT '逻辑删除:0正常,1删除',
create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (id),
UNIQUE KEY uk_teaching_plan_file (plan_id, file_id),
KEY idx_teaching_plan_attachment_plan (plan_id, del_flag),
KEY idx_teaching_plan_attachment_file (file_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='教案附件关联';
# 教师端教案管理接口
所有接口统一使用前缀 `/teaching/plan/teacher`,并从请求头 `Authorization` 解析当前用户。
服务端要求用户具有 `phone_role.role_name=教师`,且不会接收客户端传入的 `teacherId`。
部署前执行 `src/main/resources/sql/teaching_plan.sql` 创建教案主表和附件关联表。
## 1. 分页查询教案
`POST /teaching/plan/teacher/page`
```json
{
"pageNum": 1,
"pageSize": 10,
"keyword": "高处作业",
"status": "DRAFT",
"startDate": "2026-08-01",
"endDate": "2026-08-31"
}
```
`status` 支持 `ALL`、`DRAFT`、`PENDING`、`APPROVED`、`REJECTED`。关键字同时匹配教案标题和课程名称,
日期范围包含起止日期。返回项目统一的 `TableDataInfo` 分页结构,每条教案均包含当前有效附件。
## 2. 新增、详情、编辑和删除
- `POST /teaching/plan/teacher`:新增教案,状态固定为 `DRAFT`。
- `GET /teaching/plan/teacher/{id}`:查询本人教案详情。
- `PUT /teaching/plan/teacher/{id}`:编辑本人草稿。
- `DELETE /teaching/plan/teacher/{id}`:逻辑删除本人草稿及附件关系。
新增或编辑请求示例:
```json
{
"title": "高处作业安全教案",
"courseName": "高处作业安全",
"teachingDate": "2026-08-20",
"classHours": 2,
"teachingObjectives": "掌握高处作业基本安全要求",
"teachingContent": "安全防护用品使用和风险识别",
"keyPoints": "正确使用安全带",
"difficultPoints": "复杂环境风险识别",
"teachingMethods": "讲授、演示与案例讨论",
"teachingProcess": "导入、讲授、演示、练习和总结",
"afterClassSummary": "选填的课后总结"
}
```
标题和课程名称最多 200 个字符;六个教学正文均为必填项且单项最多 20000 个字符;课时必须为正整数。
状态不是 `DRAFT` 时,编辑和删除接口都会拒绝操作。
## 3. 状态流转
`PUT /teaching/plan/teacher/{id}/status`
```json
{
"status": "PENDING"
}
```
本期状态由教案所属教师本人维护,不记录审核意见或历史。只允许以下流转:
- `DRAFT → PENDING`
- `PENDING → APPROVED`
- `PENDING → REJECTED`
- `REJECTED → DRAFT`
`APPROVED` 为终态。驳回教案必须先退回 `DRAFT`,才能继续编辑、删除或管理附件。
## 4. 附件
- `POST /teaching/plan/teacher/{id}/attachments`:使用 `multipart/form-data`,字段名为 `files`,可在一个请求中上传多个文件。
- `DELETE /teaching/plan/teacher/{id}/attachments/{attachmentId}`:删除单个草稿附件。
- `GET /teaching/plan/teacher/{id}/attachments/{attachmentId}/download`:校验教师、教案和附件关系后下载。
每份教案最多保留 10 个附件,支持 PDF、DOC、DOCX、PPT、PPTX,扩展名不区分大小写,单个附件不得超过
50 MiB。上传和删除附件仅允许在 `DRAFT` 状态执行;下载在任意有效状态均可执行。接口不返回服务器文件路径。
package com.platform.business.controller;
import com.platform.business.model.dto.TeachingPlanQueryDTO;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/** 教案控制器分页边界测试,避免无效页码或超大分页参数直接进入 PageHelper。 */
class TeachingPlanControllerTest {
private final TeachingPlanController controller = new TeachingPlanController();
@Test
void normalizePageShouldApplyDefaults() {
TeachingPlanQueryDTO query = new TeachingPlanQueryDTO();
controller.normalizePage(query);
assertEquals(1, query.getPageNum());
assertEquals(10, query.getPageSize());
}
@Test
void normalizePageShouldKeepValidPageAndCapPageSize() {
TeachingPlanQueryDTO query = new TeachingPlanQueryDTO();
query.setPageNum(3);
query.setPageSize(500);
controller.normalizePage(query);
assertEquals(3, query.getPageNum());
assertEquals(100, query.getPageSize());
}
}
package com.platform.business.service.impl;
import com.platform.business.constant.TeachingPlanConstants;
import com.platform.business.mapper.TeachingPlanAttachmentMapper;
import com.platform.business.mapper.TeachingPlanMapper;
import com.platform.business.model.dto.TeachingPlanQueryDTO;
import com.platform.business.model.dto.TeachingPlanSaveDTO;
import com.platform.business.model.dto.TeachingPlanStatusDTO;
import com.platform.business.model.entity.BsFileEntity;
import com.platform.business.model.entity.TeachingPlanAttachmentEntity;
import com.platform.business.model.entity.TeachingPlanEntity;
import com.platform.business.model.vo.TeachingPlanVO;
import com.platform.business.service.BsFileService;
import com.platform.exception.BusinessException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import java.util.Collections;
import java.util.Date;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* 教案管理核心规则单元测试。
*
* <p>测试不连接数据库和文件系统,重点验证默认数据归属、状态机、草稿写保护、
* 附件类型/大小/数量边界以及下载前的数据权限校验。</p>
*/
@ExtendWith(MockitoExtension.class)
class TeachingPlanServiceImplTest {
private static final String TEACHER_ID = "teacher-1";
@Mock
private TeachingPlanMapper teachingPlanMapper;
@Mock
private TeachingPlanAttachmentMapper attachmentMapper;
@Mock
private BsFileService bsFileService;
@InjectMocks
private TeachingPlanServiceImpl teachingPlanService;
@Test
void createShouldForceCurrentTeacherAndDraftStatus() {
when(teachingPlanMapper.insert(any(TeachingPlanEntity.class))).thenReturn(1);
when(teachingPlanMapper.selectTeacherDetail(anyString(), eq(TEACHER_ID)))
.thenAnswer(invocation -> {
TeachingPlanVO vo = new TeachingPlanVO();
vo.setId(invocation.getArgument(0));
vo.setTeacherId(TEACHER_ID);
vo.setStatus(TeachingPlanConstants.STATUS_DRAFT);
return vo;
});
when(attachmentMapper.selectByPlanIds(anyList())).thenReturn(Collections.emptyList());
TeachingPlanVO result = teachingPlanService.create(validRequest(), TEACHER_ID);
ArgumentCaptor<TeachingPlanEntity> captor = ArgumentCaptor.forClass(TeachingPlanEntity.class);
verify(teachingPlanMapper).insert(captor.capture());
assertEquals(TEACHER_ID, captor.getValue().getTeacherId());
assertEquals(TeachingPlanConstants.STATUS_DRAFT, captor.getValue().getStatus());
assertNotNull(captor.getValue().getId());
assertEquals(TeachingPlanConstants.STATUS_DRAFT, result.getStatus());
}
@Test
void createShouldRejectMissingRequiredContent() {
TeachingPlanSaveDTO request = validRequest();
request.setTeachingObjectives(" ");
assertThrows(BusinessException.class,
() -> teachingPlanService.create(request, TEACHER_ID));
verify(teachingPlanMapper, never()).insert(any());
}
@Test
void listShouldNormalizeKeywordAndStatus() {
when(teachingPlanMapper.selectTeacherList(eq(TEACHER_ID), any()))
.thenReturn(Collections.emptyList());
TeachingPlanQueryDTO query = new TeachingPlanQueryDTO();
query.setKeyword(" 安全课 ");
query.setStatus("pending");
teachingPlanService.list(query, TEACHER_ID);
assertEquals("安全课", query.getKeyword());
assertEquals(TeachingPlanConstants.STATUS_PENDING, query.getStatus());
}
@Test
void listShouldRejectInvalidStatusAndDateRange() {
TeachingPlanQueryDTO invalidStatus = new TeachingPlanQueryDTO();
invalidStatus.setStatus("UNKNOWN");
assertThrows(BusinessException.class,
() -> teachingPlanService.list(invalidStatus, TEACHER_ID));
TeachingPlanQueryDTO invalidDates = new TeachingPlanQueryDTO();
invalidDates.setStartDate(new Date(2_000L));
invalidDates.setEndDate(new Date(1_000L));
assertThrows(BusinessException.class,
() -> teachingPlanService.list(invalidDates, TEACHER_ID));
verify(teachingPlanMapper, never()).selectTeacherList(anyString(), any());
}
@Test
void updateShouldRejectAnotherTeachersPlan() {
TeachingPlanEntity foreignPlan = plan(TeachingPlanConstants.STATUS_DRAFT);
foreignPlan.setTeacherId("teacher-2");
when(teachingPlanMapper.selectById("plan-1")).thenReturn(foreignPlan);
assertThrows(BusinessException.class,
() -> teachingPlanService.update("plan-1", validRequest(), TEACHER_ID));
verify(teachingPlanMapper, never()).updateDraft(any(), anyString());
}
@Test
void updateAndDeleteShouldRejectNonDraftPlan() {
TeachingPlanEntity pending = plan(TeachingPlanConstants.STATUS_PENDING);
when(teachingPlanMapper.selectById("plan-1")).thenReturn(pending);
assertThrows(BusinessException.class,
() -> teachingPlanService.update("plan-1", validRequest(), TEACHER_ID));
when(teachingPlanMapper.selectTeacherPlanForUpdate("plan-1", TEACHER_ID))
.thenReturn(pending);
assertThrows(BusinessException.class,
() -> teachingPlanService.delete("plan-1", TEACHER_ID));
verify(teachingPlanMapper, never()).deleteDraft(anyString(), anyString());
}
@ParameterizedTest
@CsvSource({
"DRAFT,PENDING",
"PENDING,APPROVED",
"PENDING,REJECTED",
"REJECTED,DRAFT"
})
void updateStatusShouldAllowEveryDefinedTransition(String currentStatus, String targetStatus) {
when(teachingPlanMapper.selectById("plan-1")).thenReturn(plan(currentStatus));
when(teachingPlanMapper.updateStatus("plan-1", TEACHER_ID, currentStatus, targetStatus))
.thenReturn(1);
TeachingPlanVO detail = new TeachingPlanVO();
detail.setId("plan-1");
detail.setStatus(targetStatus);
when(teachingPlanMapper.selectTeacherDetail("plan-1", TEACHER_ID)).thenReturn(detail);
when(attachmentMapper.selectByPlanIds(anyList())).thenReturn(Collections.emptyList());
TeachingPlanStatusDTO request = new TeachingPlanStatusDTO();
request.setStatus(targetStatus.toLowerCase());
TeachingPlanVO result = teachingPlanService.updateStatus("plan-1", request, TEACHER_ID);
assertEquals(targetStatus, result.getStatus());
}
@Test
void approvedStatusShouldBeTerminal() {
when(teachingPlanMapper.selectById("plan-1"))
.thenReturn(plan(TeachingPlanConstants.STATUS_APPROVED));
TeachingPlanStatusDTO request = new TeachingPlanStatusDTO();
request.setStatus(TeachingPlanConstants.STATUS_DRAFT);
assertThrows(BusinessException.class,
() -> teachingPlanService.updateStatus("plan-1", request, TEACHER_ID));
verify(teachingPlanMapper, never()).updateStatus(anyString(), anyString(), anyString(), anyString());
}
@Test
void statusUpdateShouldDetectConcurrentStateChange() {
when(teachingPlanMapper.selectById("plan-1"))
.thenReturn(plan(TeachingPlanConstants.STATUS_DRAFT));
when(teachingPlanMapper.updateStatus("plan-1", TEACHER_ID,
TeachingPlanConstants.STATUS_DRAFT, TeachingPlanConstants.STATUS_PENDING))
.thenReturn(0);
TeachingPlanStatusDTO request = new TeachingPlanStatusDTO();
request.setStatus(TeachingPlanConstants.STATUS_PENDING);
assertThrows(BusinessException.class,
() -> teachingPlanService.updateStatus("plan-1", request, TEACHER_ID));
}
@Test
void uploadShouldAcceptSupportedDocumentAndCreateRelation() {
when(teachingPlanMapper.selectTeacherPlanForUpdate("plan-1", TEACHER_ID))
.thenReturn(plan(TeachingPlanConstants.STATUS_DRAFT));
when(attachmentMapper.countActive("plan-1")).thenReturn(0);
BsFileEntity storedFile = BsFileEntity.builder()
.id(100)
.fileName("LESSON.DOCX")
.delFlag(0)
.build();
when(bsFileService.uploadFile(any())).thenReturn(storedFile);
when(attachmentMapper.insert(any())).thenReturn(1);
MockMultipartFile file = new MockMultipartFile(
"files", "LESSON.DOCX", "application/octet-stream", new byte[]{1, 2});
assertEquals(1, teachingPlanService.uploadAttachments(
"plan-1", Collections.singletonList(file), TEACHER_ID).size());
verify(attachmentMapper).insert(any(TeachingPlanAttachmentEntity.class));
}
@Test
void uploadShouldRejectInvalidExtensionAndOversizeFileBeforeStorage() {
MockMultipartFile invalidType = new MockMultipartFile(
"files", "lesson.exe", "application/octet-stream", new byte[]{1});
assertThrows(BusinessException.class, () -> teachingPlanService.uploadAttachments(
"plan-1", Collections.singletonList(invalidType), TEACHER_ID));
MultipartFile oversized = mock(MultipartFile.class);
when(oversized.isEmpty()).thenReturn(false);
when(oversized.getSize()).thenReturn(TeachingPlanConstants.MAX_ATTACHMENT_SIZE + 1);
assertThrows(BusinessException.class, () -> teachingPlanService.uploadAttachments(
"plan-1", Collections.singletonList(oversized), TEACHER_ID));
verify(bsFileService, never()).uploadFile(any());
}
@Test
void uploadShouldEnforceMaximumTotalAttachmentCount() {
when(teachingPlanMapper.selectTeacherPlanForUpdate("plan-1", TEACHER_ID))
.thenReturn(plan(TeachingPlanConstants.STATUS_DRAFT));
when(attachmentMapper.countActive("plan-1")).thenReturn(10);
MockMultipartFile file = new MockMultipartFile(
"files", "lesson.pdf", "application/pdf", new byte[]{1});
assertThrows(BusinessException.class, () -> teachingPlanService.uploadAttachments(
"plan-1", Collections.singletonList(file), TEACHER_ID));
verify(bsFileService, never()).uploadFile(any());
}
@Test
void downloadShouldRejectForeignPlanBeforeLookingUpAttachment() {
TeachingPlanEntity foreignPlan = plan(TeachingPlanConstants.STATUS_DRAFT);
foreignPlan.setTeacherId("teacher-2");
when(teachingPlanMapper.selectById("plan-1")).thenReturn(foreignPlan);
assertThrows(BusinessException.class, () -> teachingPlanService.downloadAttachment(
"plan-1", "attachment-1", TEACHER_ID));
verify(attachmentMapper, never()).selectActive(anyString(), anyString());
verify(bsFileService, never()).downloadFile(any());
}
@Test
void downloadShouldStreamFileAfterOwnershipAndRelationChecks() {
when(teachingPlanMapper.selectById("plan-1"))
.thenReturn(plan(TeachingPlanConstants.STATUS_APPROVED));
TeachingPlanAttachmentEntity attachment = new TeachingPlanAttachmentEntity();
attachment.setId("attachment-1");
attachment.setPlanId("plan-1");
attachment.setFileId(100);
when(attachmentMapper.selectActive("plan-1", "attachment-1")).thenReturn(attachment);
teachingPlanService.downloadAttachment("plan-1", "attachment-1", TEACHER_ID);
verify(bsFileService).downloadFile(100);
}
@Test
void statusTransitionMatrixShouldContainOnlyFourAllowedEdges() {
String[] statuses = {
TeachingPlanConstants.STATUS_DRAFT,
TeachingPlanConstants.STATUS_PENDING,
TeachingPlanConstants.STATUS_APPROVED,
TeachingPlanConstants.STATUS_REJECTED
};
int allowed = 0;
for (String from : statuses) {
for (String to : statuses) {
if (TeachingPlanConstants.canTransition(from, to)) {
allowed++;
}
}
}
assertEquals(4, allowed);
assertTrue(TeachingPlanConstants.canTransition("REJECTED", "DRAFT"));
assertFalse(TeachingPlanConstants.canTransition("APPROVED", "DRAFT"));
}
private TeachingPlanEntity plan(String status) {
TeachingPlanEntity plan = new TeachingPlanEntity();
plan.setId("plan-1");
plan.setTeacherId(TEACHER_ID);
plan.setStatus(status);
plan.setDelFlag(0);
return plan;
}
private TeachingPlanSaveDTO validRequest() {
TeachingPlanSaveDTO request = new TeachingPlanSaveDTO();
request.setTitle("高处作业安全教案");
request.setCourseName("高处作业安全");
request.setTeachingDate(new Date());
request.setClassHours(2);
request.setTeachingObjectives("掌握高处作业基本安全要求");
request.setTeachingContent("安全防护用品使用和风险识别");
request.setKeyPoints("正确使用安全带");
request.setDifficultPoints("复杂环境风险识别");
request.setTeachingMethods("讲授、演示与案例讨论");
request.setTeachingProcess("导入、讲授、演示、练习和总结");
request.setAfterClassSummary("课堂目标已完成");
return request;
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment