Commit 36a922c8 authored by wujipeng's avatar wujipeng
Browse files

首页

parent dd2bf60f
......@@ -61,6 +61,15 @@ public class ClassEntity {
@ApiModelProperty("班级备注")
private String remark;
/**
* 班级归档标记:0未归档、1已归档。
*
* <p>首页的班级总数和状态分布只统计未归档班级;旧数据由增量脚本统一回填为0。</p>
*/
@TableField("archived_flag")
@ApiModelProperty("是否归档")
private Boolean archivedFlag;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
......
package com.platform.business.model.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
/**
* 实训室设备维护信息。
*
* <p>本期首页仅使用该表统计已到维护日期的有效设备;设备增删改由实训室设备管理模块
* 后续接入,不在首页 Controller 中暴露写接口。</p>
*/
@Data
@TableName("training_room_equipment")
public class TrainingRoomEquipmentEntity {
@TableId(value = "id", type = IdType.ASSIGN_ID)
private String id;
@TableField("room_id")
private String roomId;
@TableField("equipment_code")
private String equipmentCode;
private String name;
/** RUNNING运行中、FAULT故障、MAINTENANCE维护中、DISABLED停用。 */
private String status;
@TableField("last_maintenance_date")
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date lastMaintenanceDate;
@TableField("next_maintenance_date")
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date nextMaintenanceDate;
@TableLogic(value = "0", delval = "1")
@TableField("del_flag")
private Integer delFlag;
@TableField(value = "create_time", fill = FieldFill.INSERT)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
}
package com.platform.business.model.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/** 管理员首页各统计模块的响应模型集合。 */
public final class AdminHomeVO {
private AdminHomeVO() {
}
/** 管理首页顶部核心指标。 */
@Data
public static class Statistics {
private Integer studentCount;
private Integer monthlyNewStudentCount;
private Integer classCount;
private Integer ongoingClassCount;
private Integer teacherCount;
private Integer monthlyNewTeacherCount;
private Integer finishedExamCount;
private BigDecimal passRate;
}
/** 雷达图班级筛选项。 */
@Data
public static class ClassOption {
private Integer classId;
private String className;
}
/** 理论练习一级知识点掌握情况。 */
@Data
public static class Mastery {
private String knowledgePoint;
private Long answerCount;
private Long correctCount;
private BigDecimal masteryRate;
}
/** 管理首页的一类聚合待办。 */
@Data
public static class Todo {
/** TEACHING_PLAN/EXAM_REVIEW/LEAVE_APPROVAL/EQUIPMENT_MAINTENANCE。 */
private String type;
private String title;
private Integer count;
/** 前端使用的稳定模块跳转代码。 */
private String target;
private Integer priority;
}
/** 班级状态分布。 */
@Data
public static class ClassStatus {
private Integer totalCount;
private List<ClassStatusItem> items = new ArrayList<>();
}
/** 单个班级状态及占比。 */
@Data
public static class ClassStatusItem {
/** NOT_STARTED/ONGOING/FINISHED/GRADUATED。 */
private String status;
private String label;
private Integer count;
private BigDecimal percentage;
}
/** Mapper 查询后由服务层判定状态的班级原始数据。 */
@Data
public static class ClassStatusRaw {
private Integer classId;
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date startDate;
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date endDate;
private Integer studentCount;
private Integer graduatedStudentCount;
}
/** 最近七天活跃趋势与摘要。 */
@Data
public static class StudentActivity {
private List<ActivityDay> days = new ArrayList<>();
private Integer todayLoginCount;
private Integer sevenDayActiveCount;
private Integer dormantStudentCount;
}
/** 某个自然日的登录和答题人数。 */
@Data
public static class ActivityDay {
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date date;
private String week;
private Integer loginCount;
private Integer answerCount;
}
/** Mapper 用于承载单序列按日聚合结果。 */
@Data
public static class DailyCount {
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date date;
private Integer count;
}
}
package com.platform.business.model.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* 学员首页各模块的响应模型集合。
*
* <p>首页采用按模块加载的方式,因此这里使用语义明确的嵌套响应类型,避免继续复用旧版
* {@code HomeVO} 中含义不固定的字段。所有用户归属字段均由服务端登录态确定。</p>
*/
public final class StudentHomeVO {
private StudentHomeVO() {
}
/** 学员欢迎区及当前培训班级信息。 */
@Data
public static class Profile {
private String name;
private String studentNo;
private String avatar;
private Integer classId;
private String className;
private String level;
}
/** 学员首页顶部四项统计。 */
@Data
public static class Statistics {
private Integer courseCount;
private Integer pendingExamCount;
private Integer completedExamCount;
private BigDecimal averageScore;
}
/** 未来七天内可见的考试安排。 */
@Data
public static class UpcomingExam {
private Integer examId;
private String examName;
private String type;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm", timezone = "GMT+8")
private Date examTime;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm", timezone = "GMT+8")
private Date endTime;
private Integer duration;
private String location;
/** NOT_STARTED未开始、IN_PROGRESS进行中。 */
private String status;
/** ENTER_EXAM进入考试、VIEW_INSTRUCTION查看说明。 */
private String actionType;
private Boolean actionEnabled;
}
/** 正式考试或理论模拟考试的一条成绩。 */
@Data
public static class Score {
private String recordId;
/** EXAM正式考试、SIMULATION理论模拟考试。 */
private String source;
private String examName;
private String type;
private BigDecimal score;
private BigDecimal totalScore;
/** 模拟考试没有班级排名,因此允许为空。 */
private Integer rank;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm", timezone = "GMT+8")
private Date scoreTime;
}
/** 首页近三天课程的单日分组。 */
@Data
public static class CourseDay {
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date date;
/** TODAY今天、TOMORROW明天、DAY_AFTER_TOMORROW后天。 */
private String dayType;
private String week;
private List<Course> courses = new ArrayList<>();
}
/** 一节课程的展示信息。 */
@Data
public static class Course {
private Integer subjectId;
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date date;
private String timeFrame;
private String subjectName;
private String teacherName;
private String location;
/** IN_PROGRESS进行中、UPCOMING即将开始、PENDING待上课。 */
private String status;
}
}
package com.platform.business.model.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/** 教师首页按模块返回的响应模型集合。 */
public final class TeacherHomeVO {
private TeacherHomeVO() {
}
/** 教师欢迎区信息。 */
@Data
public static class Profile {
private String name;
private String employeeNo;
private String avatar;
private List<String> courseNames = new ArrayList<>();
private Integer classCount;
}
/** 教师工作台顶部四项统计。 */
@Data
public static class Statistics {
private Integer courseCount;
private Integer classCount;
private Integer pendingReviewCount;
private Integer monthlyExamCount;
}
/** 一项待阅卷考试任务。 */
@Data
public static class PendingReview {
private Integer examId;
private String examName;
private Integer classId;
private String className;
private String type;
private Integer submittedCount;
private Integer totalCount;
private Integer pendingCount;
}
/** 教师未来七天参与的考试。 */
@Data
public static class UpcomingExam {
private Integer examId;
private String examName;
private Integer classId;
private String className;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm", timezone = "GMT+8")
private Date examTime;
/** SCHEDULED已安排、PENDING_PUBLICATION待发布。 */
private String status;
}
/** 教师今日授课班级的出勤汇总,数量口径为人次。 */
@Data
public static class Attendance {
private Integer classId;
private String className;
private Integer requiredCount;
private Integer actualCount;
private Integer leaveCount;
private Integer absentCount;
private BigDecimal attendanceRate;
}
}
package com.platform.business.controller;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.AdminHomeVO;
import com.platform.business.service.AdminHomeService;
import com.platform.business.service.AuthenticatedUserService;
import com.platform.model.resp.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/** 管理员首页接口;所有入口先执行管理员角色校验。 */
@Api(tags = "管理员端-首页")
@RestController
@RequestMapping("/home/admin")
public class AdminHomeController {
@Resource
private AdminHomeService adminHomeService;
@Resource
private AuthenticatedUserService authenticatedUserService;
@ApiOperation("管理首页核心指标")
@GetMapping("/statistics")
public Result<AdminHomeVO.Statistics> statistics(HttpServletRequest request) {
requireAdmin(request);
return Result.data(adminHomeService.statistics());
}
@ApiOperation("理论掌握率班级筛选项")
@GetMapping("/classes")
public Result<List<AdminHomeVO.ClassOption>> classes(HttpServletRequest request) {
requireAdmin(request);
return Result.data(adminHomeService.classes());
}
@ApiOperation("理论练习知识点掌握率")
@GetMapping("/theory-mastery")
public Result<List<AdminHomeVO.Mastery>> theoryMastery(
@RequestParam(value = "classId", required = false) Integer classId,
HttpServletRequest request) {
requireAdmin(request);
return Result.data(adminHomeService.theoryMastery(classId));
}
@ApiOperation("管理首页聚合待办")
@GetMapping("/todos")
public Result<List<AdminHomeVO.Todo>> todos(HttpServletRequest request) {
requireAdmin(request);
return Result.data(adminHomeService.todos());
}
@ApiOperation("班级状态分布")
@GetMapping("/class-status")
public Result<AdminHomeVO.ClassStatus> classStatus(HttpServletRequest request) {
requireAdmin(request);
return Result.data(adminHomeService.classStatus());
}
@ApiOperation("最近七天学员活跃趋势")
@GetMapping("/student-activity")
public Result<AdminHomeVO.StudentActivity> studentActivity(HttpServletRequest request) {
requireAdmin(request);
return Result.data(adminHomeService.studentActivity());
}
private UserEntity requireAdmin(HttpServletRequest request) {
UserEntity administrator = authenticatedUserService.current(request);
authenticatedUserService.requireAdmin(administrator);
return administrator;
}
}
package com.platform.business.controller;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.HomeVO;
import com.platform.business.service.AuthenticatedUserService;
import com.platform.business.service.HomeService;
import com.platform.model.resp.Result;
import io.swagger.annotations.Api;
......@@ -10,44 +12,62 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* @author : wujipeng
* @date : 2025/9/4 13:41
* @Version: 1.0
* @Desc : 描述信息
* 旧版管理员首页路由兼容层。
*
* <p>该类只承载历史地址,不混入学员或教师接口。新前端应改用
* {@code /home/admin/**};兼容接口保留原响应结构并统一补上管理员鉴权。</p>
*/
@Api(tags = "首页控制层")
@Deprecated
@Api(tags = "管理员端-首页(旧版兼容)")
@RestController
@RequestMapping("/home")
public class HomeController {
public class AdminHomeLegacyController {
@Resource
private HomeService homeService;
@ApiOperation("近期培训计划")
@Resource
private AuthenticatedUserService authenticatedUserService;
@Deprecated
@ApiOperation(value = "近期培训计划(已废弃)", notes = "请迁移至/home/admin下的新接口")
@GetMapping("/recent/train/Plan")
private Result<List<HomeVO>> recentTrainingPlan() {
public Result<List<HomeVO>> recentTrainingPlan(HttpServletRequest request) {
requireAdmin(request);
return Result.data(homeService.recentTrainingPlan());
}
@ApiOperation("年度计划完成情况")
@Deprecated
@ApiOperation(value = "年度计划完成情况(已废弃)", notes = "请迁移至/home/admin下的新接口")
@GetMapping("/year/plan/complete")
private Result<List<HomeVO>> yearPlanComplete() {
public Result<List<HomeVO>> yearPlanComplete(HttpServletRequest request) {
requireAdmin(request);
return Result.data(homeService.yearPlanComplete());
}
@ApiOperation("当前课程情况")
@Deprecated
@ApiOperation(value = "当前课程情况(已废弃)", notes = "请迁移至/home/admin下的新接口")
@GetMapping("/current/course/situation")
private Result<List<HomeVO>> currentCourseSituation() {
public Result<List<HomeVO>> currentCourseSituation(HttpServletRequest request) {
requireAdmin(request);
return Result.data(homeService.currentCourseSituation());
}
@ApiOperation("今天课程")
@Deprecated
@ApiOperation(value = "今天课程(已废弃)", notes = "请迁移至/home/admin下的新接口")
@GetMapping("/today/course")
private Result<List<HomeVO>> todayCourse() {
public Result<List<HomeVO>> todayCourse(HttpServletRequest request) {
requireAdmin(request);
return Result.data(homeService.todayCourse());
}
private UserEntity requireAdmin(HttpServletRequest request) {
UserEntity administrator = authenticatedUserService.current(request);
authenticatedUserService.requireAdmin(administrator);
return administrator;
}
}
package com.platform.business.controller;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.StudentHomeVO;
import com.platform.business.service.AuthenticatedUserService;
import com.platform.business.service.StudentHomeService;
import com.platform.model.resp.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* 学员端首页接口。
*
* <p>所有方法只从Authorization解析当前学员,不提供studentId请求参数,从入口上阻止查询
* 其他学员的班级、考试、成绩和课程信息。</p>
*/
@Api(tags = "学员端-首页")
@RestController
@RequestMapping("/home/student")
public class StudentHomeController {
@Resource
private StudentHomeService studentHomeService;
@Resource
private AuthenticatedUserService authenticatedUserService;
@ApiOperation("学员欢迎区及当前班级")
@GetMapping("/profile")
public Result<StudentHomeVO.Profile> profile(HttpServletRequest request) {
return Result.data(studentHomeService.profile(currentStudent(request)));
}
@ApiOperation("学员首页统计")
@GetMapping("/statistics")
public Result<StudentHomeVO.Statistics> statistics(HttpServletRequest request) {
return Result.data(studentHomeService.statistics(currentStudent(request)));
}
@ApiOperation("未来七天考试安排")
@GetMapping("/upcoming-exams")
public Result<List<StudentHomeVO.UpcomingExam>> upcomingExams(HttpServletRequest request) {
return Result.data(studentHomeService.upcomingExams(currentStudent(request)));
}
@ApiOperation("最近五条正式及模拟成绩")
@GetMapping("/recent-scores")
public Result<List<StudentHomeVO.Score>> recentScores(HttpServletRequest request) {
return Result.data(studentHomeService.recentScores(currentStudent(request)));
}
@ApiOperation("今天至后天课程安排")
@GetMapping("/courses/next-three-days")
public Result<List<StudentHomeVO.CourseDay>> nextThreeDayCourses(HttpServletRequest request) {
return Result.data(studentHomeService.nextThreeDayCourses(currentStudent(request)));
}
/** 统一完成JWT解析和学员角色校验,Controller不信任任何客户端用户标识。 */
private UserEntity currentStudent(HttpServletRequest request) {
UserEntity student = authenticatedUserService.current(request);
authenticatedUserService.requireStudent(student);
return student;
}
}
package com.platform.business.controller;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.TeacherHomeVO;
import com.platform.business.service.AuthenticatedUserService;
import com.platform.business.service.TeacherHomeService;
import com.platform.model.resp.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/** 教师端首页接口,教师ID始终取自JWT登录态。 */
@Api(tags = "教师端-首页")
@RestController
@RequestMapping("/home/teacher")
public class TeacherHomeController {
@Resource
private TeacherHomeService teacherHomeService;
@Resource
private AuthenticatedUserService authenticatedUserService;
@ApiOperation("教师欢迎区及任教信息")
@GetMapping("/profile")
public Result<TeacherHomeVO.Profile> profile(HttpServletRequest request) {
return Result.data(teacherHomeService.profile(currentTeacher(request)));
}
@ApiOperation("教师工作台统计")
@GetMapping("/statistics")
public Result<TeacherHomeVO.Statistics> statistics(HttpServletRequest request) {
return Result.data(teacherHomeService.statistics(currentTeacher(request)));
}
@ApiOperation("首页待阅卷任务")
@GetMapping("/pending-reviews")
public Result<List<TeacherHomeVO.PendingReview>> pendingReviews(HttpServletRequest request) {
return Result.data(teacherHomeService.pendingReviews(currentTeacher(request)));
}
@ApiOperation("教师未来七天考试安排")
@GetMapping("/upcoming-exams")
public Result<List<TeacherHomeVO.UpcomingExam>> upcomingExams(HttpServletRequest request) {
return Result.data(teacherHomeService.upcomingExams(currentTeacher(request)));
}
@ApiOperation("教师今日授课班级出勤")
@GetMapping("/attendance/today")
public Result<List<TeacherHomeVO.Attendance>> todayAttendance(HttpServletRequest request) {
return Result.data(teacherHomeService.todayAttendance(currentTeacher(request)));
}
/** 统一完成JWT解析和教师角色校验。 */
private UserEntity currentTeacher(HttpServletRequest request) {
UserEntity teacher = authenticatedUserService.current(request);
authenticatedUserService.requireTeacher(teacher);
return teacher;
}
}
package com.platform.business.mapper;
import com.platform.business.model.vo.AdminHomeVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.Date;
import java.util.List;
/** 管理员首页专用全平台聚合查询。 */
@Mapper
public interface AdminHomeMapper {
AdminHomeVO.Statistics selectStatistics(@Param("today") Date today,
@Param("now") Date now,
@Param("monthStart") Date monthStart,
@Param("nextMonthStart") Date nextMonthStart);
List<AdminHomeVO.ClassOption> selectClassOptions();
List<AdminHomeVO.Mastery> selectTheoryMastery(@Param("classId") Integer classId);
List<AdminHomeVO.Todo> selectTodos(@Param("today") Date today);
List<AdminHomeVO.ClassStatusRaw> selectClassStatusRows();
List<AdminHomeVO.DailyCount> selectDailyLoginCounts(
@Param("startTime") Date startTime,
@Param("endTime") Date endTime);
List<AdminHomeVO.DailyCount> selectDailyAnswerCounts(
@Param("startTime") Date startTime,
@Param("endTime") Date endTime);
Integer countSevenDayActiveStudents(@Param("startTime") Date startTime,
@Param("endTime") Date endTime);
Integer countStudyingStudents();
}
package com.platform.business.mapper;
import com.platform.business.model.vo.StudentHomeVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.Date;
import java.util.List;
/** 学员首页专用聚合查询,所有查询都必须带当前登录学员ID。 */
@Mapper
public interface StudentHomeMapper {
StudentHomeVO.Profile selectProfile(@Param("studentId") String studentId,
@Param("today") Date today);
StudentHomeVO.Statistics selectStatistics(@Param("studentId") String studentId,
@Param("classId") Integer classId,
@Param("now") Date now);
List<StudentHomeVO.UpcomingExam> selectUpcomingExams(
@Param("studentId") String studentId,
@Param("now") Date now,
@Param("endTime") Date endTime);
List<StudentHomeVO.Score> selectRecentExamScores(@Param("studentId") String studentId);
List<StudentHomeVO.Score> selectRecentSimulationScores(@Param("studentId") String studentId);
List<StudentHomeVO.Course> selectCourses(@Param("classId") Integer classId,
@Param("startDate") Date startDate,
@Param("endDate") Date endDate);
}
package com.platform.business.mapper;
import com.platform.business.model.vo.TeacherHomeVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.Date;
import java.util.List;
/** 教师首页专用查询,教师数据范围统一通过teacherId限制。 */
@Mapper
public interface TeacherHomeMapper {
List<String> selectCourseNames(@Param("teacherId") String teacherId,
@Param("today") Date today);
Integer countClasses(@Param("teacherId") String teacherId,
@Param("today") Date today);
TeacherHomeVO.Statistics selectStatistics(@Param("teacherId") String teacherId,
@Param("today") Date today,
@Param("monthStart") Date monthStart,
@Param("nextMonthStart") Date nextMonthStart);
List<TeacherHomeVO.PendingReview> selectPendingReviews(
@Param("teacherId") String teacherId,
@Param("limit") int limit);
List<TeacherHomeVO.UpcomingExam> selectUpcomingExams(
@Param("teacherId") String teacherId,
@Param("startTime") Date startTime,
@Param("endTime") Date endTime);
List<TeacherHomeVO.Attendance> selectTodayAttendance(
@Param("teacherId") String teacherId,
@Param("today") Date today);
}
package com.platform.business.service;
import com.platform.business.model.vo.AdminHomeVO;
import java.util.List;
/** 管理员首页分模块查询服务。 */
public interface AdminHomeService {
AdminHomeVO.Statistics statistics();
List<AdminHomeVO.ClassOption> classes();
List<AdminHomeVO.Mastery> theoryMastery(Integer classId);
List<AdminHomeVO.Todo> todos();
AdminHomeVO.ClassStatus classStatus();
AdminHomeVO.StudentActivity studentActivity();
}
......@@ -73,7 +73,25 @@ public class AuthenticatedUserService {
List<SysPhoneRoleEntity> roles = phoneRoleService.queryByPhone(user.getPhoneNumber());
boolean teacher = roles != null && roles.stream().anyMatch(role -> "教师".equals(role.getRoleName()));
if (!teacher) {
throw new BusinessException("只有教师可以访问教案管理接口");
throw new BusinessException("只有教师可以访问教师端接口");
}
}
/**
* 校验当前用户是否具备学员角色。
*
* <p>历史环境同时存在“学生”和“学员”两种中文大类角色,因此两者均视为学员端权限;
* 首页只使用JWT解析出的当前用户,不允许客户端通过参数指定其他学员。</p>
*/
public void requireStudent(UserEntity user) {
if (user == null) {
throw new BusinessException("当前登录用户不存在");
}
List<SysPhoneRoleEntity> roles = phoneRoleService.queryByPhone(user.getPhoneNumber());
boolean student = roles != null && roles.stream().anyMatch(role ->
"学生".equals(role.getRoleName()) || "学员".equals(role.getRoleName()));
if (!student) {
throw new BusinessException("只有学员可以访问学员端接口");
}
}
}
package com.platform.business.service;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.StudentHomeVO;
import java.util.List;
/** 学员首页分模块查询服务。 */
public interface StudentHomeService {
StudentHomeVO.Profile profile(UserEntity student);
StudentHomeVO.Statistics statistics(UserEntity student);
List<StudentHomeVO.UpcomingExam> upcomingExams(UserEntity student);
List<StudentHomeVO.Score> recentScores(UserEntity student);
List<StudentHomeVO.CourseDay> nextThreeDayCourses(UserEntity student);
}
package com.platform.business.service;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.TeacherHomeVO;
import java.util.List;
/** 教师首页分模块查询服务。 */
public interface TeacherHomeService {
TeacherHomeVO.Profile profile(UserEntity teacher);
TeacherHomeVO.Statistics statistics(UserEntity teacher);
List<TeacherHomeVO.PendingReview> pendingReviews(UserEntity teacher);
List<TeacherHomeVO.UpcomingExam> upcomingExams(UserEntity teacher);
List<TeacherHomeVO.Attendance> todayAttendance(UserEntity teacher);
}
package com.platform.business.service.impl;
import com.platform.business.mapper.AdminHomeMapper;
import com.platform.business.model.vo.AdminHomeVO;
import com.platform.business.service.AdminHomeService;
import com.platform.exception.BusinessException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/** 管理员首页全平台统计服务实现。 */
@Service
public class AdminHomeServiceImpl implements AdminHomeService {
@Resource
private AdminHomeMapper adminHomeMapper;
@Override
public AdminHomeVO.Statistics statistics() {
Date current = now();
Date monthStart = monthStart(current);
AdminHomeVO.Statistics result = adminHomeMapper.selectStatistics(
startOfDay(current), current, monthStart, addMonths(monthStart, 1));
if (result == null) {
result = new AdminHomeVO.Statistics();
}
result.setStudentCount(value(result.getStudentCount()));
result.setMonthlyNewStudentCount(value(result.getMonthlyNewStudentCount()));
result.setClassCount(value(result.getClassCount()));
result.setOngoingClassCount(value(result.getOngoingClassCount()));
result.setTeacherCount(value(result.getTeacherCount()));
result.setMonthlyNewTeacherCount(value(result.getMonthlyNewTeacherCount()));
result.setFinishedExamCount(value(result.getFinishedExamCount()));
result.setPassRate(result.getPassRate() == null ? BigDecimal.ZERO : result.getPassRate());
return result;
}
@Override
public List<AdminHomeVO.ClassOption> classes() {
List<AdminHomeVO.ClassOption> result = adminHomeMapper.selectClassOptions();
return result == null ? Collections.emptyList() : result;
}
@Override
public List<AdminHomeVO.Mastery> theoryMastery(Integer classId) {
if (classId != null && classId <= 0) {
throw new BusinessException("班级ID必须为正整数");
}
List<AdminHomeVO.Mastery> result = adminHomeMapper.selectTheoryMastery(classId);
return result == null ? Collections.emptyList() : result;
}
@Override
public List<AdminHomeVO.Todo> todos() {
List<AdminHomeVO.Todo> result = adminHomeMapper.selectTodos(startOfDay(now()));
return result == null ? Collections.emptyList() : result;
}
@Override
public AdminHomeVO.ClassStatus classStatus() {
List<AdminHomeVO.ClassStatusRaw> rows = adminHomeMapper.selectClassStatusRows();
rows = rows == null ? Collections.emptyList() : rows;
Date today = startOfDay(now());
Map<String, Integer> counts = new LinkedHashMap<>();
counts.put("NOT_STARTED", 0);
counts.put("ONGOING", 0);
counts.put("FINISHED", 0);
counts.put("GRADUATED", 0);
for (AdminHomeVO.ClassStatusRaw row : rows) {
String status = resolveClassStatus(row, today);
counts.put(status, counts.get(status) + 1);
}
AdminHomeVO.ClassStatus result = new AdminHomeVO.ClassStatus();
result.setTotalCount(rows.size());
Map<String, String> labels = new HashMap<>();
labels.put("NOT_STARTED", "待开班");
labels.put("ONGOING", "进行中");
labels.put("FINISHED", "已结课");
labels.put("GRADUATED", "已结业");
for (Map.Entry<String, Integer> entry : counts.entrySet()) {
AdminHomeVO.ClassStatusItem item = new AdminHomeVO.ClassStatusItem();
item.setStatus(entry.getKey());
item.setLabel(labels.get(entry.getKey()));
item.setCount(entry.getValue());
item.setPercentage(rate(entry.getValue(), rows.size()));
result.getItems().add(item);
}
return result;
}
@Override
public AdminHomeVO.StudentActivity studentActivity() {
Date today = startOfDay(now());
Date start = addDays(today, -6);
Date end = addDays(today, 1);
Map<String, Integer> loginCounts = toDailyMap(adminHomeMapper.selectDailyLoginCounts(start, end));
Map<String, Integer> answerCounts = toDailyMap(adminHomeMapper.selectDailyAnswerCounts(start, end));
AdminHomeVO.StudentActivity result = new AdminHomeVO.StudentActivity();
for (int i = 0; i < 7; i++) {
Date date = addDays(start, i);
String key = dayKey(date);
AdminHomeVO.ActivityDay day = new AdminHomeVO.ActivityDay();
day.setDate(date);
day.setWeek(chineseWeek(date));
day.setLoginCount(loginCounts.getOrDefault(key, 0));
day.setAnswerCount(answerCounts.getOrDefault(key, 0));
result.getDays().add(day);
}
int active = value(adminHomeMapper.countSevenDayActiveStudents(start, end));
int studying = value(adminHomeMapper.countStudyingStudents());
result.setTodayLoginCount(loginCounts.getOrDefault(dayKey(today), 0));
result.setSevenDayActiveCount(active);
result.setDormantStudentCount(Math.max(0, studying - active));
return result;
}
/** 已全部结业优先于日期状态;无日期的历史班级按进行中兼容展示。 */
static String resolveClassStatus(AdminHomeVO.ClassStatusRaw row, Date today) {
int students = value(row.getStudentCount());
int graduated = value(row.getGraduatedStudentCount());
if (students > 0 && graduated >= students) {
return "GRADUATED";
}
if (row.getStartDate() != null && row.getStartDate().after(today)) {
return "NOT_STARTED";
}
if (row.getEndDate() != null && row.getEndDate().before(today)) {
return "FINISHED";
}
return "ONGOING";
}
/** 允许单元测试固定当前时间。 */
Date now() {
return new Date();
}
private static Map<String, Integer> toDailyMap(List<AdminHomeVO.DailyCount> rows) {
Map<String, Integer> result = new HashMap<>();
if (rows != null) {
for (AdminHomeVO.DailyCount row : rows) {
if (row.getDate() != null) {
result.put(dayKey(row.getDate()), value(row.getCount()));
}
}
}
return result;
}
private static BigDecimal rate(int part, int total) {
if (total <= 0) {
return BigDecimal.ZERO;
}
return BigDecimal.valueOf(part)
.multiply(BigDecimal.valueOf(100))
.divide(BigDecimal.valueOf(total), 1, RoundingMode.HALF_UP);
}
private static int value(Integer value) {
return value == null ? 0 : value;
}
private static Date startOfDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
private static Date monthStart(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(startOfDay(date));
calendar.set(Calendar.DAY_OF_MONTH, 1);
return calendar.getTime();
}
private static Date addDays(Date date, int days) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, days);
return calendar.getTime();
}
private static Date addMonths(Date date, int months) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, months);
return calendar.getTime();
}
private static String dayKey(Date date) {
return new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(date);
}
private static String chineseWeek(Date date) {
String[] weeks = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return weeks[calendar.get(Calendar.DAY_OF_WEEK) - 1];
}
}
package com.platform.business.service.impl;
import com.platform.business.mapper.StudentHomeMapper;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.StudentHomeVO;
import com.platform.business.service.StudentHomeService;
import com.platform.exception.BusinessException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* 学员首页服务实现。
*
* <p>Mapper只负责按当前学员聚合原始数据;时间状态、正式与模拟成绩合并以及三天分组在
* 服务层完成,避免把当前服务器时间和展示枚举散落到SQL中。</p>
*/
@Service
public class StudentHomeServiceImpl implements StudentHomeService {
private static final int UPCOMING_MINUTES = 60;
private static final int RECENT_SCORE_LIMIT = 5;
@Resource
private StudentHomeMapper studentHomeMapper;
@Override
public StudentHomeVO.Profile profile(UserEntity student) {
requireStudent(student);
StudentHomeVO.Profile profile = studentHomeMapper.selectProfile(student.getId(), startOfDay(now()));
if (profile == null) {
throw new BusinessException("当前学员信息不存在");
}
return profile;
}
@Override
public StudentHomeVO.Statistics statistics(UserEntity student) {
StudentHomeVO.Profile profile = profile(student);
StudentHomeVO.Statistics result = studentHomeMapper.selectStatistics(
student.getId(), profile.getClassId(), now());
return result == null ? emptyStatistics() : result;
}
@Override
public List<StudentHomeVO.UpcomingExam> upcomingExams(UserEntity student) {
requireStudent(student);
Date current = now();
List<StudentHomeVO.UpcomingExam> exams = studentHomeMapper.selectUpcomingExams(
student.getId(), current, addDays(current, 7));
if (exams == null) {
return Collections.emptyList();
}
for (StudentHomeVO.UpcomingExam exam : exams) {
boolean started = exam.getExamTime() != null && !current.before(exam.getExamTime());
exam.setStatus(started ? "IN_PROGRESS" : "NOT_STARTED");
boolean theory = exam.getType() != null && exam.getType().contains("理论");
exam.setActionType(theory ? "ENTER_EXAM" : "VIEW_INSTRUCTION");
exam.setActionEnabled(!theory || started);
}
return exams;
}
@Override
public List<StudentHomeVO.Score> recentScores(UserEntity student) {
requireStudent(student);
List<StudentHomeVO.Score> merged = new ArrayList<>();
addAll(merged, studentHomeMapper.selectRecentExamScores(student.getId()));
addAll(merged, studentHomeMapper.selectRecentSimulationScores(student.getId()));
merged.sort(Comparator
.comparing(StudentHomeVO.Score::getScoreTime,
Comparator.nullsLast(Comparator.reverseOrder()))
.thenComparing(StudentHomeVO.Score::getRecordId,
Comparator.nullsLast(Comparator.reverseOrder())));
return merged.size() <= RECENT_SCORE_LIMIT
? merged : new ArrayList<>(merged.subList(0, RECENT_SCORE_LIMIT));
}
@Override
public List<StudentHomeVO.CourseDay> nextThreeDayCourses(UserEntity student) {
StudentHomeVO.Profile profile = profile(student);
Date today = startOfDay(now());
Date exclusiveEnd = addDays(today, 3);
List<StudentHomeVO.Course> courses = profile.getClassId() == null
? Collections.emptyList()
: studentHomeMapper.selectCourses(profile.getClassId(), today, exclusiveEnd);
// LinkedHashMap确保无课程日期也按今天、明天、后天的固定顺序返回。
Map<String, StudentHomeVO.CourseDay> groups = new LinkedHashMap<>();
for (int i = 0; i < 3; i++) {
Date date = addDays(today, i);
StudentHomeVO.CourseDay day = new StudentHomeVO.CourseDay();
day.setDate(date);
day.setDayType(i == 0 ? "TODAY" : i == 1 ? "TOMORROW" : "DAY_AFTER_TOMORROW");
day.setWeek(chineseWeek(date));
groups.put(dayKey(date), day);
}
Date current = now();
if (courses != null) {
for (StudentHomeVO.Course course : courses) {
StudentHomeVO.CourseDay day = groups.get(dayKey(course.getDate()));
if (day != null) {
course.setStatus(resolveCourseStatus(course.getDate(), course.getTimeFrame(), current));
day.getCourses().add(course);
}
}
}
return new ArrayList<>(groups.values());
}
/** 允许测试覆盖服务器当前时间,生产环境始终返回真实时间。 */
Date now() {
return new Date();
}
/**
* 根据课程最早开始和最晚结束时刻计算首页状态。
* 多时段课程在时段之间仍按进行中展示,避免首页在课间频繁跳回待上课。
*/
static String resolveCourseStatus(Date courseDate, String timeFrame, Date current) {
if (courseDate == null || timeFrame == null || timeFrame.trim().isEmpty()) {
return "PENDING";
}
Date firstStart = null;
Date lastEnd = null;
for (String period : timeFrame.split("[,,]")) {
String[] parts = period.trim().split("\\s*[-—–~~]\\s*");
if (parts.length != 2) {
continue;
}
Date start = combineDateAndTime(courseDate, parts[0]);
Date end = combineDateAndTime(courseDate, parts[1]);
if (start != null && (firstStart == null || start.before(firstStart))) {
firstStart = start;
}
if (end != null && (lastEnd == null || end.after(lastEnd))) {
lastEnd = end;
}
}
if (firstStart == null || lastEnd == null) {
return "PENDING";
}
if (!current.before(firstStart) && current.before(lastEnd)) {
return "IN_PROGRESS";
}
long minutes = (firstStart.getTime() - current.getTime()) / 60_000L;
return minutes >= 0 && minutes <= UPCOMING_MINUTES ? "UPCOMING" : "PENDING";
}
private static Date combineDateAndTime(Date date, String time) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
dateTimeFormat.setLenient(false);
try {
return dateTimeFormat.parse(dateFormat.format(date) + " " + time.trim());
} catch (ParseException ignored) {
return null;
}
}
private static void requireStudent(UserEntity student) {
if (student == null || student.getId() == null) {
throw new BusinessException("当前登录学员不存在");
}
}
private static StudentHomeVO.Statistics emptyStatistics() {
StudentHomeVO.Statistics result = new StudentHomeVO.Statistics();
result.setCourseCount(0);
result.setPendingExamCount(0);
result.setCompletedExamCount(0);
result.setAverageScore(java.math.BigDecimal.ZERO);
return result;
}
private static void addAll(List<StudentHomeVO.Score> target, List<StudentHomeVO.Score> source) {
if (source != null) {
target.addAll(source);
}
}
private static Date startOfDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
private static Date addDays(Date date, int days) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, days);
return calendar.getTime();
}
private static String dayKey(Date date) {
return new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(date);
}
private static String chineseWeek(Date date) {
String[] weeks = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return weeks[calendar.get(Calendar.DAY_OF_WEEK) - 1];
}
}
package com.platform.business.service.impl;
import com.platform.business.mapper.TeacherHomeMapper;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.TeacherHomeVO;
import com.platform.business.service.TeacherHomeService;
import com.platform.exception.BusinessException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/** 教师首页服务实现,所有数据访问均使用当前登录教师ID。 */
@Service
public class TeacherHomeServiceImpl implements TeacherHomeService {
private static final int HOME_REVIEW_LIMIT = 5;
@Resource
private TeacherHomeMapper teacherHomeMapper;
@Override
public TeacherHomeVO.Profile profile(UserEntity teacher) {
requireTeacher(teacher);
Date today = startOfDay(now());
TeacherHomeVO.Profile profile = new TeacherHomeVO.Profile();
profile.setName(firstNotBlank(teacher.getNickName(), teacher.getUsername()));
profile.setEmployeeNo(teacher.getEmployeeNo());
profile.setAvatar(teacher.getAvatar());
List<String> courseNames = teacherHomeMapper.selectCourseNames(teacher.getId(), today);
profile.setCourseNames(courseNames == null ? Collections.emptyList() : courseNames);
profile.setClassCount(value(teacherHomeMapper.countClasses(teacher.getId(), today)));
return profile;
}
@Override
public TeacherHomeVO.Statistics statistics(UserEntity teacher) {
requireTeacher(teacher);
Date current = now();
Date monthStart = monthStart(current);
TeacherHomeVO.Statistics result = teacherHomeMapper.selectStatistics(
teacher.getId(), startOfDay(current), monthStart, addMonths(monthStart, 1));
if (result == null) {
result = new TeacherHomeVO.Statistics();
}
result.setCourseCount(value(result.getCourseCount()));
result.setClassCount(value(result.getClassCount()));
result.setPendingReviewCount(value(result.getPendingReviewCount()));
result.setMonthlyExamCount(value(result.getMonthlyExamCount()));
return result;
}
@Override
public List<TeacherHomeVO.PendingReview> pendingReviews(UserEntity teacher) {
requireTeacher(teacher);
List<TeacherHomeVO.PendingReview> result = teacherHomeMapper.selectPendingReviews(
teacher.getId(), HOME_REVIEW_LIMIT);
return result == null ? Collections.emptyList() : result;
}
@Override
public List<TeacherHomeVO.UpcomingExam> upcomingExams(UserEntity teacher) {
requireTeacher(teacher);
Date current = now();
List<TeacherHomeVO.UpcomingExam> result = teacherHomeMapper.selectUpcomingExams(
teacher.getId(), current, addDays(current, 7));
return result == null ? Collections.emptyList() : result;
}
@Override
public List<TeacherHomeVO.Attendance> todayAttendance(UserEntity teacher) {
requireTeacher(teacher);
List<TeacherHomeVO.Attendance> result = teacherHomeMapper.selectTodayAttendance(
teacher.getId(), startOfDay(now()));
return result == null ? Collections.emptyList() : result;
}
/** 允许单元测试固定当前时间。 */
Date now() {
return new Date();
}
private static void requireTeacher(UserEntity teacher) {
if (teacher == null || teacher.getId() == null) {
throw new BusinessException("当前登录教师不存在");
}
}
private static String firstNotBlank(String first, String second) {
return first != null && !first.trim().isEmpty() ? first : second;
}
private static int value(Integer value) {
return value == null ? 0 : value;
}
private static Date startOfDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
private static Date monthStart(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(startOfDay(date));
calendar.set(Calendar.DAY_OF_MONTH, 1);
return calendar.getTime();
}
private static Date addDays(Date date, int days) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, days);
return calendar.getTime();
}
private static Date addMonths(Date date, int months) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, months);
return calendar.getTime();
}
}
<?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.AdminHomeMapper">
<!-- 每个指标独立聚合,确保账户角色、考试考生和班级成员之间不会相互放大。 -->
<select id="selectStatistics" resultType="com.platform.business.model.vo.AdminHomeVO$Statistics">
select
(select count(distinct u.id)
from user u
inner join phone_role role_info on role_info.phone = u.phone_number
where role_info.role_name in ('学生', '学员')
and u.account_status = 'STUDYING'
and coalesce(u.del_flag, 0) = 0) as studentCount,
(select count(distinct u.id)
from user u
inner join phone_role role_info on role_info.phone = u.phone_number
where role_info.role_name in ('学生', '学员')
and u.create_time &gt;= #{monthStart}
and u.create_time &lt; #{nextMonthStart}
and coalesce(u.del_flag, 0) = 0) as monthlyNewStudentCount,
(select count(*) from `class` c where coalesce(c.archived_flag, 0) = 0) as classCount,
(select count(*) from `class` c
where coalesce(c.archived_flag, 0) = 0
and (c.start_date is null or c.start_date &lt;= #{today})
and (c.end_date is null or c.end_date &gt;= #{today})) as ongoingClassCount,
(select count(distinct u.id)
from user u
inner join phone_role role_info on role_info.phone = u.phone_number
where role_info.role_name = '教师'
and coalesce(u.del_flag, 0) = 0) as teacherCount,
(select count(distinct u.id)
from user u
inner join phone_role role_info on role_info.phone = u.phone_number
where role_info.role_name = '教师'
and u.create_time &gt;= #{monthStart}
and u.create_time &lt; #{nextMonthStart}
and coalesce(u.del_flag, 0) = 0) as monthlyNewTeacherCount,
(select count(*) from exam e
where timestampadd(minute, coalesce(e.duration, 0), e.exam_time) &lt; #{now})
as finishedExamCount,
coalesce((select round(sum(case when attempt.score &gt;= coalesce(e.pass_score, 60)
then 1 else 0 end) * 100.0 / count(attempt.id), 1)
from exam_student attempt
inner join exam e on e.id = attempt.exam_id
where coalesce(attempt.submit, 0) = 1
and coalesce(attempt.mark_flag, 0) = 1
and attempt.score is not null), 0) as passRate
</select>
<select id="selectClassOptions" resultType="com.platform.business.model.vo.AdminHomeVO$ClassOption">
select c.id as classId, c.name as className
from `class` c
where coalesce(c.archived_flag, 0) = 0
order by c.start_date desc, c.name asc, c.id desc
</select>
<!-- knowledge_point保存作答时的一级名称快照,正好对应原型雷达图的“按章统计”。 -->
<select id="selectTheoryMastery" resultType="com.platform.business.model.vo.AdminHomeVO$Mastery">
select
answer_record.knowledge_point as knowledgePoint,
count(answer_record.id) as answerCount,
sum(case when answer_record.is_correct = 1 then 1 else 0 end) as correctCount,
round(sum(case when answer_record.is_correct = 1 then 1 else 0 end)
* 100.0 / count(answer_record.id), 1) as masteryRate
from theoretical_practice_answer_record answer_record
<if test="classId != null">
inner join class_student member
on member.user_id = answer_record.student_id and member.class_id = #{classId}
</if>
where answer_record.knowledge_point is not null
and trim(answer_record.knowledge_point) &lt;&gt; ''
group by answer_record.knowledge_point
order by answerCount desc, answer_record.knowledge_point asc
limit 6
</select>
<!-- 待办按业务类别聚合,零数量也返回,前端无需补齐固定卡片。 -->
<select id="selectTodos" resultType="com.platform.business.model.vo.AdminHomeVO$Todo">
select 'TEACHING_PLAN' as type, '教案待审核' as title,
count(*) as count, 'admin-plan' as target, 3 as priority
from teaching_plan plan
where plan.status = 'PENDING' and coalesce(plan.del_flag, 0) = 0
union all
select 'EXAM_REVIEW', '试卷待批阅', count(distinct e.id), 'review', 4
from exam e
inner join exam_student attempt on attempt.exam_id = e.id
where coalesce(attempt.submit, 0) = 1 and coalesce(attempt.mark_flag, 0) = 0
union all
select 'LEAVE_APPROVAL', '请假待审批', count(*), 'leave', 2
from student_leave_application leave_application
where leave_application.status = 'PENDING'
union all
select 'EQUIPMENT_MAINTENANCE', '设备到期维护', count(*), 'room-mgr', 1
from training_room_equipment equipment
where coalesce(equipment.del_flag, 0) = 0
and equipment.status &lt;&gt; 'DISABLED'
and equipment.next_maintenance_date is not null
and equipment.next_maintenance_date &lt;= #{today}
order by priority asc
</select>
<select id="selectClassStatusRows" resultType="com.platform.business.model.vo.AdminHomeVO$ClassStatusRaw">
select
c.id as classId,
c.start_date as startDate,
c.end_date as endDate,
count(member.id) as studentCount,
sum(case when student.account_status in ('GRADUATED', 'ARCHIVED') then 1 else 0 end)
as graduatedStudentCount
from `class` c
left join class_student member on member.class_id = c.id
left join user student on student.id = member.user_id
where coalesce(c.archived_flag, 0) = 0
group by c.id, c.start_date, c.end_date
order by c.id asc
</select>
<select id="selectDailyLoginCounts" resultType="com.platform.business.model.vo.AdminHomeVO$DailyCount">
select date(login_log.login_time) as date, count(distinct login_log.user_id) as count
from account_login_log login_log
inner join user u on u.id = login_log.user_id
inner join phone_role role_info on role_info.phone = u.phone_number
where login_log.login_time &gt;= #{startTime}
and login_log.login_time &lt; #{endTime}
and login_log.result = 'SUCCESS'
and role_info.role_name in ('学生', '学员')
and coalesce(u.del_flag, 0) = 0
group by date(login_log.login_time)
order by date asc
</select>
<select id="selectDailyAnswerCounts" resultType="com.platform.business.model.vo.AdminHomeVO$DailyCount">
select date(answered_at) as date, count(distinct student_id) as count
from theoretical_practice_answer_record
where answered_at &gt;= #{startTime}
and answered_at &lt; #{endTime}
group by date(answered_at)
order by date asc
</select>
<!-- 登录或答题任一发生即视为七日活跃,UNION负责跨来源去重。 -->
<select id="countSevenDayActiveStudents" resultType="java.lang.Integer">
select count(*)
from (
select login_log.user_id as student_id
from account_login_log login_log
inner join user u on u.id = login_log.user_id
inner join phone_role role_info on role_info.phone = u.phone_number
where login_log.login_time &gt;= #{startTime}
and login_log.login_time &lt; #{endTime}
and login_log.result = 'SUCCESS'
and role_info.role_name in ('学生', '学员')
and coalesce(u.del_flag, 0) = 0
union
select answer_record.student_id
from theoretical_practice_answer_record answer_record
inner join user u on u.id = answer_record.student_id
inner join phone_role role_info on role_info.phone = u.phone_number
where answer_record.answered_at &gt;= #{startTime}
and answer_record.answered_at &lt; #{endTime}
and role_info.role_name in ('学生', '学员')
and coalesce(u.del_flag, 0) = 0
) active_student
</select>
<select id="countStudyingStudents" resultType="java.lang.Integer">
select count(distinct u.id)
from user u
inner join phone_role role_info on role_info.phone = u.phone_number
where role_info.role_name in ('学生', '学员')
and u.account_status = 'STUDYING'
and coalesce(u.del_flag, 0) = 0
</select>
</mapper>
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