Commit 2c66995a authored by 王蔡翾's avatar 王蔡翾
Browse files

bug修复

parent a8e84103
......@@ -37,7 +37,7 @@ public class CombinationDTO {
@ApiModelProperty("配分规则")
private List<PaperRuleEntity> paperRuleList;
@ApiModelProperty("顺序/乱序")
@ApiModelProperty("试卷生成后固定为顺序;历史乱序值会兼容转换为顺序")
private String sequence;
@ApiModelProperty("考试类型")
......
......@@ -21,7 +21,7 @@ public class TheoreticalPaperAutoSaveDTO {
@ApiModelProperty("及格分;为空时按总分的60%计算")
private Double passScore;
@ApiModelProperty("顺序/乱序;默认顺序")
@ApiModelProperty("试卷生成后固定为顺序;历史乱序值会兼容转换为顺序")
private String sequence;
@ApiModelProperty("保存状态:DRAFT/PUBLISHED,默认DRAFT")
......
......@@ -24,7 +24,7 @@ public class TheoreticalPaperManualSaveDTO {
@ApiModelProperty("及格分;为空时按总分的60%计算")
private Double passScore;
@ApiModelProperty("顺序/乱序;默认顺序")
@ApiModelProperty("试卷生成后固定为顺序;历史乱序值会兼容转换为顺序")
private String sequence;
@ApiModelProperty("保存状态:DRAFT/PUBLISHED,默认DRAFT")
......
......@@ -69,7 +69,7 @@ public class TheoreticalPaperEntity {
@TableField("create_time")
private Date createTime;
@ApiModelProperty("顺序/乱序")
@ApiModelProperty("试卷生成后的固定顺序;历史乱序值按顺序兼容")
private String sequence;
/** 状态使用稳定代码:DRAFT(草稿)、PUBLISHED(已发布)、ARCHIVED(已归档)。 */
......
......@@ -38,6 +38,6 @@ public class AttendanceCourseStatisticsVO {
private long absentCount;
/** 已批准请假人次;统计出勤率时不计为出勤。 */
private long leaveCount;
/** 出勤率百分比:正常签到/应出勤×100;迟到属于异常人次。 */
/** 出勤率百分比:(正常签到+迟到签到)/应出勤×100。 */
private BigDecimal attendanceRate;
}
......@@ -23,6 +23,6 @@ public class AttendanceStudentStatisticsVO {
private long absentCount;
/** 请假课次;计算出勤率时按未出勤处理。 */
private long leaveCount;
/** 出勤率百分比:正常签到/应出勤×100;迟到属于异常人次。 */
/** 出勤率百分比:(正常签到+迟到签到)/应出勤×100。 */
private BigDecimal attendanceRate;
}
......@@ -27,8 +27,8 @@ public class AttendanceSummaryVO {
/** 异常总人次:迟到、缺勤和请假的合计。 */
private long abnormalCount;
/**
* 班级出勤率百分比:正常签到/应出勤×100。
* 迟到、请假和缺勤均属于管理端看板展示的异常人次,不计入此分子。
* 班级出勤率百分比:实际出勤/应出勤×100。
* 实际出勤包含正常签到和迟到签到;请假和缺勤不计入分子。
*/
private BigDecimal attendanceRate;
/** 按学员汇总的统计列表。 */
......
package com.platform.business.model.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import java.math.BigDecimal;
......@@ -27,6 +28,10 @@ public class ClassAdminCourseVO {
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date lastDate;
/** 最后一节排课的实际结束时刻,仅供服务层实时计算课程状态。 */
@JsonIgnore
private Date lastEndTime;
private String status;
private String statusName;
......
package com.platform.business.model.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import java.math.BigDecimal;
......@@ -95,7 +96,10 @@ public final class StudentHomeVO {
private String subjectName;
private String teacherName;
private String location;
/** IN_PROGRESS进行中、UPCOMING即将开始、PENDING待上课。 */
/** Mapper读取的当前学员出勤状态,仅用于服务层计算最终课程状态。 */
@JsonIgnore
private String attendanceStatus;
/** LEAVE请假、IN_PROGRESS进行中、UPCOMING即将开始、PENDING待上课。 */
private String status;
}
}
......@@ -13,7 +13,8 @@ public final class TheoreticalPaperAdminConstants {
public static final String STATUS_ARCHIVED = "ARCHIVED";
public static final String SEQUENCE_ORDERED = "顺序";
public static final String SEQUENCE_RANDOM = "乱序";
/** 历史客户端可能仍提交该值,服务端仅用于兼容接收并统一转换为固定顺序。 */
public static final String LEGACY_SEQUENCE_RANDOM = "乱序";
/** 单份试卷题量上限,防止错误配置导致一次抽取、复制过多数据。 */
public static final int MAX_QUESTION_COUNT = 500;
......
......@@ -71,14 +71,26 @@ public class TheoreticalPaperController extends BaseController {
}
}
@ApiOperation("查询自动组卷规则预览;/auto为旧页面兼容路径")
@GetMapping({"/auto-configuration", "/auto"})
@ApiOperation("教师端查询自动组卷规则预览")
@GetMapping("/auto-configuration")
public Result<CombinationVO> autoConfiguration(@RequestParam("lev") String level,
HttpServletRequest request) {
UserEntity teacher = currentTeacher(request);
return Result.data(paperTeacherService.autoConfiguration(level, teacher.getId()));
}
/**
* 学员模拟考场仍通过历史GET /auto读取公共组卷配置。
* 该配置不包含教师私有数据,但调用方仍须有有效登录态;写接口继续严格限制教师角色。
*/
@ApiOperation("兼容学员模拟考场查询公共组卷配置")
@GetMapping("/auto")
public Result<CombinationVO> legacyAutoConfiguration(@RequestParam("lev") String level,
HttpServletRequest request) {
authenticatedUserService.current(request);
return Result.data(legacyPaperService.auto(level));
}
@ApiOperation("按数据库最新规则自动创建当前教师的试卷")
@PostMapping("/auto")
public Result<TheoreticalPaperVO> createAutomatic(
......
......@@ -27,7 +27,8 @@ public interface StudentHomeMapper {
List<StudentHomeVO.Score> selectRecentSimulationScores(@Param("studentId") String studentId);
List<StudentHomeVO.Course> selectCourses(@Param("classId") Integer classId,
List<StudentHomeVO.Course> selectCourses(@Param("studentId") String studentId,
@Param("classId") Integer classId,
@Param("startDate") Date startDate,
@Param("endDate") Date endDate);
}
......@@ -16,5 +16,6 @@ import java.util.List;
@Mapper
public interface TheoreticalPaperDetailMapper extends BaseMapper<TheoreticalPaperDetailEntity> {
List<TheoreticalPaperDetailEntity> selectDisorderly(@Param("paperId") String paperId);
/** 按题型分组、组内按试卷题号读取,供生成学员个人试卷使用。 */
List<TheoreticalPaperDetailEntity> selectInPaperOrder(@Param("paperId") String paperId);
}
......@@ -13,5 +13,11 @@ import java.util.List;
*/
public interface TheoreticalPaperDetailService extends IService<TheoreticalPaperDetailEntity> {
List<TheoreticalPaperDetailEntity> selectDisorderly(String paperId);
/**
* 按试卷已经确定的固定顺序读取题目。
*
* <p>随机性只用于组卷阶段从题库抽题;试卷生成后必须按题型分组,并在组内保持
* 试卷题号顺序,不能在学员开考时再次随机。</p>
*/
List<TheoreticalPaperDetailEntity> selectInPaperOrder(String paperId);
}
......@@ -176,7 +176,8 @@ public class ClassAdminServiceImpl implements ClassAdminService {
if (courses == null) {
courses = Collections.emptyList();
}
courses.forEach(course -> applyCourseStatus(course, today));
Date now = new Date();
courses.forEach(course -> applyCourseStatus(course, today, now));
detail.setCourses(courses);
detail.setCourseCount(courses.size());
......@@ -428,8 +429,15 @@ public class ClassAdminServiceImpl implements ClassAdminService {
return "信息待补全";
}
private void applyCourseStatus(ClassAdminCourseVO course, LocalDate today) {
String status = resolveClassStatus(course.getFirstDate(), course.getLastDate(), today);
private void applyCourseStatus(ClassAdminCourseVO course, LocalDate today, Date now) {
/*
* 日期状态只能判断到“天”。最后一节排课当天必须继续比较具体结束时刻,
* 当前时间到达或超过lastEndTime后立即标记已完成,不再延迟到第二天。
* 历史脏数据无法解析结束时刻时,仍回退到原有日期规则,避免详情接口失败。
*/
String status = course.getLastEndTime() != null && !now.before(course.getLastEndTime())
? ClassAdminConstants.STATUS_ENDED
: resolveClassStatus(course.getFirstDate(), course.getLastDate(), today);
course.setStatus(status);
if (ClassAdminConstants.STATUS_UPCOMING.equals(status)) course.setStatusName("未开始");
else if (ClassAdminConstants.STATUS_ONGOING.equals(status)) course.setStatusName("进行中");
......
......@@ -72,6 +72,8 @@ public class EvaluationServiceImpl implements EvaluationService {
private static final int MAX_BATCH_REVOKE_SIZE = 100;
private static final int MAX_COMMENT_LENGTH = 1000;
/** 发布通知和历史通知详情统一使用该文案,避免同一撤回状态出现两种说法。 */
private static final String REVOKED_MESSAGE_CONTENT = "当前新增评价任务已被撤回";
@Resource
private EvaluationTaskMapper taskMapper;
......@@ -351,6 +353,41 @@ public class EvaluationServiceImpl implements EvaluationService {
if (taskMapper.revokePending(taskId, adminId, now) == 0) {
throw new BusinessException("任务状态已变化,无法撤回:" + taskId);
}
publishRevokeNotification(task, adminId);
}
/**
* 向任务创建时固化的目标学员发送撤回消息。
*
* <p>通知继续关联原任务ID,消息中心查询时即可让原发布通知和本条撤回通知共同展示
* 当前任务的撤回状态;不设置过期时间,防止原截止时间到达后撤回记录从消息中心消失。</p>
*/
private void publishRevokeNotification(EvaluationTaskEntity task, String adminId) {
List<EvaluationRecordVO> records = recordMapper.queryTaskRecords(task.getId(), null);
if (records == null || records.isEmpty()) {
// 兼容没有学员快照的历史异常数据:任务仍可撤回,但不能构造无接收人的非法消息。
return;
}
List<String> studentIds = records.stream()
.map(EvaluationRecordVO::getStudentId)
.filter(id -> !isBlank(id))
.distinct()
.collect(Collectors.toList());
if (studentIds.isEmpty()) {
return;
}
NotificationPublishDTO message = new NotificationPublishDTO();
message.setEventId("evaluation-task-revoked:" + task.getId());
message.setMessageType("COURSE");
message.setTitle("课程评价任务已撤回");
message.setSummary(REVOKED_MESSAGE_CONTENT);
message.setContent(REVOKED_MESSAGE_CONTENT);
message.setBusinessType("EVALUATION");
message.setBusinessId(task.getId());
message.setPriority("IMPORTANT");
message.setRecipientUserIds(studentIds);
notificationPublisher.publish(message, adminId, "管理员");
}
/** 管理端和学员端共同使用的筛选校验及状态标准化。 */
......
......@@ -181,28 +181,50 @@ public class ExamAdminServiceImpl implements ExamAdminService {
if (!examStudentService.saveBatch(candidates)) {
throw new BusinessException("应考学员保存失败,请稍后重试");
}
// 考试主表、应考名单和通知发件箱原子提交,教师不会收到创建失败的考试安排。
publishExamNotification(entity, managedClass);
// 考试主表、应考名单和两端通知发件箱原子提交,任何一步失败都不会产生孤立消息。
publishExamNotification(entity, managedClass, studentIds);
return detail(entity.getId());
}
/** 新建考试只通知该场考试配置的首席考评员和监考教师,消息中心会再次去重。 */
private void publishExamNotification(ExamEntity exam, ExamAdminClassVO managedClass) {
/**
* 新建考试分别通知负责教师和应考学员。
*
* <p>两端使用不同事件ID和跳转地址,既避免教师入口被发给学员,也保证同一事务重试时
* 两条消息都能由消息中心独立去重。</p>
*/
private void publishExamNotification(ExamEntity exam, ExamAdminClassVO managedClass,
List<String> studentIds) {
String className = trimToNull(managedClass.getClassName()) == null
? "对应班级" : managedClass.getClassName().trim();
NotificationPublishDTO message = new NotificationPublishDTO();
message.setEventId("exam-created:" + exam.getId());
message.setMessageType("EXAM");
message.setTitle("新的考试安排");
message.setSummary(className + "已创建考试“" + exam.getName() + "”");
message.setContent("管理员已为" + className + "创建考试“" + exam.getName()
NotificationPublishDTO teacherMessage = new NotificationPublishDTO();
teacherMessage.setEventId("exam-created:" + exam.getId());
teacherMessage.setMessageType("EXAM");
teacherMessage.setTitle("新的考试安排");
teacherMessage.setSummary(className + "已创建考试“" + exam.getName() + "”");
teacherMessage.setContent("管理员已为" + className + "创建考试“" + exam.getName()
+ "”,请及时查看考试时间、地点及职责安排。");
message.setBusinessType("EXAM");
message.setBusinessId(String.valueOf(exam.getId()));
message.setActionUrl("/exam/teacher/scores/exams/" + exam.getId());
message.setPriority("IMPORTANT");
message.setRecipientUserIds(Arrays.asList(exam.getChiefId(), exam.getInvigilationId()));
notificationPublisher.publish(message, null, AccountAdminConstants.ROLE_ADMIN);
teacherMessage.setBusinessType("EXAM");
teacherMessage.setBusinessId(String.valueOf(exam.getId()));
teacherMessage.setActionUrl("/exam/teacher/scores/exams/" + exam.getId());
teacherMessage.setPriority("IMPORTANT");
teacherMessage.setRecipientUserIds(Arrays.asList(exam.getChiefId(), exam.getInvigilationId()));
notificationPublisher.publish(teacherMessage, null, AccountAdminConstants.ROLE_ADMIN);
NotificationPublishDTO studentMessage = new NotificationPublishDTO();
studentMessage.setEventId("exam-created-students:" + exam.getId());
studentMessage.setMessageType("EXAM");
studentMessage.setTitle("新的考试通知");
studentMessage.setSummary(className + "已创建考试“" + exam.getName() + "”");
studentMessage.setContent("管理员已为" + className + "创建考试“" + exam.getName()
+ "”,请及时查看考试时间、地点及考试要求。");
studentMessage.setBusinessType("EXAM");
studentMessage.setBusinessId(String.valueOf(exam.getId()));
studentMessage.setActionUrl("/exam/student/center");
studentMessage.setPriority("IMPORTANT");
// 直接使用已经通过班级归属校验并保存到exam_student的名单,避免通知非应考学员。
studentMessage.setRecipientUserIds(studentIds);
notificationPublisher.publish(studentMessage, null, AccountAdminConstants.ROLE_ADMIN);
}
@Override
......
......@@ -6,7 +6,6 @@ import com.platform.business.mapper.StudentExamCenterMapper;
import com.platform.business.model.dto.StudentExamAnswerDTO;
import com.platform.business.model.dto.StudentExamCenterQueryDTO;
import com.platform.business.model.entity.TheoreticalPaperDetailEntity;
import com.platform.business.model.entity.TheoreticalPaperEntity;
import com.platform.business.model.entity.TheoreticalPaperStudentDetailEntity;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.StudentExamCenterVO;
......@@ -173,6 +172,13 @@ public class StudentExamCenterServiceImpl implements StudentExamCenterService {
if (questions == null || questions.isEmpty()) {
throw new BusinessException("个人试卷尚未生成,请重新开始考试");
}
/*
* Mapper已按原试卷的题型分组顺序返回。这里以最终展示位置生成连续题号,既保证
* 新试卷稳定,也修正历史个人试卷沿用旧题号造成的65、100、104、66跳号。
*/
for (int index = 0; index < questions.size(); index++) {
questions.get(index).setSequence(String.valueOf(index + 1));
}
int answered = (int) questions.stream()
.filter(question -> hasText(question.getActualChoice())).count();
StudentExamCenterVO.Paper result = new StudentExamCenterVO.Paper();
......@@ -363,30 +369,32 @@ public class StudentExamCenterServiceImpl implements StudentExamCenterService {
if (!hasText(attempt.getPaperId())) {
throw new BusinessException("考试尚未配置理论试卷");
}
TheoreticalPaperEntity paper = theoreticalPaperService.getById(attempt.getPaperId());
if (paper == null) {
if (theoreticalPaperService.getById(attempt.getPaperId()) == null) {
throw new BusinessException("考试关联的理论试卷不存在");
}
List<TheoreticalPaperDetailEntity> source;
if ("乱序".equals(paper.getSequence())) {
source = theoreticalPaperDetailService.selectDisorderly(attempt.getPaperId());
} else {
source = theoreticalPaperDetailService.lambdaQuery()
.eq(TheoreticalPaperDetailEntity::getPaperId, attempt.getPaperId())
.orderByAsc(TheoreticalPaperDetailEntity::getSequence)
.list();
}
/*
* 自动组卷时已经从题库随机抽取过题目。开考阶段只复制这份已确定的试卷,并保持
* “题型分组 + 组内题号”顺序;忽略历史试卷的“乱序”标记,避免再次随机。
*/
List<TheoreticalPaperDetailEntity> source =
theoreticalPaperDetailService.selectInPaperOrder(attempt.getPaperId());
if (source == null || source.isEmpty()) {
throw new BusinessException("考试试卷没有可用题目");
}
List<TheoreticalPaperStudentDetailEntity> personal = new ArrayList<>(source.size());
for (TheoreticalPaperDetailEntity item : source) {
for (int index = 0; index < source.size(); index++) {
TheoreticalPaperDetailEntity item = source.get(index);
TheoreticalPaperStudentDetailEntity target = BeanUtil.copyProperties(
item, TheoreticalPaperStudentDetailEntity.class);
target.setId(null);
// 必须使用JWT学员ID;旧实现误用应考记录ID检查重复,可能生成多份个人试卷。
target.setStudentId(studentId);
target.setExamId(attempt.getExamId());
/*
* source已经按原试卷的题型分组顺序返回。个人试卷必须按该列表重新生成连续
* 题号,不能沿用分组前的历史题号,否则答题页会出现65后跳到100的现象。
*/
target.setSequence(String.valueOf(index + 1));
target.setActualChoice(null);
target.setActualScore(null);
target.setResult(null);
......
package com.platform.business.service.impl;
import com.platform.business.constant.AttendanceConstants;
import com.platform.business.mapper.StudentHomeMapper;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.StudentHomeVO;
......@@ -94,7 +95,7 @@ public class StudentHomeServiceImpl implements StudentHomeService {
Date exclusiveEnd = addDays(today, 3);
List<StudentHomeVO.Course> courses = profile.getClassId() == null
? Collections.emptyList()
: studentHomeMapper.selectCourses(profile.getClassId(), today, exclusiveEnd);
: studentHomeMapper.selectCourses(student.getId(), profile.getClassId(), today, exclusiveEnd);
// LinkedHashMap确保无课程日期也按今天、明天、后天的固定顺序返回。
Map<String, StudentHomeVO.CourseDay> groups = new LinkedHashMap<>();
......@@ -111,7 +112,13 @@ public class StudentHomeServiceImpl implements StudentHomeService {
for (StudentHomeVO.Course course : courses) {
StudentHomeVO.CourseDay day = groups.get(dayKey(course.getDate()));
if (day != null) {
course.setStatus(resolveCourseStatus(course.getDate(), course.getTimeFrame(), current));
/*
* 审批通过的请假是已经确定的课程结果,优先级高于课程时间状态。
* 即使课程尚未开始,也必须返回LEAVE,不能再被映射成待签到或已签到。
*/
course.setStatus(AttendanceConstants.STATUS_LEAVE.equals(course.getAttendanceStatus())
? AttendanceConstants.STATUS_LEAVE
: resolveCourseStatus(course.getDate(), course.getTimeFrame(), current));
day.getCourses().add(course);
}
}
......
......@@ -40,6 +40,7 @@ import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHeightRule;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
......@@ -48,6 +49,7 @@ import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
......@@ -69,6 +71,10 @@ import java.util.Map;
@Service
public class TeachingPlanServiceImpl implements TeachingPlanService {
private static final String TEACHING_PLAN_WORD_TEMPLATE =
"templates/teaching-plan/B8-teaching-plan.docx";
private static final String TEACHING_PLAN_WORD_FONT = "Songti SC";
@Resource
private TeachingPlanMapper teachingPlanMapper;
......@@ -446,43 +452,15 @@ public class TeachingPlanServiceImpl implements TeachingPlanService {
@Override
public void exportAdminDetail(String id, HttpServletResponse response) {
TeachingPlanVO plan = adminDetail(id);
try (XWPFDocument document = new XWPFDocument()) {
XWPFParagraph title = document.createParagraph();
title.setAlignment(ParagraphAlignment.CENTER);
XWPFRun titleRun = title.createRun();
titleRun.setBold(true);
titleRun.setFontSize(18);
titleRun.setText(plan.getTitle());
XWPFTable summary = document.createTable(1, 2);
writeWordTableRow(summary.getRow(0), "教师", plan.getTeacherName());
addWordTableRow(summary, "课程类型", plan.getCourseType());
addWordTableRow(summary, "适用课程", plan.getApplicableCourse());
addWordTableRow(summary, "职业(等级)", plan.getVocationalLevel());
addWordTableRow(summary, "培训机构", plan.getTrainingInstitution());
addWordTableRow(summary, "编写日期", formatDate(plan.getPreparationDate(), "yyyy-MM-dd"));
addWordTableRow(summary, "授课日期", formatDate(plan.getTeachingDate(), "yyyy-MM-dd"));
addWordTableRow(summary, "章节(课题)", plan.getChapterTopic());
addWordTableRow(summary, "课时(分钟)", value(plan.getDurationMinutes()));
addWordTableRow(summary, "授课班级", plan.getClassName());
addWordTableRow(summary, "状态", plan.getStatus());
addWordSection(document, "教学目的", plan.getTeachingPurpose());
if (TeachingPlanConstants.COURSE_TYPE_PRACTICE.equals(plan.getCourseType())) {
addWordSection(document, "实训内容", plan.getPracticeContent());
addWordSection(document, "实训设备", plan.getPracticeEquipment());
}
addWordSection(document, "教学重点", plan.getKeyPoints());
addWordSection(document, "教学难点", plan.getDifficultPoints());
addWordSection(document, "教学辅助手段", plan.getTeachingAids());
addWordSteps(document, plan.getSteps());
addWordSection(document, "教学后记", plan.getTeachingNote());
addWordSection(document, "签名", plan.getSignature());
addWordSection(document, "审核人", plan.getReviewerName());
addWordSection(document, "审核意见", plan.getReviewOpinion());
addWordSection(document, "审核时间",
formatDate(plan.getReviewTime(), "yyyy-MM-dd HH:mm:ss"));
addWordSection(document, "附件", attachmentNames(plan.getAttachments()));
InputStream templateInput = getClass().getClassLoader()
.getResourceAsStream(TEACHING_PLAN_WORD_TEMPLATE);
if (templateInput == null) {
throw new BusinessException("教案导出模板不存在");
}
try (InputStream input = templateInput;
XWPFDocument document = new XWPFDocument(input)) {
// 直接填充项目内的 B8 表模板,完整保留原表格合并、两页分节、页码和说明文字。
populateTeachingPlanTemplate(document, plan);
writeDownloadResponse(response, document,
safeFilename(plan.getTitle()) + "-教案.docx",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document");
......@@ -798,62 +776,212 @@ public class TeachingPlanServiceImpl implements TeachingPlanService {
row.createCell(column).setCellValue(value(cellValue));
}
/** 写入Word基本信息表格的一行。 */
private void addWordTableRow(XWPFTable table, String label, String content) {
writeWordTableRow(table.createRow(), label, content);
/**
* 按 B8 教案表的固定槽位写入业务数据。
*
* <p>模板第一张表使用合并单元格,因此这里使用“物理单元格下标”,不能按视觉上的
* 九列网格直接寻址;第二张表保持原来的三列结构,课时写在教学环节名称之后。</p>
*/
private void populateTeachingPlanTemplate(XWPFDocument document, TeachingPlanVO plan) {
if (document.getParagraphs().size() < 3 || document.getTables().size() < 2) {
throw new BusinessException("教案导出模板结构不正确");
}
normalizeTeachingPlanTemplateFont(document);
writeWordParagraph(document.getParagraphs().get(1),
"培训机构:" + value(plan.getTrainingInstitution())
+ " 授课教师:" + value(plan.getTeacherName())
+ " (课程类型:" + courseTypeName(plan.getCourseType()) + ")",
ParagraphAlignment.LEFT, true, 12);
writeWordParagraph(document.getParagraphs().get(2),
"编写日期 " + formatDate(plan.getPreparationDate(), "yyyy年M月d日"),
ParagraphAlignment.RIGHT, true, 12);
XWPFTable summary = document.getTables().get(0);
if (summary.getRows().size() < 9) {
throw new BusinessException("教案导出模板综合信息表结构不正确");
}
// 原表为手写留出了大块空白;电子填值后缩短最小行高,确保审批和页下注仍位于第一页。
setWordRowMinimumHeight(summary.getRow(2), 760);
setWordRowMinimumHeight(summary.getRow(3), 760);
setWordRowMinimumHeight(summary.getRow(4),
TeachingPlanConstants.COURSE_TYPE_PRACTICE.equals(plan.getCourseType()) ? 1400 : 1200);
setWordRowMinimumHeight(summary.getRow(5), 1200);
// 四个竖排标签使用较小字号,既完整显示四个汉字,也避免把页下注挤到下一页。
setWordCellFontSize(summary.getRow(4).getCell(0), 10);
setWordCellFontSize(summary.getRow(4).getCell(2), 10);
setWordCellFontSize(summary.getRow(5).getCell(0), 10);
setWordCellFontSize(summary.getRow(5).getCell(2), 10);
setWordRowMinimumHeight(summary.getRow(6), 760);
setWordRowMinimumHeight(summary.getRow(7), 760);
setWordRowMinimumHeight(summary.getRow(8), 1300);
writeWordCell(summary.getRow(0).getCell(1), plan.getVocationalLevel());
writeWordCell(summary.getRow(0).getCell(4), plan.getClassName(), 9);
writeWordCell(summary.getRow(1).getCell(1), plan.getApplicableCourse());
writeWordCell(summary.getRow(1).getCell(4), teachingDateAndDuration(plan), 9);
writeWordCell(summary.getRow(2).getCell(1), teachingPlanTopic(plan));
writeWordCell(summary.getRow(3).getCell(1), plan.getTeachingPurpose());
writeWordCell(summary.getRow(4).getCell(1), practiceValue(plan.getPracticeContent(), plan));
writeWordCell(summary.getRow(4).getCell(3), practiceValue(plan.getPracticeEquipment(), plan));
writeWordCell(summary.getRow(5).getCell(1), plan.getKeyPoints());
writeWordCell(summary.getRow(5).getCell(3), plan.getDifficultPoints());
writeWordCell(summary.getRow(6).getCell(1), plan.getTeachingAids());
writeWordCell(summary.getRow(7).getCell(1), plan.getTeachingNote());
writeWordCell(summary.getRow(8).getCell(1), approvalText(plan), 10);
XWPFTable stepsTable = document.getTables().get(1);
if (stepsTable.getRows().size() < 2 || stepsTable.getRow(1).getTableCells().size() < 3) {
throw new BusinessException("教案导出模板教学环节表结构不正确");
}
setWordRowMinimumHeight(stepsTable.getRow(1), 10000);
writeTeachingPlanSteps(stepsTable.getRow(1), plan.getSteps());
}
/** 将模板中未显式指定中文字体的固定文字统一为宋体风格,避免不同系统替换成无字形字体。 */
private void normalizeTeachingPlanTemplateFont(XWPFDocument document) {
for (XWPFParagraph paragraph : document.getParagraphs()) {
setWordRunsFont(paragraph);
}
for (XWPFTable table : document.getTables()) {
for (XWPFTableRow row : table.getRows()) {
for (XWPFTableCell cell : row.getTableCells()) {
for (XWPFParagraph paragraph : cell.getParagraphs()) {
setWordRunsFont(paragraph);
}
}
}
}
}
private void setWordRunsFont(XWPFParagraph paragraph) {
for (XWPFRun run : paragraph.getRuns()) {
run.setFontFamily(TEACHING_PLAN_WORD_FONT);
run.setFontFamily(TEACHING_PLAN_WORD_FONT, XWPFRun.FontCharRange.eastAsia);
run.setColor("000000");
}
}
/** 重置单元格默认段落内容并写入标签和值。 */
private void writeWordTableRow(XWPFTableRow row, String label, String content) {
while (row.getTableCells().size() < 2) {
row.addNewTableCell();
private void setWordCellFontSize(XWPFTableCell cell, int fontSize) {
for (XWPFParagraph paragraph : cell.getParagraphs()) {
for (XWPFRun run : paragraph.getRuns()) {
run.setFontSize(fontSize);
}
}
writeWordCell(row.getCell(0), label);
writeWordCell(row.getCell(1), content);
}
/** 清空可编辑段落原有占位符,再按模板字号写入动态内容。 */
private void writeWordParagraph(XWPFParagraph paragraph, String content,
ParagraphAlignment alignment, boolean bold, int fontSize) {
for (int i = paragraph.getRuns().size() - 1; i >= 0; i--) {
paragraph.removeRun(i);
}
paragraph.setAlignment(alignment);
XWPFRun run = paragraph.createRun();
run.setBold(bold);
run.setFontSize(fontSize);
run.setFontFamily(TEACHING_PLAN_WORD_FONT);
run.setFontFamily(TEACHING_PLAN_WORD_FONT, XWPFRun.FontCharRange.eastAsia);
run.setColor("000000");
writeWordText(run, content);
}
/** 保留单元格、边框和合并关系,仅替换其正文;空值显示“无”,避免表单含义不清。 */
private void writeWordCell(XWPFTableCell cell, String content) {
cell.removeParagraph(0);
XWPFParagraph paragraph = cell.addParagraph();
writeWordText(paragraph.createRun(), content);
}
/** 将长正文按“标题 + 内容”段落写入Word,并正确保留换行。 */
private void addWordSection(XWPFDocument document, String label, String content) {
XWPFParagraph heading = document.createParagraph();
XWPFRun headingRun = heading.createRun();
headingRun.setBold(true);
headingRun.setText(label);
XWPFParagraph body = document.createParagraph();
writeWordText(body.createRun(), content);
}
/** 将结构化教学环节导出为表格,顺序与编辑器中的数组顺序保持一致。 */
private void addWordSteps(XWPFDocument document, List<TeachingPlanStepVO> steps) {
XWPFParagraph heading = document.createParagraph();
XWPFRun headingRun = heading.createRun();
headingRun.setBold(true);
headingRun.setText("教学环节");
writeWordCell(cell, content, 11);
}
private void writeWordCell(XWPFTableCell cell, String content, int fontSize) {
while (cell.getParagraphs().size() > 1) {
cell.removeParagraph(cell.getParagraphs().size() - 1);
}
XWPFParagraph paragraph = cell.getParagraphs().get(0);
paragraph.setSpacingBefore(0);
paragraph.setSpacingAfter(0);
writeWordParagraph(paragraph, StringUtils.hasText(content) ? content : "无",
ParagraphAlignment.LEFT, false, fontSize);
}
/** 行高只作为下限,内容较多时仍可自动增高,避免固定高度裁切正文。 */
private void setWordRowMinimumHeight(XWPFTableRow row, int height) {
row.setHeight(height);
row.getCtRow().getTrPr().getTrHeightArray(0).setHRule(STHeightRule.AT_LEAST);
}
/** 三列使用完全相同的编号顺序,正文中的原始换行继续保留。 */
private void writeTeachingPlanSteps(XWPFTableRow row, List<TeachingPlanStepVO> steps) {
if (steps == null || steps.isEmpty()) {
writeWordText(document.createParagraph().createRun(), "无");
writeWordCell(row.getCell(0), "无");
writeWordCell(row.getCell(1), "无");
writeWordCell(row.getCell(2), "无");
return;
}
XWPFTable table = document.createTable(1, 5);
XWPFTableRow header = table.getRow(0);
writeWordCell(header.getCell(0), "序号");
writeWordCell(header.getCell(1), "教学环节");
writeWordCell(header.getCell(2), "教学内容");
writeWordCell(header.getCell(3), "教学方法");
writeWordCell(header.getCell(4), "时长(分钟)");
StringBuilder stages = new StringBuilder();
StringBuilder contents = new StringBuilder();
StringBuilder methods = new StringBuilder();
for (int i = 0; i < steps.size(); i++) {
TeachingPlanStepVO step = steps.get(i);
XWPFTableRow row = table.createRow();
writeWordCell(row.getCell(0), value(i + 1));
writeWordCell(row.getCell(1), step.getStageName());
writeWordCell(row.getCell(2), step.getContent());
writeWordCell(row.getCell(3), step.getMethod());
writeWordCell(row.getCell(4), value(step.getDurationMinutes()));
appendWordListItem(stages, i, step.getStageName(), step.getDurationMinutes());
appendWordListItem(contents, i, step.getContent(), null);
appendWordListItem(methods, i, step.getMethod(), null);
}
writeWordCell(row.getCell(0), stages.toString(), 9);
writeWordCell(row.getCell(1), contents.toString(), 10);
writeWordCell(row.getCell(2), methods.toString(), 10);
}
private void appendWordListItem(StringBuilder builder, int index, String content,
Integer durationMinutes) {
if (builder.length() > 0) {
builder.append('\n');
}
builder.append(index + 1).append(". ").append(value(content));
if (durationMinutes != null) {
builder.append("(").append(durationMinutes).append("分钟)");
}
}
private String teachingPlanTopic(TeachingPlanVO plan) {
return "教案名称:" + value(plan.getTitle()) + "\n章节(课题):" + value(plan.getChapterTopic());
}
private String teachingDateAndDuration(TeachingPlanVO plan) {
return formatDate(plan.getTeachingDate(), "yyyy-MM-dd")
+ "\n" + value(plan.getDurationMinutes()) + "分钟";
}
private String practiceValue(String content, TeachingPlanVO plan) {
return TeachingPlanConstants.COURSE_TYPE_PRACTICE.equals(plan.getCourseType())
? value(content) : "—";
}
/** 审批槽统一容纳管理端状态、审核记录、教师签名和附件,确保原导出字段不丢失。 */
private String approvalText(TeachingPlanVO plan) {
return "状态:" + statusName(plan.getStatus())
+ " 审核人:" + value(plan.getReviewerName())
+ "\n审核意见:" + value(plan.getReviewOpinion())
+ "\n审核时间:" + formatDate(plan.getReviewTime(), "yyyy-MM-dd HH:mm")
+ " 教师签名:" + value(plan.getSignature())
+ " 附件:" + attachmentNames(plan.getAttachments());
}
private String courseTypeName(String courseType) {
return TeachingPlanConstants.COURSE_TYPE_PRACTICE.equals(courseType) ? "实训课" : "理论课";
}
private String statusName(String status) {
if (TeachingPlanConstants.STATUS_DRAFT.equals(status)) {
return "草稿";
}
if (TeachingPlanConstants.STATUS_PENDING.equals(status)) {
return "待审核";
}
if (TeachingPlanConstants.STATUS_APPROVED.equals(status)) {
return "审核通过";
}
if (TeachingPlanConstants.STATUS_REJECTED.equals(status)) {
return "已退回";
}
return value(status);
}
private void writeWordText(XWPFRun run, String content) {
......
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