Commit 0b2419f1 authored by 王蔡翾's avatar 王蔡翾
Browse files

消息中心,消息队列和websocket,以及请假注释

parent 1ea1a030
package com.platform.business.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.function.LongSupplier;
/** 未读数只作为可丢失缓存,MySQL 始终是真实数据源。 */
@Service
@Slf4j
public class NotificationUnreadCache {
private static final String PREFIX = "notification:unread:";
@Resource
private StringRedisTemplate stringRedisTemplate;
/**
* 获取未读数。缓存未命中时调用loader查询MySQL,并缓存5分钟。
* Redis故障不会中断消息中心主流程,而是直接执行loader完成降级。
*/
public long get(String userId, LongSupplier loader) {
try {
String value = stringRedisTemplate.opsForValue().get(PREFIX + userId);
if (value != null) {
return Long.parseLong(value);
}
long loaded = loader.getAsLong();
stringRedisTemplate.opsForValue().set(PREFIX + userId, String.valueOf(loaded), 5, TimeUnit.MINUTES);
return loaded;
} catch (Exception e) {
log.warn("Redis 未读数缓存不可用,降级查询数据库: {}", e.getMessage());
return loader.getAsLong();
}
}
/**
* 使单个用户的未读缓存失效。
* 所有已读、删除和新消息写入操作都调用该方法,避免维护易出错的缓存增减计数。
*/
public void evict(String userId) {
try {
stringRedisTemplate.delete(PREFIX + userId);
} catch (Exception e) {
log.warn("清理未读数缓存失败: {}", e.getMessage());
}
}
}
...@@ -45,6 +45,7 @@ import java.util.List; ...@@ -45,6 +45,7 @@ import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Set; import java.util.Set;
/** 出勤管理核心实现,所有时间判断均以课程计划开始、结束时间为基准。 */
@Service @Service
@Slf4j @Slf4j
public class AttendanceServiceImpl implements AttendanceService { public class AttendanceServiceImpl implements AttendanceService {
...@@ -76,6 +77,7 @@ public class AttendanceServiceImpl implements AttendanceService { ...@@ -76,6 +77,7 @@ public class AttendanceServiceImpl implements AttendanceService {
ClassSubjectEntity subject = requireSubject(subjectId); ClassSubjectEntity subject = requireSubject(subjectId);
requireTeacher(subject, teacherId); requireTeacher(subject, teacherId);
// 课程与会话是一对一关系:已经开始过的课程始终返回原验证码,不重新生成。
ClassSubjectAttendanceSessionEntity existing = findSession(subjectId); ClassSubjectAttendanceSessionEntity existing = findSession(subjectId);
if (existing != null) { if (existing != null) {
if (existing.getVerificationCode() == null) { if (existing.getVerificationCode() == null) {
...@@ -96,15 +98,18 @@ public class AttendanceServiceImpl implements AttendanceService { ...@@ -96,15 +98,18 @@ public class AttendanceServiceImpl implements AttendanceService {
ClassSubjectAttendanceSessionEntity session = new ClassSubjectAttendanceSessionEntity(); ClassSubjectAttendanceSessionEntity session = new ClassSubjectAttendanceSessionEntity();
session.setSubjectId(subjectId); session.setSubjectId(subjectId);
session.setTeacherId(teacherId); session.setTeacherId(teacherId);
// 固定补足6位,包含可能以0开头的验证码。
session.setVerificationCode(String.format("%06d", RANDOM.nextInt(1_000_000))); session.setVerificationCode(String.format("%06d", RANDOM.nextInt(1_000_000)));
session.setScheduledStartTime(window.getStart()); session.setScheduledStartTime(window.getStart());
session.setScheduledEndTime(window.getEnd()); session.setScheduledEndTime(window.getEnd());
session.setStartedAt(now); session.setStartedAt(now);
// 验证码窗口以计划开始时间计算,与教师实际点击开始上课时间无关。
session.setCodeExpiresAt(addMinutes(window.getStart(), attendanceProperties.getVerificationCodeValidMinutes())); session.setCodeExpiresAt(addMinutes(window.getStart(), attendanceProperties.getVerificationCodeValidMinutes()));
session.setStatus(AttendanceConstants.SESSION_ACTIVE); session.setStatus(AttendanceConstants.SESSION_ACTIVE);
session.setCreatedTime(now); session.setCreatedTime(now);
session.setUpdateTime(now); session.setUpdateTime(now);
session.setId(IdWorker.getIdStr()); session.setId(IdWorker.getIdStr());
// 唯一索引解决教师重复点击或并发请求;未插入时读取另一请求创建的会话。
if (attendanceSessionMapper.insertIgnore(session) == 0) { if (attendanceSessionMapper.insertIgnore(session) == 0) {
session = findSession(subjectId); session = findSession(subjectId);
if (session == null) { if (session == null) {
...@@ -137,6 +142,7 @@ public class AttendanceServiceImpl implements AttendanceService { ...@@ -137,6 +142,7 @@ public class AttendanceServiceImpl implements AttendanceService {
if (session == null || !AttendanceConstants.SESSION_ACTIVE.equals(session.getStatus())) { if (session == null || !AttendanceConstants.SESSION_ACTIVE.equals(session.getStatus())) {
throw new BusinessException("教师尚未开始上课,暂不能签到"); throw new BusinessException("教师尚未开始上课,暂不能签到");
} }
// 无论是否超过验证码窗口,网段校验都是必需条件。
if (!IpNetworkMatcher.matchesAny(clientIp, attendanceProperties.getAllowedIpCidrs())) { if (!IpNetworkMatcher.matchesAny(clientIp, attendanceProperties.getAllowedIpCidrs())) {
throw new BusinessException("当前IP不在允许签到的网段内"); throw new BusinessException("当前IP不在允许签到的网段内");
} }
...@@ -149,6 +155,7 @@ public class AttendanceServiceImpl implements AttendanceService { ...@@ -149,6 +155,7 @@ public class AttendanceServiceImpl implements AttendanceService {
throw new BusinessException("当前出勤状态为" + existing.getStatus() + ",不能重复签到"); throw new BusinessException("当前出勤状态为" + existing.getStatus() + ",不能重复签到");
} }
// 超过计划开始+配置分钟数后不再要求验证码,但初始状态固定为迟到。
boolean afterCodeWindow = now.after(session.getCodeExpiresAt()); boolean afterCodeWindow = now.after(session.getCodeExpiresAt());
String status; String status;
String method; String method;
...@@ -178,6 +185,7 @@ public class AttendanceServiceImpl implements AttendanceService { ...@@ -178,6 +185,7 @@ public class AttendanceServiceImpl implements AttendanceService {
record.setCreatedTime(now); record.setCreatedTime(now);
record.setUpdateTime(now); record.setUpdateTime(now);
record.setId(IdWorker.getIdStr()); record.setId(IdWorker.getIdStr());
// 与请假审批并发时由课程+学员唯一索引决定最终顺序,不能覆盖LEAVE或ABSENT。
if (attendanceMapper.insertIgnore(record) == 0) { if (attendanceMapper.insertIgnore(record) == 0) {
ClassSubjectAttendanceEntity concurrentRecord = findRecord(subject.getId(), studentId); ClassSubjectAttendanceEntity concurrentRecord = findRecord(subject.getId(), studentId);
if (concurrentRecord != null && AttendanceConstants.isPresent(concurrentRecord.getStatus())) { if (concurrentRecord != null && AttendanceConstants.isPresent(concurrentRecord.getStatus())) {
...@@ -229,6 +237,7 @@ public class AttendanceServiceImpl implements AttendanceService { ...@@ -229,6 +237,7 @@ public class AttendanceServiceImpl implements AttendanceService {
record.setConfirmedBy(teacherId); record.setConfirmedBy(teacherId);
record.setConfirmedAt(now); record.setConfirmedAt(now);
record.setUpdateTime(now); record.setUpdateTime(now);
// SQL层再次保护LEAVE,避免“查询后、写入前”发生请假审批造成竞态覆盖。
attendanceMapper.upsertTeacherStatus(record); attendanceMapper.upsertTeacherStatus(record);
AttendanceRecordVO result = requireRecordVO(subject.getId(), request.getStudentId()); AttendanceRecordVO result = requireRecordVO(subject.getId(), request.getStudentId());
if (AttendanceConstants.STATUS_LEAVE.equals(result.getStatus())) { if (AttendanceConstants.STATUS_LEAVE.equals(result.getStatus())) {
...@@ -265,6 +274,7 @@ public class AttendanceServiceImpl implements AttendanceService { ...@@ -265,6 +274,7 @@ public class AttendanceServiceImpl implements AttendanceService {
} else if (summary.getAttendanceRate() == null) { } else if (summary.getAttendanceRate() == null) {
summary.setAttendanceRate(BigDecimal.ZERO); summary.setAttendanceRate(BigDecimal.ZERO);
} }
// 同一次筛选同时返回总览、学员维度和课程维度,保证管理端统计口径一致。
summary.setStudentStatistics(attendanceMapper.queryStudentStatistics(safeQuery)); summary.setStudentStatistics(attendanceMapper.queryStudentStatistics(safeQuery));
summary.setCourseStatistics(attendanceMapper.queryCourseStatistics(safeQuery)); summary.setCourseStatistics(attendanceMapper.queryCourseStatistics(safeQuery));
return summary; return summary;
...@@ -291,6 +301,7 @@ public class AttendanceServiceImpl implements AttendanceService { ...@@ -291,6 +301,7 @@ public class AttendanceServiceImpl implements AttendanceService {
} }
} }
/** 关闭单门已结束课程,并为仍无任何记录的班级学员幂等补写ABSENT。 */
private void finalizeSubject(ClassSubjectEntity subject, ClassSubjectTimeUtils.TimeWindow window, Date now) { private void finalizeSubject(ClassSubjectEntity subject, ClassSubjectTimeUtils.TimeWindow window, Date now) {
ClassSubjectAttendanceSessionEntity session = findSession(subject.getId()); ClassSubjectAttendanceSessionEntity session = findSession(subject.getId());
if (session == null) { if (session == null) {
...@@ -321,6 +332,7 @@ public class AttendanceServiceImpl implements AttendanceService { ...@@ -321,6 +332,7 @@ public class AttendanceServiceImpl implements AttendanceService {
for (ClassSubjectAttendanceEntity record : existing) { for (ClassSubjectAttendanceEntity record : existing) {
recordedUsers.add(record.getUserId()); recordedUsers.add(record.getUserId());
} }
// 已存在NORMAL/LATE/LEAVE/ABSENT任一记录都不再补写,避免覆盖签到或请假。
List<ClassSubjectAttendanceEntity> absences = new ArrayList<>(); List<ClassSubjectAttendanceEntity> absences = new ArrayList<>();
for (ClassStudentEntity student : students) { for (ClassStudentEntity student : students) {
if (recordedUsers.contains(student.getUserId())) { if (recordedUsers.contains(student.getUserId())) {
...@@ -342,6 +354,7 @@ public class AttendanceServiceImpl implements AttendanceService { ...@@ -342,6 +354,7 @@ public class AttendanceServiceImpl implements AttendanceService {
} }
} }
/** 组装签到会话展示信息,并补充班级、教师姓名及完整手机号。 */
private AttendanceSessionVO toSessionVO(ClassSubjectAttendanceSessionEntity session, ClassSubjectEntity subject) { private AttendanceSessionVO toSessionVO(ClassSubjectAttendanceSessionEntity session, ClassSubjectEntity subject) {
AttendanceSessionVO result = new AttendanceSessionVO(); AttendanceSessionVO result = new AttendanceSessionVO();
result.setSessionId(session.getId()); result.setSessionId(session.getId());
...@@ -366,6 +379,7 @@ public class AttendanceServiceImpl implements AttendanceService { ...@@ -366,6 +379,7 @@ public class AttendanceServiceImpl implements AttendanceService {
return result; return result;
} }
/** 查询刚写入的单条出勤记录;查不到时按保存失败处理。 */
private AttendanceRecordVO requireRecordVO(Integer subjectId, String studentId) { private AttendanceRecordVO requireRecordVO(Integer subjectId, String studentId) {
AttendanceQueryDTO query = new AttendanceQueryDTO(); AttendanceQueryDTO query = new AttendanceQueryDTO();
query.setSubjectId(subjectId); query.setSubjectId(subjectId);
...@@ -377,6 +391,7 @@ public class AttendanceServiceImpl implements AttendanceService { ...@@ -377,6 +391,7 @@ public class AttendanceServiceImpl implements AttendanceService {
return records.get(0); return records.get(0);
} }
/** 校验课程排课ID并返回课程实体。 */
private ClassSubjectEntity requireSubject(Integer subjectId) { private ClassSubjectEntity requireSubject(Integer subjectId) {
if (subjectId == null) { if (subjectId == null) {
throw new BusinessException("课程ID不能为空"); throw new BusinessException("课程ID不能为空");
...@@ -388,12 +403,14 @@ public class AttendanceServiceImpl implements AttendanceService { ...@@ -388,12 +403,14 @@ public class AttendanceServiceImpl implements AttendanceService {
return subject; return subject;
} }
/** 校验操作者是该排课的授课教师。 */
private void requireTeacher(ClassSubjectEntity subject, String teacherId) { private void requireTeacher(ClassSubjectEntity subject, String teacherId) {
if (isBlank(teacherId) || !teacherId.equals(subject.getTeacherId())) { if (isBlank(teacherId) || !teacherId.equals(subject.getTeacherId())) {
throw new BusinessException("只有本课程授课教师可以执行该操作"); throw new BusinessException("只有本课程授课教师可以执行该操作");
} }
} }
/** 校验学员属于课程所在班级,防止跨班签到或教师误操作。 */
private void requireStudentInClass(Integer classId, String studentId) { private void requireStudentInClass(Integer classId, String studentId) {
if (isBlank(studentId)) { if (isBlank(studentId)) {
throw new BusinessException("无法获取当前学员身份"); throw new BusinessException("无法获取当前学员身份");
...@@ -406,12 +423,14 @@ public class AttendanceServiceImpl implements AttendanceService { ...@@ -406,12 +423,14 @@ public class AttendanceServiceImpl implements AttendanceService {
} }
} }
/** 按课程排课ID查询唯一签到会话。 */
private ClassSubjectAttendanceSessionEntity findSession(Integer subjectId) { private ClassSubjectAttendanceSessionEntity findSession(Integer subjectId) {
return attendanceSessionService.getOne( return attendanceSessionService.getOne(
new LambdaQueryWrapper<ClassSubjectAttendanceSessionEntity>() new LambdaQueryWrapper<ClassSubjectAttendanceSessionEntity>()
.eq(ClassSubjectAttendanceSessionEntity::getSubjectId, subjectId), false); .eq(ClassSubjectAttendanceSessionEntity::getSubjectId, subjectId), false);
} }
/** 按课程和学员查询唯一出勤记录。 */
private ClassSubjectAttendanceEntity findRecord(Integer subjectId, String userId) { private ClassSubjectAttendanceEntity findRecord(Integer subjectId, String userId) {
return attendanceRecordService.getOne( return attendanceRecordService.getOne(
new LambdaQueryWrapper<ClassSubjectAttendanceEntity>() new LambdaQueryWrapper<ClassSubjectAttendanceEntity>()
...@@ -419,6 +438,7 @@ public class AttendanceServiceImpl implements AttendanceService { ...@@ -419,6 +438,7 @@ public class AttendanceServiceImpl implements AttendanceService {
.eq(ClassSubjectAttendanceEntity::getUserId, userId), false); .eq(ClassSubjectAttendanceEntity::getUserId, userId), false);
} }
/** 将日期筛选规范化为当天00:00:00.000至23:59:59.999。 */
private Date[] normalizeRange(Date startDate, Date endDate) { private Date[] normalizeRange(Date startDate, Date endDate) {
Calendar start = Calendar.getInstance(); Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance(); Calendar end = Calendar.getInstance();
...@@ -446,6 +466,7 @@ public class AttendanceServiceImpl implements AttendanceService { ...@@ -446,6 +466,7 @@ public class AttendanceServiceImpl implements AttendanceService {
return new Date[]{start.getTime(), end.getTime()}; return new Date[]{start.getTime(), end.getTime()};
} }
/** 补齐空查询对象;完全未传日期时默认使用当月1日至当前时间。 */
private AttendanceQueryDTO prepareQuery(AttendanceQueryDTO query) { private AttendanceQueryDTO prepareQuery(AttendanceQueryDTO query) {
AttendanceQueryDTO safeQuery = query == null ? new AttendanceQueryDTO() : query; AttendanceQueryDTO safeQuery = query == null ? new AttendanceQueryDTO() : query;
if (safeQuery.getStartDate() == null && safeQuery.getEndDate() == null) { if (safeQuery.getStartDate() == null && safeQuery.getEndDate() == null) {
...@@ -461,10 +482,12 @@ public class AttendanceServiceImpl implements AttendanceService { ...@@ -461,10 +482,12 @@ public class AttendanceServiceImpl implements AttendanceService {
return safeQuery; return safeQuery;
} }
/** 在指定时间基础上增加分钟数。 */
private static Date addMinutes(Date date, int minutes) { private static Date addMinutes(Date date, int minutes) {
return new Date(date.getTime() + minutes * 60_000L); return new Date(date.getTime() + minutes * 60_000L);
} }
/** 以恒定时间方式比较验证码,避免普通字符串比较产生明显时序差异。 */
private static boolean constantTimeEquals(String left, String right) { private static boolean constantTimeEquals(String left, String right) {
if (right == null) { if (right == null) {
return false; return false;
...@@ -472,6 +495,7 @@ public class AttendanceServiceImpl implements AttendanceService { ...@@ -472,6 +495,7 @@ public class AttendanceServiceImpl implements AttendanceService {
return MessageDigest.isEqual(left.getBytes(StandardCharsets.UTF_8), right.getBytes(StandardCharsets.UTF_8)); return MessageDigest.isEqual(left.getBytes(StandardCharsets.UTF_8), right.getBytes(StandardCharsets.UTF_8));
} }
/** 判断字符串是否为空或仅包含空白。 */
private static boolean isBlank(String value) { private static boolean isBlank(String value) {
return value == null || value.trim().isEmpty(); return value == null || value.trim().isEmpty();
} }
......
...@@ -6,6 +6,7 @@ import com.platform.business.model.entity.ClassSubjectAttendanceSessionEntity; ...@@ -6,6 +6,7 @@ import com.platform.business.model.entity.ClassSubjectAttendanceSessionEntity;
import com.platform.business.service.ClassSubjectAttendanceSessionService; import com.platform.business.service.ClassSubjectAttendanceSessionService;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
/** 课程签到会话通用持久化服务实现。 */
@Service @Service
public class ClassSubjectAttendanceSessionServiceImpl public class ClassSubjectAttendanceSessionServiceImpl
extends ServiceImpl<ClassSubjectAttendanceSessionMapper, ClassSubjectAttendanceSessionEntity> extends ServiceImpl<ClassSubjectAttendanceSessionMapper, ClassSubjectAttendanceSessionEntity>
......
...@@ -40,6 +40,7 @@ import java.util.Locale; ...@@ -40,6 +40,7 @@ import java.util.Locale;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** 请假管理核心实现,负责课程自动匹配、单级审批及出勤状态联动。 */
@Service @Service
public class LeaveManagementServiceImpl implements LeaveManagementService { public class LeaveManagementServiceImpl implements LeaveManagementService {
...@@ -64,6 +65,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService { ...@@ -64,6 +65,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService {
@Transactional @Transactional
public LeaveApplicationVO apply(LeaveApplyDTO request, String studentId) { public LeaveApplicationVO apply(LeaveApplyDTO request, String studentId) {
validateRequest(request); validateRequest(request);
// 课程由服务端计算,避免学员漏选或任意指定不属于本人班级的课程。
List<ClassSubjectEntity> subjects = matchSubjects(request, studentId); List<ClassSubjectEntity> subjects = matchSubjects(request, studentId);
ensureNoSignedAttendance(subjects, studentId, false); ensureNoSignedAttendance(subjects, studentId, false);
ensureNoOverlappingApplication(request, studentId, null); ensureNoOverlappingApplication(request, studentId, null);
...@@ -108,6 +110,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService { ...@@ -108,6 +110,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService {
current.setEmergencyContactPhone(trimToNull(request.getEmergencyContactPhone())); current.setEmergencyContactPhone(trimToNull(request.getEmergencyContactPhone()));
current.setUpdatedAt(new Date()); current.setUpdatedAt(new Date());
leaveApplicationMapper.updateById(current); leaveApplicationMapper.updateById(current);
// 修改时间后课程和证明材料都全量替换,保证关联数据与申请当前内容一致。
leaveSubjectMapper.delete(new LambdaQueryWrapper<StudentLeaveSubjectEntity>() leaveSubjectMapper.delete(new LambdaQueryWrapper<StudentLeaveSubjectEntity>()
.eq(StudentLeaveSubjectEntity::getLeaveId, current.getId())); .eq(StudentLeaveSubjectEntity::getLeaveId, current.getId()));
leaveAttachmentMapper.delete(new LambdaQueryWrapper<StudentLeaveAttachmentEntity>() leaveAttachmentMapper.delete(new LambdaQueryWrapper<StudentLeaveAttachmentEntity>()
...@@ -150,6 +153,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService { ...@@ -150,6 +153,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService {
throw new BusinessException("审批意见不能超过1000个字符"); throw new BusinessException("审批意见不能超过1000个字符");
} }
// 先锁申请主记录,教师与管理员并发审批时只有第一个事务能处理PENDING状态。
StudentLeaveApplicationEntity leave = requireLockedApplication(leaveId); StudentLeaveApplicationEntity leave = requireLockedApplication(leaveId);
if (!LeaveConstants.STATUS_PENDING.equals(leave.getStatus())) { if (!LeaveConstants.STATUS_PENDING.equals(leave.getStatus())) {
throw new BusinessException("该申请已被处理,不能重复审批"); throw new BusinessException("该申请已被处理,不能重复审批");
...@@ -167,6 +171,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService { ...@@ -167,6 +171,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService {
Date now = new Date(); Date now = new Date();
if (LeaveConstants.STATUS_APPROVED.equals(reviewStatus)) { if (LeaveConstants.STATUS_APPROVED.equals(reviewStatus)) {
// 锁定现有出勤记录,防止审批读取与学员签到写入交叉执行。
List<ClassSubjectAttendanceEntity> lockedRecords = attendanceMapper.lockRecords(subjectIds, leave.getStudentId()); List<ClassSubjectAttendanceEntity> lockedRecords = attendanceMapper.lockRecords(subjectIds, leave.getStudentId());
if (lockedRecords.stream().anyMatch(record -> AttendanceConstants.isPresent(record.getStatus()))) { if (lockedRecords.stream().anyMatch(record -> AttendanceConstants.isPresent(record.getStatus()))) {
throw new BusinessException("学员已完成正常或迟到签到,无需请假,不能审批通过"); throw new BusinessException("学员已完成正常或迟到签到,无需请假,不能审批通过");
...@@ -196,6 +201,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService { ...@@ -196,6 +201,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService {
leaveRecords.add(record); leaveRecords.add(record);
} }
attendanceMapper.upsertLeaveStatuses(leaveRecords); attendanceMapper.upsertLeaveStatuses(leaveRecords);
// SQL会保留并发产生的NORMAL/LATE;再次检查并抛错可回滚审批状态。
List<ClassSubjectAttendanceEntity> finalRecords = List<ClassSubjectAttendanceEntity> finalRecords =
attendanceMapper.lockRecords(subjectIds, leave.getStudentId()); attendanceMapper.lockRecords(subjectIds, leave.getStudentId());
if (finalRecords.stream().anyMatch(record -> AttendanceConstants.isPresent(record.getStatus()))) { if (finalRecords.stream().anyMatch(record -> AttendanceConstants.isPresent(record.getStatus()))) {
...@@ -238,6 +244,10 @@ public class LeaveManagementServiceImpl implements LeaveManagementService { ...@@ -238,6 +244,10 @@ public class LeaveManagementServiceImpl implements LeaveManagementService {
return requireDetail(leaveId); return requireDetail(leaveId);
} }
/**
* 从学员所属班级中查找与请假区间真正发生时间重叠的全部课程。
* 任何匹配课程已经开始时均拒绝,用于落实不允许补交请假的规则。
*/
private List<ClassSubjectEntity> matchSubjects(LeaveApplyDTO request, String studentId) { private List<ClassSubjectEntity> matchSubjects(LeaveApplyDTO request, String studentId) {
List<Integer> classIds = classStudentService.queryClassIdByUserId(studentId); List<Integer> classIds = classStudentService.queryClassIdByUserId(studentId);
if (classIds == null || classIds.isEmpty()) { if (classIds == null || classIds.isEmpty()) {
...@@ -264,6 +274,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService { ...@@ -264,6 +274,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService {
return matched; return matched;
} }
/** 校验关联课程不存在NORMAL或LATE记录;审批阶段可选择加行锁。 */
private void ensureNoSignedAttendance(List<ClassSubjectEntity> subjects, String studentId, boolean lock) { private void ensureNoSignedAttendance(List<ClassSubjectEntity> subjects, String studentId, boolean lock) {
List<Integer> subjectIds = subjects.stream().map(ClassSubjectEntity::getId).collect(Collectors.toList()); List<Integer> subjectIds = subjects.stream().map(ClassSubjectEntity::getId).collect(Collectors.toList());
List<ClassSubjectAttendanceEntity> records = lock List<ClassSubjectAttendanceEntity> records = lock
...@@ -276,6 +287,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService { ...@@ -276,6 +287,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService {
} }
} }
/** 拒绝与本人现有待审批或已批准申请时间重叠的新申请。 */
private void ensureNoOverlappingApplication(LeaveApplyDTO request, String studentId, String excludeId) { private void ensureNoOverlappingApplication(LeaveApplyDTO request, String studentId, String excludeId) {
LambdaQueryWrapper<StudentLeaveApplicationEntity> wrapper = LambdaQueryWrapper<StudentLeaveApplicationEntity> wrapper =
new LambdaQueryWrapper<StudentLeaveApplicationEntity>() new LambdaQueryWrapper<StudentLeaveApplicationEntity>()
...@@ -292,6 +304,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService { ...@@ -292,6 +304,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService {
} }
} }
/** 保存请假申请自动匹配出的课程关联。 */
private void saveSubjectRelations(String leaveId, List<ClassSubjectEntity> subjects, Date now) { private void saveSubjectRelations(String leaveId, List<ClassSubjectEntity> subjects, Date now) {
for (ClassSubjectEntity subject : subjects) { for (ClassSubjectEntity subject : subjects) {
StudentLeaveSubjectEntity relation = new StudentLeaveSubjectEntity(); StudentLeaveSubjectEntity relation = new StudentLeaveSubjectEntity();
...@@ -303,6 +316,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService { ...@@ -303,6 +316,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService {
} }
} }
/** 去重、校验文件存在性后保存证明材料关联;不重复存储文件本体。 */
private void saveAttachmentRelations(String leaveId, List<Integer> attachmentFileIds, Date now) { private void saveAttachmentRelations(String leaveId, List<Integer> attachmentFileIds, Date now) {
if (attachmentFileIds == null || attachmentFileIds.isEmpty()) { if (attachmentFileIds == null || attachmentFileIds.isEmpty()) {
return; return;
...@@ -327,6 +341,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService { ...@@ -327,6 +341,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService {
} }
} }
/** 查询完整详情,并一次性装配课程和附件;不存在时抛出业务异常。 */
private LeaveApplicationVO requireDetail(String leaveId) { private LeaveApplicationVO requireDetail(String leaveId) {
if (isBlank(leaveId)) { if (isBlank(leaveId)) {
throw new BusinessException("请假申请ID不能为空"); throw new BusinessException("请假申请ID不能为空");
...@@ -340,6 +355,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService { ...@@ -340,6 +355,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService {
return applications.get(0); return applications.get(0);
} }
/** 使用SELECT FOR UPDATE读取申请,供修改、撤回和审批事务使用。 */
private StudentLeaveApplicationEntity requireLockedApplication(String leaveId) { private StudentLeaveApplicationEntity requireLockedApplication(String leaveId) {
if (isBlank(leaveId)) { if (isBlank(leaveId)) {
throw new BusinessException("请假申请ID不能为空"); throw new BusinessException("请假申请ID不能为空");
...@@ -351,6 +367,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService { ...@@ -351,6 +367,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService {
return application; return application;
} }
/** 校验申请属于当前学员且仍处于待审批状态。 */
private void requireOwnerAndPending(StudentLeaveApplicationEntity application, String studentId) { private void requireOwnerAndPending(StudentLeaveApplicationEntity application, String studentId) {
if (!studentId.equals(application.getStudentId())) { if (!studentId.equals(application.getStudentId())) {
throw new BusinessException("无权修改他人的请假申请"); throw new BusinessException("无权修改他人的请假申请");
...@@ -360,6 +377,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService { ...@@ -360,6 +377,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService {
} }
} }
/** 校验时间、类型、原因、联系人和附件数量等请假表单规则。 */
private void validateRequest(LeaveApplyDTO request) { private void validateRequest(LeaveApplyDTO request) {
if (request == null || request.getStartTime() == null || request.getEndTime() == null) { if (request == null || request.getStartTime() == null || request.getEndTime() == null) {
throw new BusinessException("请假开始时间和结束时间不能为空"); throw new BusinessException("请假开始时间和结束时间不能为空");
...@@ -401,10 +419,12 @@ public class LeaveManagementServiceImpl implements LeaveManagementService { ...@@ -401,10 +419,12 @@ public class LeaveManagementServiceImpl implements LeaveManagementService {
} }
} }
/** 使用左闭右开语义判断课程时间窗口与请假区间是否重叠。 */
private static boolean overlaps(ClassSubjectTimeUtils.TimeWindow window, Date start, Date end) { private static boolean overlaps(ClassSubjectTimeUtils.TimeWindow window, Date start, Date end) {
return window.getStart().before(end) && window.getEnd().after(start); return window.getStart().before(end) && window.getEnd().after(start);
} }
/** 返回指定日期的当天起点,用于缩小候选课程查询范围。 */
private static Date startOfDay(Date date) { private static Date startOfDay(Date date) {
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
calendar.setTime(date); calendar.setTime(date);
...@@ -415,6 +435,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService { ...@@ -415,6 +435,7 @@ public class LeaveManagementServiceImpl implements LeaveManagementService {
return calendar.getTime(); return calendar.getTime();
} }
/** 返回指定日期的当天终点,用于缩小候选课程查询范围。 */
private static Date endOfDay(Date date) { private static Date endOfDay(Date date) {
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
calendar.setTime(date); calendar.setTime(date);
...@@ -425,14 +446,17 @@ public class LeaveManagementServiceImpl implements LeaveManagementService { ...@@ -425,14 +446,17 @@ public class LeaveManagementServiceImpl implements LeaveManagementService {
return calendar.getTime(); return calendar.getTime();
} }
/** 去除空白并将请假类型规范化为大写。 */
private static String normalizeType(String type) { private static String normalizeType(String type) {
return type == null ? null : type.trim().toUpperCase(Locale.ROOT); return type == null ? null : type.trim().toUpperCase(Locale.ROOT);
} }
/** 将空白字符串转换为null,便于可选字段统一入库。 */
private static String trimToNull(String value) { private static String trimToNull(String value) {
return isBlank(value) ? null : value.trim(); return isBlank(value) ? null : value.trim();
} }
/** 判断字符串是否为空或仅包含空白。 */
private static boolean isBlank(String value) { private static boolean isBlank(String value) {
return value == null || value.trim().isEmpty(); return value == null || value.trim().isEmpty();
} }
......
package com.platform.business.service.impl;
import com.platform.business.mapper.NotificationAudienceMapper;
import com.platform.business.model.dto.NotificationEventDTO;
import com.platform.business.service.NotificationAudienceService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/** 默认接收范围解析器,使用LinkedHashSet同时实现稳定顺序和去重。 */
@Service
public class NotificationAudienceServiceImpl implements NotificationAudienceService {
@Resource
private NotificationAudienceMapper audienceMapper;
@Override
public List<String> resolve(NotificationEventDTO event) {
Set<String> result = new LinkedHashSet<>();
// 显式用户无需查库,但仍过滤空字符串。
if (!CollectionUtils.isEmpty(event.getRecipientUserIds())) {
event.getRecipientUserIds().stream().filter(this::hasText).forEach(result::add);
}
// 角色基于phone_role解析,可同时覆盖管理端、教师端和学员端。
if (!CollectionUtils.isEmpty(event.getRecipientRoleNames())) {
result.addAll(audienceMapper.selectUserIdsByRoleNames(event.getRecipientRoleNames()));
}
// 班级范围通过class_student解析为学员用户ID。
if (!CollectionUtils.isEmpty(event.getRecipientClassIds())) {
result.addAll(audienceMapper.selectUserIdsByClassIds(event.getRecipientClassIds()));
}
// broadcast为true时追加全部有效用户,Set会自动消除与前述范围重复的用户。
if (Boolean.TRUE.equals(event.getBroadcast())) {
result.addAll(audienceMapper.selectAllActiveUserIds());
}
return new ArrayList<>(result);
}
private boolean hasText(String value) {
return value != null && !value.trim().isEmpty();
}
}
package com.platform.business.service.impl;
import com.alibaba.fastjson2.JSON;
import com.platform.business.constant.NotificationConstants;
import com.platform.business.mapper.NotificationMessageMapper;
import com.platform.business.mapper.NotificationMessageRecipientMapper;
import com.platform.business.mapper.NotificationOutboxMapper;
import com.platform.business.model.dto.NotificationEventDTO;
import com.platform.business.model.dto.NotificationMessageQueryDTO;
import com.platform.business.model.dto.NotificationPublishDTO;
import com.platform.business.model.dto.NotificationPushDTO;
import com.platform.business.model.entity.NotificationMessageEntity;
import com.platform.business.model.entity.NotificationMessageRecipientEntity;
import com.platform.business.model.entity.NotificationOutboxEntity;
import com.platform.business.model.vo.NotificationMessageVO;
import com.platform.business.service.NotificationAudienceService;
import com.platform.business.service.NotificationMessageService;
import com.platform.business.service.NotificationPushDispatcher;
import com.platform.business.service.NotificationUnreadCache;
import com.platform.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.UUID;
/**
* 消息中心核心应用服务实现。
*
* <p>发布方向使用事务发件箱,消费方向使用eventId和接收人唯一键保证幂等;消息写库事务提交后才进行
* WebSocket在线推送,避免客户端收到通知后立即查询却读不到尚未提交的数据。</p>
*/
@Service
@Slf4j
public class NotificationMessageServiceImpl implements NotificationMessageService {
/** 对外允许的消息类型白名单,避免任意类型造成前端样式和路由不可控。 */
private static final Set<String> TYPES = new HashSet<>(Arrays.asList(
"SYSTEM", "EXAM", "SCORE", "LEAVE", "COURSE", "TEACHING_PLAN"));
/** 允许的优先级白名单。 */
private static final Set<String> PRIORITIES = new HashSet<>(Arrays.asList(
"NORMAL", "IMPORTANT", "URGENT"));
/** 单次接收人批量插入数量,控制SQL长度和数据库锁持有时间。 */
private static final int RECIPIENT_BATCH_SIZE = 300;
@Resource
private NotificationMessageMapper messageMapper;
@Resource
private NotificationMessageRecipientMapper recipientMapper;
@Resource
private NotificationOutboxMapper outboxMapper;
@Resource
private NotificationAudienceService audienceService;
@Resource
private NotificationPushDispatcher pushDispatcher;
@Resource
private NotificationUnreadCache unreadCache;
@Override
@Transactional(rollbackFor = Exception.class)
public String publish(NotificationPublishDTO request, String senderId, String senderName) {
// 先完成全部业务校验,防止无效消息进入发件箱后反复重试。
validatePublishRequest(request);
Date now = new Date();
// 将外部命令转换为稳定事件快照。发送人名称和接收范围均在此时固化。
NotificationEventDTO event = new NotificationEventDTO();
event.setEventId(hasText(request.getEventId()) ? request.getEventId().trim() : id());
event.setMessageType(request.getMessageType().trim().toUpperCase(Locale.ROOT));
event.setTitle(request.getTitle().trim());
event.setSummary(trimToNull(request.getSummary()));
event.setContent(request.getContent().trim());
event.setSenderId(senderId);
event.setSenderName(senderName);
event.setBusinessType(trimToNull(request.getBusinessType()));
event.setBusinessId(trimToNull(request.getBusinessId()));
event.setActionUrl(trimToNull(request.getActionUrl()));
event.setPriority(hasText(request.getPriority())
? request.getPriority().trim().toUpperCase(Locale.ROOT) : "NORMAL");
event.setRecipientUserIds(request.getRecipientUserIds());
event.setRecipientRoleNames(request.getRecipientRoleNames());
event.setRecipientClassIds(request.getRecipientClassIds());
event.setBroadcast(Boolean.TRUE.equals(request.getBroadcast()));
event.setCreatedAt(now);
event.setExpiresAt(request.getExpiresAt());
// 只向数据库写发件箱,不在业务请求线程中直接调用RabbitMQ。
NotificationOutboxEntity outbox = new NotificationOutboxEntity();
outbox.setId(id());
outbox.setEventId(event.getEventId());
outbox.setRoutingKey("notification." + event.getMessageType().toLowerCase(Locale.ROOT));
outbox.setPayload(JSON.toJSONString(event));
outbox.setStatus(NotificationConstants.OUTBOX_NEW);
outbox.setRetryCount(0);
// 空时间或过去时间按立即发布处理,未来时间由轮询任务到点后发布。
Date scheduledAt = request.getScheduledAt();
outbox.setScheduledAt(scheduledAt == null || scheduledAt.before(now) ? now : scheduledAt);
outbox.setCreatedAt(now);
outbox.setUpdatedAt(now);
outboxMapper.insert(outbox);
return event.getEventId();
}
@Override
@Transactional(rollbackFor = Exception.class)
public void consume(NotificationEventDTO event) {
if (event == null || !hasText(event.getEventId())) {
throw new IllegalArgumentException("消息事件缺少 eventId");
}
// insert ignore依赖event_id唯一索引:同一RabbitMQ消息重复投递不会生成重复正文。
NotificationMessageEntity message = toMessage(event);
messageMapper.insertIgnore(message);
// 无论本次是否实际插入,都重新读取数据库中的权威消息ID供接收人表关联。
NotificationMessageEntity persisted = messageMapper.selectByEventId(event.getEventId());
if (persisted == null) {
throw new IllegalStateException("消息正文持久化失败: " + event.getEventId());
}
// 用户、角色、班级和全员范围在解析服务中合并去重。
List<String> userIds = audienceService.resolve(event);
if (CollectionUtils.isEmpty(userIds)) {
throw new IllegalArgumentException("消息事件没有有效接收人: " + event.getEventId());
}
Date now = new Date();
// 1000人广播按固定大小分批写入,避免生成一条过大的INSERT语句。
for (int from = 0; from < userIds.size(); from += RECIPIENT_BATCH_SIZE) {
int to = Math.min(from + RECIPIENT_BATCH_SIZE, userIds.size());
recipientMapper.insertBatchIgnore(toRecipients(persisted.getId(), userIds.subList(from, to), now));
}
NotificationPushDTO push = toPush(persisted);
// 缓存失效与推送必须都在事务提交后执行:客户端收到事件后查询到的一定是已提交的新数量。
runAfterCommit(() -> {
userIds.forEach(unreadCache::evict);
pushDispatcher.dispatch(userIds, push);
});
}
@Override
public List<NotificationMessageVO> query(NotificationMessageQueryDTO query) {
query.setReadStatus(normalizeReadStatus(query.getReadStatus()));
return messageMapper.queryUserMessages(query);
}
@Override
@Transactional(rollbackFor = Exception.class)
public NotificationMessageVO detailAndMarkRead(String messageId, String userId) {
// 查询语句同时限定messageId和userId,不能仅凭公开的消息ID读取其他用户消息。
NotificationMessageVO message = messageMapper.selectUserMessage(messageId, userId);
if (message == null) {
throw new BusinessException("消息不存在或已删除");
}
// read_at使用coalesce保留首次阅读时间,重复打开详情不会篡改审计时间。
int changed = recipientMapper.markRead(messageId, userId, new Date());
if (changed > 0) {
synchronizeUnreadCountAfterCommit(userId, "MARK_READ");
}
return messageMapper.selectUserMessage(messageId, userId);
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean markRead(String messageId, String userId) {
int changed = recipientMapper.markRead(messageId, userId, new Date());
if (changed > 0) {
synchronizeUnreadCountAfterCommit(userId, "MARK_READ");
}
return changed > 0;
}
@Override
@Transactional(rollbackFor = Exception.class)
public int markAllRead(String userId) {
int changed = recipientMapper.markAllRead(userId, new Date());
if (changed > 0) {
synchronizeUnreadCountAfterCommit(userId, "MARK_ALL_READ");
}
return changed;
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean delete(String messageId, String userId) {
int changed = recipientMapper.logicalDelete(messageId, userId, new Date());
if (changed > 0) {
synchronizeUnreadCountAfterCommit(userId, "DELETE");
}
return changed > 0;
}
@Override
@Transactional(rollbackFor = Exception.class)
public int clearRead(String userId) {
int changed = recipientMapper.clearRead(userId, new Date());
if (changed > 0) {
synchronizeUnreadCountAfterCommit(userId, "CLEAR_READ");
}
return changed;
}
@Override
public long unreadCount(String userId) {
return unreadCache.get(userId, () -> recipientMapper.unreadCount(userId));
}
private NotificationMessageEntity toMessage(NotificationEventDTO event) {
// 正文主键与eventId分离:eventId用于跨系统幂等,主键用于本系统表关联。
NotificationMessageEntity message = new NotificationMessageEntity();
message.setId(id());
message.setEventId(event.getEventId());
message.setMessageType(event.getMessageType());
message.setTitle(event.getTitle());
message.setSummary(event.getSummary());
message.setContent(event.getContent());
message.setSenderId(event.getSenderId());
message.setSenderName(event.getSenderName());
message.setBusinessType(event.getBusinessType());
message.setBusinessId(event.getBusinessId());
message.setActionUrl(event.getActionUrl());
message.setPriority(hasText(event.getPriority()) ? event.getPriority() : "NORMAL");
message.setCreatedAt(event.getCreatedAt() == null ? new Date() : event.getCreatedAt());
message.setExpiresAt(event.getExpiresAt());
return message;
}
private List<NotificationMessageRecipientEntity> toRecipients(String messageId, List<String> userIds, Date now) {
List<NotificationMessageRecipientEntity> recipients = new ArrayList<>(userIds.size());
for (String userId : userIds) {
NotificationMessageRecipientEntity recipient = new NotificationMessageRecipientEntity();
recipient.setId(id());
recipient.setMessageId(messageId);
recipient.setUserId(userId);
recipient.setReadFlag(false);
recipient.setDeletedFlag(false);
recipient.setCreatedAt(now);
recipients.add(recipient);
}
return recipients;
}
private NotificationPushDTO toPush(NotificationMessageEntity message) {
// 实时通道只携带弹窗所需字段,完整正文通过带鉴权的HTTP详情接口读取。
NotificationPushDTO push = new NotificationPushDTO();
push.setEventType("NOTIFICATION");
push.setMessageId(message.getId());
push.setMessageType(message.getMessageType());
push.setTitle(message.getTitle());
push.setSummary(message.getSummary());
push.setPriority(message.getPriority());
push.setActionUrl(message.getActionUrl());
push.setCreatedAt(message.getCreatedAt());
// 新消息弹窗和未读角标使用同一个WebSocket事件触发,避免二者出现可见时间差。
push.setRefreshUnreadCount(true);
push.setChangeType("NEW_MESSAGE");
return push;
}
/**
* 在用户消息状态提交后,使未读缓存失效并通知该用户的全部在线连接重新查询权威数量。
*
* <p>WebSocket事件不直接携带本地计算的+1/-1,也不携带可能因并发而过期的绝对数量;
* 浏览器收到信号后调用未读数接口,可以同时覆盖多消息并发、多标签页和多设备操作。</p>
*/
private void synchronizeUnreadCountAfterCommit(String userId, String changeType) {
NotificationPushDTO push = new NotificationPushDTO();
push.setEventType("UNREAD_COUNT_CHANGED");
push.setRefreshUnreadCount(true);
push.setChangeType(changeType);
runAfterCommit(() -> {
// 先删除旧缓存,再发送刷新事件,保证客户端随后的HTTP查询不会读到事务前数据。
unreadCache.evict(userId);
pushDispatcher.dispatch(Collections.singletonList(userId), push);
});
}
/**
* 在当前Spring事务成功提交后执行动作;没有活动事务时立即执行,便于内部复用和单元测试。
* 回滚事务不会触发afterCommit,因此客户端不会收到与数据库状态不一致的数量变化事件。
*/
private void runAfterCommit(Runnable action) {
if (TransactionSynchronizationManager.isActualTransactionActive()
&& TransactionSynchronizationManager.isSynchronizationActive()) {
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCommit() {
action.run();
}
});
return;
}
action.run();
}
private void validatePublishRequest(NotificationPublishDTO request) {
if (request == null || !hasText(request.getMessageType()) || !TYPES.contains(request.getMessageType().trim().toUpperCase(Locale.ROOT))) {
throw new BusinessException("消息类型不正确");
}
if (!hasText(request.getTitle()) || request.getTitle().trim().length() > 200) {
throw new BusinessException("消息标题不能为空且不能超过200个字符");
}
if (!hasText(request.getContent())) {
throw new BusinessException("消息正文不能为空");
}
String priority = hasText(request.getPriority()) ? request.getPriority().trim().toUpperCase(Locale.ROOT) : "NORMAL";
if (!PRIORITIES.contains(priority)) {
throw new BusinessException("消息优先级不正确");
}
// 接收范围可以组合,但不能全部为空,否则消息永远不会对任何用户可见。
boolean noAudience = CollectionUtils.isEmpty(request.getRecipientUserIds())
&& CollectionUtils.isEmpty(request.getRecipientRoleNames())
&& CollectionUtils.isEmpty(request.getRecipientClassIds())
&& !Boolean.TRUE.equals(request.getBroadcast());
if (noAudience) {
throw new BusinessException("至少选择一种消息接收范围");
}
if (request.getExpiresAt() != null && request.getScheduledAt() != null
&& !request.getExpiresAt().after(request.getScheduledAt())) {
throw new BusinessException("消息过期时间必须晚于发布时间");
}
}
private String normalizeReadStatus(String value) {
// 对未知值安全降级为ALL,避免动态SQL出现未定义分支。
if (!hasText(value)) {
return "ALL";
}
String status = value.trim().toUpperCase(Locale.ROOT);
return "READ".equals(status) || "UNREAD".equals(status) ? status : "ALL";
}
private String trimToNull(String value) {
return hasText(value) ? value.trim() : null;
}
private boolean hasText(String value) {
return value != null && !value.trim().isEmpty();
}
private String id() {
return UUID.randomUUID().toString().replace("-", "");
}
}
package com.platform.business.service.impl;
import com.platform.business.constant.NotificationConstants;
import com.platform.business.duplex.NotificationWebSocketServer;
import com.platform.business.model.dto.NotificationPushDTO;
import com.platform.business.service.NotificationNodeIdentity;
import com.platform.business.service.NotificationPresenceService;
import com.platform.business.service.NotificationPushDispatcher;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* RabbitMQ在线推送路由器。
*
* <p>先根据Redis在线目录将接收人按节点分组,再为每个节点发送一个批量报文。
* 队列数量与应用实例数相关,而不是与用户数相关,避免1000名在线用户产生1000个RabbitMQ队列。</p>
*/
@Service
@Slf4j
public class RabbitNotificationPushDispatcher implements NotificationPushDispatcher {
@Resource
private RabbitTemplate rabbitTemplate;
@Resource
private NotificationPresenceService presenceService;
@Resource
private NotificationNodeIdentity nodeIdentity;
@Override
public void dispatch(List<String> userIds, NotificationPushDTO push) {
Map<String, List<String>> usersByNode = new HashMap<>();
for (String userId : userIds) {
// 一个用户可能在多个设备上连接到不同节点,因此一个用户可以出现在多个节点批次中。
Set<String> nodes = presenceService.findNodeIds(userId);
if (nodes.isEmpty() && NotificationWebSocketServer.isLocalUserOnline(userId)) {
// Redis短暂不可用时保留本机推送能力;跨节点推送则安全降级为离线补拉。
nodes = Collections.singleton(nodeIdentity.getNodeId());
}
for (String node : nodes) {
usersByNode.computeIfAbsent(node, ignored -> new ArrayList<>()).add(userId);
}
}
usersByNode.forEach((node, nodeUsers) -> {
// 每个节点必须使用独立DTO,避免并发发送时userIds被后续循环覆盖。
NotificationPushDTO batch = copy(push);
batch.setUserIds(nodeUsers);
try {
rabbitTemplate.convertAndSend(NotificationConstants.PUSH_EXCHANGE, node, batch);
} catch (RuntimeException e) {
// 实时推送允许降级;消息已持久化,客户端重连后仍可补拉。
log.warn("发送节点实时推送失败: node={}, messageId={}, error={}",
node, push.getMessageId(), e.getMessage());
}
});
}
private NotificationPushDTO copy(NotificationPushDTO source) {
// 显式复制稳定字段,避免把未来新增的内部寻址字段意外发送给浏览器。
NotificationPushDTO target = new NotificationPushDTO();
target.setEventType(source.getEventType());
target.setMessageId(source.getMessageId());
target.setMessageType(source.getMessageType());
target.setTitle(source.getTitle());
target.setSummary(source.getSummary());
target.setPriority(source.getPriority());
target.setActionUrl(source.getActionUrl());
target.setCreatedAt(source.getCreatedAt());
// 数量同步标记必须随节点报文透传,否则其他实例上的标签页不会刷新角标。
target.setRefreshUnreadCount(source.getRefreshUnreadCount());
target.setChangeType(source.getChangeType());
return target;
}
}
...@@ -6,13 +6,17 @@ import org.springframework.stereotype.Component; ...@@ -6,13 +6,17 @@ import org.springframework.stereotype.Component;
import javax.annotation.Resource; import javax.annotation.Resource;
/** 定时关闭已结束课程并补齐缺勤记录,保证统计数据最终完整。 */
@Component @Component
public class AttendanceAutoCloseTask { public class AttendanceAutoCloseTask {
@Resource @Resource
private AttendanceService attendanceService; private AttendanceService attendanceService;
/** 每分钟将已结束课程中仍无签到记录的学员自动记为缺勤。 */ /**
* 每分钟扫描当天课程,将已结束且仍无签到或请假记录的学员自动记为缺勤。
* 插入使用唯一索引幂等保护,不会覆盖正常、迟到或请假状态。
*/
@Scheduled(cron = "0 * * * * ?") @Scheduled(cron = "0 * * * * ?")
public void closeEndedSubjects() { public void closeEndedSubjects() {
attendanceService.finalizeEndedSubjects(null, null); attendanceService.finalizeEndedSubjects(null, null);
......
package com.platform.business.task;
import com.alibaba.fastjson2.JSON;
import com.platform.business.constant.NotificationConstants;
import com.platform.business.mapper.NotificationOutboxMapper;
import com.platform.business.model.dto.NotificationEventDTO;
import com.platform.business.model.entity.NotificationOutboxEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* 事务发件箱发布器。
*
* <p>状态流转为NEW/RETRY → PUBLISHING → PUBLISHED。多个服务实例可以同时扫描候选记录,
* 但只有成功执行条件更新的实例获得发布权;进程在PUBLISHING状态崩溃时,记录会在60秒后自动恢复。</p>
*/
@Component
@Slf4j
public class NotificationOutboxPublishTask {
/** 连续失败8次后转为FAILED,保留数据库记录供人工补偿。 */
private static final int MAX_ATTEMPTS = 8;
@Resource
private NotificationOutboxMapper outboxMapper;
@Resource
private RabbitTemplate rabbitTemplate;
@Scheduled(initialDelayString = "${notification.outbox.initial-delay-millis:5000}",
fixedDelayString = "${notification.outbox.poll-interval-millis:1000}")
public void publishDueEvents() {
Date now = new Date();
// 先恢复上次进程异常中断留下的PUBLISHING记录,再读取本轮候选数据。
outboxMapper.recoverStuck(addSeconds(now, -60), now);
// 每轮最多50条,防止大量积压时一个调度线程长期占用数据库和RabbitMQ连接。
List<NotificationOutboxEntity> due = outboxMapper.selectDue(now, 50);
for (NotificationOutboxEntity outbox : due) {
// claim是原子条件更新,返回0说明该记录已被其他实例抢占。
if (outboxMapper.claim(outbox.getId(), new Date()) != 1) {
continue;
}
publishOne(outbox);
}
}
private void publishOne(NotificationOutboxEntity outbox) {
try {
NotificationEventDTO event = JSON.parseObject(outbox.getPayload(), NotificationEventDTO.class);
// invoke提供独占Rabbit Channel,使waitForConfirms只等待本次作用域内发布的消息。
Boolean confirmed = rabbitTemplate.invoke(operations -> {
operations.convertAndSend(NotificationConstants.EVENT_EXCHANGE, outbox.getRoutingKey(), event,
new CorrelationData(outbox.getEventId()));
return operations.waitForConfirms(5_000L);
});
if (!Boolean.TRUE.equals(confirmed)) {
throw new IllegalStateException("RabbitMQ 未确认消息");
}
// 只有Broker确认接收后才能标记PUBLISHED,网络超时会保持可重试状态。
outboxMapper.markPublished(outbox.getId(), new Date());
} catch (Exception e) {
int retryCount = (outbox.getRetryCount() == null ? 0 : outbox.getRetryCount()) + 1;
boolean failed = retryCount >= MAX_ATTEMPTS;
// 采用5、10、20、40……秒指数退避,最高等待5分钟,避免中间件故障时持续施压。
long delaySeconds = Math.min(300L, 5L * (1L << Math.min(retryCount - 1, 6)));
String error = e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage();
if (error.length() > 1000) {
error = error.substring(0, 1000);
}
outboxMapper.markRetry(outbox.getId(), retryCount, addSeconds(new Date(), delaySeconds),
error, failed, new Date());
log.warn("发布消息发件箱失败: eventId={}, retry={}, failed={}, error={}",
outbox.getEventId(), retryCount, failed, error);
}
}
private Date addSeconds(Date value, long seconds) {
// 项目基线为Java 8且实体统一使用java.util.Date,这里保持相同时间类型。
Calendar calendar = Calendar.getInstance();
calendar.setTime(value);
calendar.add(Calendar.SECOND, (int) seconds);
return calendar.getTime();
}
}
package com.platform.business.task;
import com.platform.business.duplex.NotificationWebSocketServer;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* 消息WebSocket心跳任务。
*
* <p>默认每30秒发送协议层Ping,同时刷新Redis在线目录;连续失效的连接会在节点本地被回收,
* 实例突然宕机留下的Redis记录则由120秒TTL自动清除。</p>
*/
@Component
public class NotificationWebSocketHeartbeatTask {
@Scheduled(initialDelayString = "${notification.websocket.heartbeat-millis:30000}",
fixedDelayString = "${notification.websocket.heartbeat-millis:30000}")
public void heartbeat() {
NotificationWebSocketServer.heartbeatAll();
}
}
...@@ -12,6 +12,7 @@ import java.time.format.DateTimeFormatter; ...@@ -12,6 +12,7 @@ import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException; import java.time.format.DateTimeParseException;
import java.util.Date; import java.util.Date;
/** 将课程日期和timeFrame文本解析成可比较的计划开始、结束时间。 */
public final class ClassSubjectTimeUtils { public final class ClassSubjectTimeUtils {
private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("H:mm"); private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("H:mm");
...@@ -19,6 +20,10 @@ public final class ClassSubjectTimeUtils { ...@@ -19,6 +20,10 @@ public final class ClassSubjectTimeUtils {
private ClassSubjectTimeUtils() { private ClassSubjectTimeUtils() {
} }
/**
* 解析课程完整时间范围。
* 多段时段取最早开始和最晚结束,例如09:00-10:00,10:30-12:00解析为09:00-12:00。
*/
public static TimeWindow resolve(ClassSubjectEntity subject) { public static TimeWindow resolve(ClassSubjectEntity subject) {
if (subject == null || subject.getDate() == null || subject.getTimeFrame() == null if (subject == null || subject.getDate() == null || subject.getTimeFrame() == null
|| subject.getTimeFrame().trim().isEmpty()) { || subject.getTimeFrame().trim().isEmpty()) {
...@@ -59,8 +64,11 @@ public final class ClassSubjectTimeUtils { ...@@ -59,8 +64,11 @@ public final class ClassSubjectTimeUtils {
Date.from(LocalDateTime.of(date, latest).atZone(zone).toInstant())); Date.from(LocalDateTime.of(date, latest).atZone(zone).toInstant()));
} }
/** 不可变的课程计划时间窗口。 */
public static final class TimeWindow { public static final class TimeWindow {
/** 计划开始时间。 */
private final Date start; private final Date start;
/** 计划结束时间。 */
private final Date end; private final Date end;
private TimeWindow(Date start, Date end) { private TimeWindow(Date start, Date end) {
...@@ -68,10 +76,12 @@ public final class ClassSubjectTimeUtils { ...@@ -68,10 +76,12 @@ public final class ClassSubjectTimeUtils {
this.end = end; this.end = end;
} }
/** 返回计划开始时间。 */
public Date getStart() { public Date getStart() {
return start; return start;
} }
/** 返回计划结束时间。 */
public Date getEnd() { public Date getEnd() {
return end; return end;
} }
......
...@@ -10,6 +10,7 @@ public final class IpNetworkMatcher { ...@@ -10,6 +10,7 @@ public final class IpNetworkMatcher {
private IpNetworkMatcher() { private IpNetworkMatcher() {
} }
/** 判断客户端IPv4地址是否命中任一允许网段;网段未配置时按安全策略拒绝签到。 */
public static boolean matchesAny(String ip, List<String> cidrs) { public static boolean matchesAny(String ip, List<String> cidrs) {
if (cidrs == null || cidrs.isEmpty()) { if (cidrs == null || cidrs.isEmpty()) {
throw new BusinessException("签到允许网段尚未配置"); throw new BusinessException("签到允许网段尚未配置");
...@@ -26,6 +27,7 @@ public final class IpNetworkMatcher { ...@@ -26,6 +27,7 @@ public final class IpNetworkMatcher {
return false; return false;
} }
/** 使用32位整数和CIDR掩码进行匹配,不触发DNS解析。 */
private static boolean matches(long ipValue, String cidr) { private static boolean matches(long ipValue, String cidr) {
String[] parts = cidr.split("/", -1); String[] parts = cidr.split("/", -1);
long network = parseIpv4(parts[0]); long network = parseIpv4(parts[0]);
...@@ -34,6 +36,7 @@ public final class IpNetworkMatcher { ...@@ -34,6 +36,7 @@ public final class IpNetworkMatcher {
return (ipValue & mask) == (network & mask); return (ipValue & mask) == (network & mask);
} }
/** 校验并解析CIDR前缀长度,合法范围为0至32。 */
private static int parsePrefix(String value) { private static int parsePrefix(String value) {
try { try {
int prefix = Integer.parseInt(value); int prefix = Integer.parseInt(value);
...@@ -46,6 +49,7 @@ public final class IpNetworkMatcher { ...@@ -46,6 +49,7 @@ public final class IpNetworkMatcher {
} }
} }
/** 将严格的点分十进制IPv4地址转换为无符号32位数值。 */
private static long parseIpv4(String ip) { private static long parseIpv4(String ip) {
if (ip == null) { if (ip == null) {
throw new BusinessException("无法获取签到IP地址"); throw new BusinessException("无法获取签到IP地址");
......
spring: spring:
profiles: profiles:
active: dev active: dev
# RabbitMQ只保存事件和实时提示,消息正文及用户状态仍以MySQL为最终数据源。
rabbitmq:
host: ${RABBITMQ_HOST:127.0.0.1}
port: ${RABBITMQ_PORT:5672}
username: ${RABBITMQ_USERNAME:guest}
password: ${RABBITMQ_PASSWORD:guest}
virtual-host: ${RABBITMQ_VHOST:/}
publisher-confirm-type: correlated
publisher-returns: true
template:
mandatory: true
listener:
simple:
# 1000人在线基线下2~4个消费者足够;prefetch限制单消费者未确认消息数量。
concurrency: 2
max-concurrency: 4
prefetch: 50
acknowledge-mode: auto
default-requeue-rejected: true
# Redis故障时消息列表和未读数可回源MySQL,但新WebSocket票据无法签发。
redis:
host: ${REDIS_HOST:127.0.0.1}
port: ${REDIS_PORT:6379}
password: ${REDIS_PASSWORD:}
database: ${REDIS_DATABASE:0}
timeout: 2s
servlet: servlet:
multipart: multipart:
max-file-size: 500MB max-file-size: 500MB
...@@ -12,3 +38,16 @@ attendance: ...@@ -12,3 +38,16 @@ attendance:
allowed-ip-cidrs: [] allowed-ip-cidrs: []
# 只有网关已清洗 X-Forwarded-For / X-Real-IP 时才开启。 # 只有网关已清洗 X-Forwarded-For / X-Real-IP 时才开启。
trust-forwarded-headers: false trust-forwarded-headers: false
# 消息中心以 1000 人同时在线为基线;node-id 不配置时会按应用名、主机名和随机后缀生成。
notification:
# 多实例不可配置相同node-id,否则会争用同一个exclusive推送队列。
node-id: ${NOTIFICATION_NODE_ID:}
websocket:
# ticket短时且一次性;presence TTL应明显大于heartbeat周期。
ticket-ttl-seconds: 60
presence-ttl-seconds: 120
heartbeat-millis: 30000
outbox:
initial-delay-millis: 5000
poll-interval-millis: 1000
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.platform.business.mapper.ClassSubjectAttendanceMapper"> <mapper namespace="com.platform.business.mapper.ClassSubjectAttendanceMapper">
<!-- 并发签到幂等插入;课程+学员唯一索引冲突时忽略。 -->
<insert id="insertIgnore"> <insert id="insertIgnore">
insert ignore into class_subject_attendance insert ignore into class_subject_attendance
(id, subject_id, user_id, check_in_time, status, check_in_method, check_in_ip, (id, subject_id, user_id, check_in_time, status, check_in_method, check_in_ip,
...@@ -12,6 +13,7 @@ ...@@ -12,6 +13,7 @@
#{teacherConfirmed}, #{confirmedBy}, #{confirmedAt}, #{createdTime}, #{updateTime}) #{teacherConfirmed}, #{confirmedBy}, #{confirmedAt}, #{createdTime}, #{updateTime})
</insert> </insert>
<!-- 课程结束后批量补写缺勤,已有签到或请假记录时不覆盖。 -->
<insert id="insertAbsencesIgnore"> <insert id="insertAbsencesIgnore">
insert ignore into class_subject_attendance insert ignore into class_subject_attendance
(id, subject_id, user_id, check_in_time, status, check_in_method, check_in_ip, (id, subject_id, user_id, check_in_time, status, check_in_method, check_in_ip,
...@@ -24,6 +26,7 @@ ...@@ -24,6 +26,7 @@
</foreach> </foreach>
</insert> </insert>
<!-- 教师手动点名;CASE分支在数据库层保护LEAVE不被并发覆盖。 -->
<insert id="upsertTeacherStatus"> <insert id="upsertTeacherStatus">
insert into class_subject_attendance insert into class_subject_attendance
(id, subject_id, user_id, check_in_time, status, check_in_method, check_in_ip, (id, subject_id, user_id, check_in_time, status, check_in_method, check_in_ip,
...@@ -50,6 +53,7 @@ ...@@ -50,6 +53,7 @@
then class_subject_attendance.status else values(status) end then class_subject_attendance.status else values(status) end
</insert> </insert>
<!-- 请假审批前锁定关联课程出勤记录,协调审批与签到并发。 -->
<select id="lockRecords" resultType="com.platform.business.model.entity.ClassSubjectAttendanceEntity"> <select id="lockRecords" resultType="com.platform.business.model.entity.ClassSubjectAttendanceEntity">
select a.* select a.*
from class_subject_attendance a from class_subject_attendance a
...@@ -61,6 +65,7 @@ ...@@ -61,6 +65,7 @@
for update for update
</select> </select>
<!-- 审批通过后批量写LEAVE;已存在NORMAL/LATE时保留签到结果并由业务层回滚审批。 -->
<insert id="upsertLeaveStatuses"> <insert id="upsertLeaveStatuses">
insert into class_subject_attendance insert into class_subject_attendance
(id, subject_id, user_id, check_in_time, status, check_in_method, check_in_ip, (id, subject_id, user_id, check_in_time, status, check_in_method, check_in_ip,
...@@ -118,6 +123,7 @@ ...@@ -118,6 +123,7 @@
s.date between #{startDate} and #{endDate} s.date between #{startDate} and #{endDate}
</select> </select>
<!-- 查询三端共用的出勤明细,学员和教师手机号均完整返回。 -->
<select id="queryRecords" resultType="com.platform.business.model.vo.AttendanceRecordVO"> <select id="queryRecords" resultType="com.platform.business.model.vo.AttendanceRecordVO">
select select
a.id, a.id,
...@@ -155,6 +161,7 @@ ...@@ -155,6 +161,7 @@
order by s.date desc, s.time_frame desc, student.nick_name asc order by s.date desc, s.time_frame desc, student.nick_name asc
</select> </select>
<!-- 从班级成员生成完整点名册,无出勤记录时展示PENDING。 -->
<select id="queryTeacherRoster" resultType="com.platform.business.model.vo.AttendanceRecordVO"> <select id="queryTeacherRoster" resultType="com.platform.business.model.vo.AttendanceRecordVO">
select select
a.id, a.id,
...@@ -186,6 +193,7 @@ ...@@ -186,6 +193,7 @@
order by student.nick_name asc, student.phone_number asc order by student.nick_name asc, student.phone_number asc
</select> </select>
<!-- 请假计入应出勤分母,但只有NORMAL和LATE计入出勤率分子。 -->
<select id="querySummary" resultType="com.platform.business.model.vo.AttendanceSummaryVO"> <select id="querySummary" resultType="com.platform.business.model.vo.AttendanceSummaryVO">
select select
count(a.id) as requiredCount, count(a.id) as requiredCount,
...@@ -208,6 +216,7 @@ ...@@ -208,6 +216,7 @@
</where> </where>
</select> </select>
<!-- 按学员汇总,使用与总览相同的出勤率口径。 -->
<select id="queryStudentStatistics" resultType="com.platform.business.model.vo.AttendanceStudentStatisticsVO"> <select id="queryStudentStatistics" resultType="com.platform.business.model.vo.AttendanceStudentStatisticsVO">
select select
a.user_id as studentId, a.user_id as studentId,
...@@ -234,6 +243,7 @@ ...@@ -234,6 +243,7 @@
order by attendanceRate desc, student.nick_name asc order by attendanceRate desc, student.nick_name asc
</select> </select>
<!-- 按课程汇总,返回授课教师完整手机号。 -->
<select id="queryCourseStatistics" resultType="com.platform.business.model.vo.AttendanceCourseStatisticsVO"> <select id="queryCourseStatistics" resultType="com.platform.business.model.vo.AttendanceCourseStatisticsVO">
select select
s.id as subjectId, s.id as subjectId,
......
<?xml version="1.0" encoding="UTF-8"?> <?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"> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.platform.business.mapper.ClassSubjectAttendanceSessionMapper"> <mapper namespace="com.platform.business.mapper.ClassSubjectAttendanceSessionMapper">
<!-- 课程唯一索引保证同一课次只能生成一次签到会话和验证码。 -->
<insert id="insertIgnore"> <insert id="insertIgnore">
insert ignore into class_subject_attendance_session insert ignore into class_subject_attendance_session
(id, subject_id, teacher_id, verification_code, scheduled_start_time, scheduled_end_time, (id, subject_id, teacher_id, verification_code, scheduled_start_time, scheduled_end_time,
......
<?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.NotificationAudienceMapper">
<!-- 全员广播只包含未逻辑删除用户。 -->
<select id="selectAllActiveUserIds" resultType="java.lang.String">
select id from user where del_flag = 0 or del_flag is null
</select>
<!-- 项目角色通过用户手机号与phone_role关联,distinct避免一人多条相同角色记录。 -->
<select id="selectUserIdsByRoleNames" resultType="java.lang.String">
select distinct u.id
from user u
inner join phone_role pr on pr.phone = u.phone_number
where (u.del_flag = 0 or u.del_flag is null) and pr.role_name in
<foreach collection="roleNames" item="roleName" open="(" separator="," close=")">#{roleName}</foreach>
</select>
<!-- 班级范围解析为学员用户ID;跨班学员由服务层LinkedHashSet再次去重。 -->
<select id="selectUserIdsByClassIds" resultType="java.lang.String">
select distinct u.id
from user u
inner join class_student cs on cs.user_id = u.id
where (u.del_flag = 0 or u.del_flag is null) and cs.class_id in
<foreach collection="classIds" item="classId" open="(" separator="," close=")">#{classId}</foreach>
</select>
</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.NotificationMessageMapper">
<!--
event_id具有唯一索引。insert ignore使RabbitMQ至少一次投递产生的重复事件安全返回,
随后服务层会按event_id读取首次插入的权威消息记录。
-->
<insert id="insertIgnore">
insert ignore into notification_message
(id, event_id, message_type, title, summary, content, sender_id, sender_name,
business_type, business_id, action_url, priority, created_at, expires_at)
values
(#{id}, #{eventId}, #{messageType}, #{title}, #{summary}, #{content}, #{senderId}, #{senderName},
#{businessType}, #{businessId}, #{actionUrl}, #{priority}, #{createdAt}, #{expiresAt})
</insert>
<select id="selectByEventId" resultType="com.platform.business.model.entity.NotificationMessageEntity">
select * from notification_message where event_id = #{eventId} limit 1
</select>
<!-- 列表和详情复用同一字段映射,避免两个接口的命名或时间字段不一致。 -->
<sql id="userMessageColumns">
m.id, m.event_id as eventId, m.message_type as messageType, m.title, m.summary, m.content,
m.sender_id as senderId, m.sender_name as senderName, m.business_type as businessType,
m.business_id as businessId, m.action_url as actionUrl, m.priority,
r.read_flag as readFlag, r.read_at as readAt, m.created_at as createdAt, m.expires_at as expiresAt
</sql>
<!--
user_id和deleted_flag构成用户数据隔离条件;expires_at在查询时动态判断,
无需定时物理删除消息即可让过期消息停止展示。
-->
<select id="queryUserMessages" resultType="com.platform.business.model.vo.NotificationMessageVO">
select <include refid="userMessageColumns"/>
from notification_message_recipient r
inner join notification_message m on m.id = r.message_id
where r.user_id = #{userId}
and r.deleted_flag = 0
and (m.expires_at is null or m.expires_at &gt; now())
<if test="readStatus == 'READ'">and r.read_flag = 1</if>
<if test="readStatus == 'UNREAD'">and r.read_flag = 0</if>
<if test="messageType != null and messageType != ''">and m.message_type = #{messageType}</if>
<if test="keyword != null and keyword != ''">
and (m.title like concat('%', #{keyword}, '%') or m.summary like concat('%', #{keyword}, '%'))
</if>
<!-- 同一时间范围内优先展示紧急消息,再按创建时间倒序。 -->
order by case m.priority when 'URGENT' then 0 when 'IMPORTANT' then 1 else 2 end,
m.created_at desc
</select>
<!-- message_id必须和当前user_id同时命中,避免仅凭消息ID越权查看公共正文。 -->
<select id="selectUserMessage" resultType="com.platform.business.model.vo.NotificationMessageVO">
select <include refid="userMessageColumns"/>
from notification_message_recipient r
inner join notification_message m on m.id = r.message_id
where r.user_id = #{userId} and r.message_id = #{messageId} and r.deleted_flag = 0
and (m.expires_at is null or m.expires_at &gt; now())
limit 1
</select>
</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.NotificationMessageRecipientMapper">
<!-- message_id + user_id唯一索引配合insert ignore实现接收人幂等。 -->
<insert id="insertBatchIgnore">
insert ignore into notification_message_recipient
(id, message_id, user_id, read_flag, deleted_flag, created_at)
values
<foreach collection="recipients" item="item" separator=",">
(#{item.id}, #{item.messageId}, #{item.userId}, 0, 0, #{item.createdAt})
</foreach>
</insert>
<!-- coalesce保留首次阅读时间,重复打开详情不会覆盖read_at。 -->
<update id="markRead">
update notification_message_recipient
set read_flag = 1, read_at = coalesce(read_at, #{now})
where message_id = #{messageId} and user_id = #{userId}
and deleted_flag = 0 and read_flag = 0
</update>
<update id="markAllRead">
update notification_message_recipient
set read_flag = 1, read_at = coalesce(read_at, #{now})
where user_id = #{userId} and deleted_flag = 0 and read_flag = 0
</update>
<!-- 删除只更新当前用户状态,不删除共享正文,也不影响其他接收人。 -->
<update id="logicalDelete">
update notification_message_recipient
set deleted_flag = 1, deleted_at = #{now}
where message_id = #{messageId} and user_id = #{userId} and deleted_flag = 0
</update>
<update id="clearRead">
update notification_message_recipient
set deleted_flag = 1, deleted_at = #{now}
where user_id = #{userId} and deleted_flag = 0 and read_flag = 1
</update>
<!-- 未读数排除用户已删除和已经过期的消息,与列表口径保持一致。 -->
<select id="unreadCount" resultType="java.lang.Long">
select count(1)
from notification_message_recipient r
inner join notification_message m on m.id = r.message_id
where r.user_id = #{userId} and r.deleted_flag = 0 and r.read_flag = 0
and (m.expires_at is null or m.expires_at &gt; now())
</select>
<!-- delivered_at表示已进入至少一个本地WebSocket异步发送队列,不表示用户已读。 -->
<update id="markDelivered">
update notification_message_recipient
set delivered_at = coalesce(delivered_at, #{now})
where message_id = #{messageId} and user_id in
<foreach collection="userIds" item="userId" open="(" separator="," close=")">#{userId}</foreach>
</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.NotificationOutboxMapper">
<!--
候选查询允许多实例读到相同行,真正的发布权由后续claim条件更新决定,
因而无需使用长事务或select for update锁住扫描结果。
-->
<select id="selectDue" resultType="com.platform.business.model.entity.NotificationOutboxEntity">
select *
from notification_outbox
where status in ('NEW', 'RETRY')
and scheduled_at &lt;= #{now}
and (next_retry_at is null or next_retry_at &lt;= #{now})
order by scheduled_at, created_at
limit #{limit}
</select>
<!-- 只有NEW/RETRY可以进入PUBLISHING;并发实例中至多一个更新返回1。 -->
<update id="claim">
update notification_outbox
set status = 'PUBLISHING', updated_at = #{updatedAt}
where id = #{id} and status in ('NEW', 'RETRY')
</update>
<!-- 仅Publisher Confirm成功后调用,防止网络异常时错误标记为已发布。 -->
<update id="markPublished">
update notification_outbox
set status = 'PUBLISHED', published_at = #{publishedAt}, updated_at = #{publishedAt}, last_error = null
where id = #{id} and status = 'PUBLISHING'
</update>
<!-- failed=true代表达到最大次数并停止自动重试,否则等待next_retry_at。 -->
<update id="markRetry">
update notification_outbox
set status = <choose><when test="failed">'FAILED'</when><otherwise>'RETRY'</otherwise></choose>,
retry_count = #{retryCount}, next_retry_at = #{nextRetryAt}, last_error = #{lastError},
updated_at = #{updatedAt}
where id = #{id} and status = 'PUBLISHING'
</update>
<!-- 服务实例在发布中崩溃时,60秒后由任意存活实例恢复该记录。 -->
<update id="recoverStuck">
update notification_outbox
set status = 'RETRY', next_retry_at = #{updatedAt}, last_error = '发布进程中断,自动恢复', updated_at = #{updatedAt}
where status = 'PUBLISHING' and updated_at &lt; #{staleBefore}
</update>
</mapper>
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.platform.business.mapper.StudentLeaveApplicationMapper"> <mapper namespace="com.platform.business.mapper.StudentLeaveApplicationMapper">
<!-- 三端共用列表查询;教师通过关联课程限定数据范围,手机号完整返回。 -->
<select id="queryApplications" resultType="com.platform.business.model.vo.LeaveApplicationVO"> <select id="queryApplications" resultType="com.platform.business.model.vo.LeaveApplicationVO">
select select
l.id, l.id,
...@@ -49,10 +50,12 @@ ...@@ -49,10 +50,12 @@
order by case when l.status = 'PENDING' then 0 else 1 end, l.applied_at desc order by case when l.status = 'PENDING' then 0 else 1 end, l.applied_at desc
</select> </select>
<!-- 修改、撤回和审批前锁定申请,防止并发状态变化。 -->
<select id="selectByIdForUpdate" resultType="com.platform.business.model.entity.StudentLeaveApplicationEntity"> <select id="selectByIdForUpdate" resultType="com.platform.business.model.entity.StudentLeaveApplicationEntity">
select * from student_leave_application where id = #{id} for update select * from student_leave_application where id = #{id} for update
</select> </select>
<!-- 仅PENDING可更新,保证教师或管理员先审批者生效。 -->
<update id="reviewPending"> <update id="reviewPending">
update student_leave_application update student_leave_application
set status = #{status}, set status = #{status},
...@@ -64,6 +67,7 @@ ...@@ -64,6 +67,7 @@
where id = #{id} and status = 'PENDING' where id = #{id} and status = 'PENDING'
</update> </update>
<!-- 用关联课程的授课教师ID校验教师端查看与审批权限。 -->
<select id="countTeacherRelatedSubjects" resultType="java.lang.Integer"> <select id="countTeacherRelatedSubjects" resultType="java.lang.Integer">
select count(1) select count(1)
from student_leave_subject ls from student_leave_subject ls
......
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