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

首页

parent dd2bf60f
<?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.StudentHomeMapper">
<!--
当前班级优先级:正在培训 > 尚未结束的未来班级 > 最近一次历史班级。
archived_flag使用COALESCE兼容尚未执行首页迁移脚本的历史空值。
-->
<select id="selectProfile" resultType="com.platform.business.model.vo.StudentHomeVO$Profile">
select
coalesce(nullif(u.nick_name, ''), u.username) as name,
u.username as studentNo,
u.avatar,
selected_class.id as classId,
selected_class.name as className,
coalesce(level_info.name, u.level) as level
from user u
left join (
select c.id, c.name, c.level, member.user_id
from class_student member
inner join `class` c on c.id = member.class_id
where member.user_id = #{studentId}
and coalesce(c.archived_flag, 0) = 0
order by
case
when (c.start_date is null or c.start_date &lt;= #{today})
and (c.end_date is null or c.end_date &gt;= #{today}) then 0
when c.end_date is null or c.end_date &gt;= #{today} then 1
else 2
end,
c.start_date desc,
c.id desc
limit 1
) selected_class on selected_class.user_id = u.id
left join sys_level level_info on cast(level_info.id as char) = selected_class.level
where u.id = #{studentId}
and coalesce(u.del_flag, 0) = 0
</select>
<!-- 统计值使用独立子查询,避免课程、考试多表连接造成重复计数。 -->
<select id="selectStatistics" resultType="com.platform.business.model.vo.StudentHomeVO$Statistics">
select
<choose>
<when test="classId != null">
(select count(distinct subject.subject_name)
from class_subject subject
where subject.class_id = #{classId})
</when>
<otherwise>0</otherwise>
</choose> as courseCount,
(select count(*)
from exam_student attempt
inner join exam e on e.id = attempt.exam_id
where attempt.student_id = #{studentId}
and coalesce(attempt.submit, 0) = 0
and timestampadd(minute, coalesce(e.duration, 0), e.exam_time) &gt;= #{now})
as pendingExamCount,
(select count(*)
from exam_student attempt
where attempt.student_id = #{studentId}
and coalesce(attempt.submit, 0) = 1)
as completedExamCount,
coalesce((select round(avg(attempt.score), 2)
from exam_student attempt
where attempt.student_id = #{studentId}
and coalesce(attempt.submit, 0) = 1
and coalesce(attempt.mark_flag, 0) = 1
and attempt.score is not null), 0)
as averageScore
</select>
<!-- 只返回当前仍可见且七天内开始的个人考试,不暴露其他学员安排。 -->
<select id="selectUpcomingExams" resultType="com.platform.business.model.vo.StudentHomeVO$UpcomingExam">
select
e.id as examId,
e.name as examName,
e.type,
e.exam_time as examTime,
timestampadd(minute, coalesce(e.duration, 0), e.exam_time) as endTime,
e.duration,
e.location
from exam_student attempt
inner join exam e on e.id = attempt.exam_id
where attempt.student_id = #{studentId}
and coalesce(attempt.submit, 0) = 0
and timestampadd(minute, coalesce(e.duration, 0), e.exam_time) &gt;= #{now}
and e.exam_time &lt; #{endTime}
order by e.exam_time asc, e.id asc
</select>
<!--
使用相关子查询计算名次,避免为首页新增MySQL 8专属窗口函数,保持与项目声明的
MySQL 5.7兼容范围一致;同分学员获得相同名次。
-->
<select id="selectRecentExamScores" resultType="com.platform.business.model.vo.StudentHomeVO$Score">
select
cast(attempt.id as char) as recordId,
'EXAM' as source,
e.name as examName,
e.type,
attempt.score,
e.total_score as totalScore,
1 + (select count(*)
from exam_student higher
where higher.exam_id = attempt.exam_id
and coalesce(higher.mark_flag, 0) = 1
and higher.score &gt; attempt.score) as rank,
coalesce(from_unixtime(attempt.end_time / 1000), e.exam_time) as scoreTime
from exam_student attempt
inner join exam e on e.id = attempt.exam_id
where attempt.student_id = #{studentId}
and coalesce(attempt.submit, 0) = 1
and coalesce(attempt.mark_flag, 0) = 1
and attempt.score is not null
order by scoreTime desc, attempt.id desc
limit 5
</select>
<!-- 过滤“待作答”等非数字历史值后再转换分数。 -->
<select id="selectRecentSimulationScores" resultType="com.platform.business.model.vo.StudentHomeVO$Score">
select
simulation.id as recordId,
'SIMULATION' as source,
simulation.name as examName,
coalesce(nullif(simulation.type, ''), '理论模拟') as type,
cast(simulation.score as decimal(10, 2)) as score,
simulation.total_score as totalScore,
null as rank,
coalesce(from_unixtime(simulation.end_time / 1000), simulation.create_time) as scoreTime
from theoretical_practice_student_simulation simulation
where simulation.student_id = #{studentId}
and simulation.score regexp '^[0-9]+([.][0-9]+)?$'
order by scoreTime desc, simulation.id desc
limit 5
</select>
<select id="selectCourses" resultType="com.platform.business.model.vo.StudentHomeVO$Course">
select
subject.id as subjectId,
subject.date,
subject.time_frame as timeFrame,
subject.subject_name as subjectName,
coalesce(nullif(teacher.nick_name, ''), teacher.username) as teacherName,
subject.location
from class_subject subject
left join user teacher on teacher.id = subject.teacher_id
where subject.class_id = #{classId}
and subject.date &gt;= #{startDate}
and subject.date &lt; #{endDate}
order by subject.date asc, subject.time_frame asc, subject.id asc
</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.TeacherHomeMapper">
<select id="selectCourseNames" resultType="java.lang.String">
select distinct subject.subject_name
from class_subject subject
inner join `class` c on c.id = subject.class_id
where subject.teacher_id = #{teacherId}
and coalesce(c.archived_flag, 0) = 0
and (c.end_date is null or c.end_date &gt;= #{today})
and subject.subject_name is not null
and trim(subject.subject_name) &lt;&gt; ''
order by subject.subject_name asc
</select>
<select id="countClasses" resultType="java.lang.Integer">
select count(distinct subject.class_id)
from class_subject subject
inner join `class` c on c.id = subject.class_id
where subject.teacher_id = #{teacherId}
and coalesce(c.archived_flag, 0) = 0
and (c.end_date is null or c.end_date &gt;= #{today})
</select>
<!-- 教师参与考试兼容invigilation_id历史逗号分隔存储。 -->
<select id="selectStatistics" resultType="com.platform.business.model.vo.TeacherHomeVO$Statistics">
select
(select count(distinct subject.subject_name)
from class_subject subject
inner join `class` c on c.id = subject.class_id
where subject.teacher_id = #{teacherId}
and coalesce(c.archived_flag, 0) = 0
and (c.end_date is null or c.end_date &gt;= #{today})) as courseCount,
(select count(distinct subject.class_id)
from class_subject subject
inner join `class` c on c.id = subject.class_id
where subject.teacher_id = #{teacherId}
and coalesce(c.archived_flag, 0) = 0
and (c.end_date is null or c.end_date &gt;= #{today})) as classCount,
(select count(distinct e.id)
from exam e
inner join exam_student attempt on attempt.exam_id = e.id
where e.chief_id = #{teacherId}
and coalesce(attempt.submit, 0) = 1
and coalesce(attempt.mark_flag, 0) = 0) as pendingReviewCount,
(select count(distinct e.id)
from exam e
where e.exam_time &gt;= #{monthStart}
and e.exam_time &lt; #{nextMonthStart}
and (e.chief_id = #{teacherId}
or find_in_set(#{teacherId}, replace(coalesce(e.invigilation_id, ''), ' ', '')) &gt; 0))
as monthlyExamCount
</select>
<select id="selectPendingReviews" resultType="com.platform.business.model.vo.TeacherHomeVO$PendingReview">
select
e.id as examId,
e.name as examName,
e.class_id as classId,
c.name as className,
e.type,
sum(case when coalesce(attempt.submit, 0) = 1 then 1 else 0 end) as submittedCount,
count(attempt.id) as totalCount,
sum(case when coalesce(attempt.submit, 0) = 1
and coalesce(attempt.mark_flag, 0) = 0 then 1 else 0 end) as pendingCount
from exam e
inner join exam_student attempt on attempt.exam_id = e.id
left join `class` c on c.id = e.class_id
where e.chief_id = #{teacherId}
group by e.id, e.name, e.class_id, c.name, e.type, e.exam_time
having sum(case when coalesce(attempt.submit, 0) = 1
and coalesce(attempt.mark_flag, 0) = 0 then 1 else 0 end) &gt; 0
order by e.exam_time asc, e.id asc
limit #{limit}
</select>
<select id="selectUpcomingExams" resultType="com.platform.business.model.vo.TeacherHomeVO$UpcomingExam">
select
e.id as examId,
e.name as examName,
e.class_id as classId,
c.name as className,
e.exam_time as examTime,
case when exists(select 1 from exam_student attempt where attempt.exam_id = e.id)
then 'SCHEDULED' else 'PENDING_PUBLICATION' end as status
from exam e
left join `class` c on c.id = e.class_id
where e.exam_time &gt;= #{startTime}
and e.exam_time &lt; #{endTime}
and (e.chief_id = #{teacherId}
or find_in_set(#{teacherId}, replace(coalesce(e.invigilation_id, ''), ' ', '')) &gt; 0)
order by e.exam_time asc, e.id asc
</select>
<!--
同一教师同一天可能给同一班级上多节课,因此这里按出勤人次汇总:应到为
“课次数 × 班级人数”,实到只计算NORMAL和LATE。
-->
<select id="selectTodayAttendance" resultType="com.platform.business.model.vo.TeacherHomeVO$Attendance">
select
subject.class_id as classId,
c.name as className,
count(member.id) as requiredCount,
sum(case when attendance.status in ('NORMAL', 'LATE') then 1 else 0 end) as actualCount,
sum(case when attendance.status = 'LEAVE' then 1 else 0 end) as leaveCount,
sum(case when attendance.status = 'ABSENT' then 1 else 0 end) as absentCount,
case when count(member.id) = 0 then 0
else round(sum(case when attendance.status in ('NORMAL', 'LATE') then 1 else 0 end)
* 100.0 / count(member.id), 2)
end as attendanceRate
from class_subject subject
inner join `class` c on c.id = subject.class_id
inner join class_student member on member.class_id = subject.class_id
inner join user student on student.id = member.user_id and coalesce(student.del_flag, 0) = 0
left join class_subject_attendance attendance
on attendance.subject_id = subject.id and attendance.user_id = member.user_id
where subject.teacher_id = #{teacherId}
and subject.date = #{today}
group by subject.class_id, c.name
order by c.name asc, subject.class_id asc
</select>
</mapper>
# 学员 / 教师 / 管理员首页接口
## 1. 通用约定
- 服务:`practical-business`,所有接口均为 `GET`。
- 请求头:`Authorization: Bearer <token>`,同时兼容项目历史裸 Token 格式。
- 响应:统一使用 `Result<T>` 包装。
- 学员和教师接口不接收用户 ID,服务端只使用 JWT 对应的当前用户。
- 日期格式:日期为 `yyyy-MM-dd`,时间为 `yyyy-MM-dd HH:mm`,时区为 `GMT+8`。
- 空列表返回 `[]`,统计数量和比率无数据时返回 `0`,不返回 `null`。
## 2. 学员首页
### 2.1 欢迎区
`GET /home/student/profile`
返回:`name`、`studentNo`、`avatar`、`classId`、`className`、`level`。
当前班级优先选择正在培训的未归档班级,其次选择尚未结束的未来班级,最后回退到最近的历史班级。
### 2.2 首页统计
`GET /home/student/statistics`
返回:`courseCount`、`pendingExamCount`、`completedExamCount`、`averageScore`。
- 课程数按当前班级不同课程名称统计。
- 已完成考试按已交卷统计。
- 平均分只统计已发布且分数非空的正式考试。
### 2.3 未来七天考试
`GET /home/student/upcoming-exams`
每项字段:`examId`、`examName`、`type`、`examTime`、`endTime`、`duration`、`location`、`status`、`actionType`、`actionEnabled`。
- `status`:`NOT_STARTED`、`IN_PROGRESS`。
- `actionType`:理论考试为 `ENTER_EXAM`,实训考试为 `VIEW_INSTRUCTION`。
- 理论考试未到开始时间时 `actionEnabled=false`。
### 2.4 最近成绩
`GET /home/student/recent-scores`
正式考试和理论模拟考试按时间合并后返回最近 5 条。每项字段:`recordId`、`source`、`examName`、`type`、`score`、`totalScore`、`rank`、`scoreTime`。
- `source`:`EXAM`、`SIMULATION`。
- 模拟考试没有班级排名,`rank` 返回 `null`。
### 2.5 近三天课程
`GET /home/student/courses/next-three-days`
固定返回今天、明天、后天三个分组,即使当天没有课程也会返回空 `courses`。课程状态为 `IN_PROGRESS`、`UPCOMING` 或 `PENDING`;距离首个时段开始不超过 60 分钟为 `UPCOMING`。
## 3. 教师首页
| 接口 | 说明 |
|---|---|
| `GET /home/teacher/profile` | 姓名、工号、头像、任教课程集合、授课班级数 |
| `GET /home/teacher/statistics` | 任教课程数、班级数、待阅卷数、本月参与考试数 |
| `GET /home/teacher/pending-reviews` | 当前教师作为首席考评员的前 5 个待阅卷任务 |
| `GET /home/teacher/upcoming-exams` | 当前教师未来 7 天参与的考试 |
| `GET /home/teacher/attendance/today` | 今日授课班级出勤人次汇总 |
考试安排状态:存在 `exam_student` 分配记录为 `SCHEDULED`,否则为 `PENDING_PUBLICATION`。出勤率分子为 `NORMAL + LATE`,分母为授课课次对应的应到人次。
## 4. 管理员首页
| 接口 | 说明 |
|---|---|
| `GET /home/admin/statistics` | 学员、班级、教师、考试 KPI |
| `GET /home/admin/classes` | 理论掌握率可筛选的未归档班级 |
| `GET /home/admin/theory-mastery?classId=1` | 最多 6 个一级知识点掌握率;不传班级统计全平台 |
| `GET /home/admin/todos` | 教案、阅卷、请假、设备维护四类待办 |
| `GET /home/admin/class-status` | 待开班、进行中、已结课、已结业分布 |
| `GET /home/admin/student-activity` | 最近 7 天登录/答题人数及活跃摘要 |
待办类型固定为:`TEACHING_PLAN`、`EXAM_REVIEW`、`LEAVE_APPROVAL`、`EQUIPMENT_MAINTENANCE`。
班级状态固定为:`NOT_STARTED`、`ONGOING`、`FINISHED`、`GRADUATED`。有学员且所有学员账户均为 `GRADUATED/ARCHIVED` 时优先判定为已结业。
## 5. 旧接口兼容
下列旧地址暂时保留在管理员兼容 Controller 中,并增加管理员角色校验:
- `/home/recent/train/Plan`
- `/home/year/plan/complete`
- `/home/current/course/situation`
- `/home/today/course`
新页面不得继续接入上述接口。
## 6. 数据库发布
执行 `sql/home_dashboard.sql`。脚本会增加 `class.archived_flag`、创建设备维护表并补充首页聚合索引;脚本可重复执行,不会伪造设备维护记录。
-- 学员端、教师端、管理员端首页增量数据库脚本(MySQL 5.7+/8.0)。
--
-- 执行顺序:
-- 1. 先执行既有 account_management.sql、class_management.sql、exam_management.sql、
-- teaching_plan.sql、theoretical_practice_statistics.sql,并确认请假、实训室基础表已部署;
-- 2. 再执行本脚本;
-- 3. 最后发布 practical-business。
--
-- 设计说明:
-- 1. 只增加首页真实聚合所需的最小字段、设备维护表和查询索引,不删除或覆盖业务数据。
-- 2. 项目现有业务表不统一建立外键,本脚本沿用该约定,由业务服务保证ID归属。
-- 3. 所有ALTER操作均先检查information_schema,脚本可以重复执行。
create table if not exists training_room_equipment (
id varchar(64) not null comment '设备ID(雪花算法字符串)',
room_id varchar(64) not null comment '所属实训室ID',
equipment_code varchar(64) not null comment '设备编号,同一实训室内唯一',
name varchar(100) not null comment '设备名称',
status varchar(20) not null default 'RUNNING'
comment 'RUNNING运行中/FAULT故障/MAINTENANCE维护中/DISABLED停用',
last_maintenance_date date null comment '上次维护日期',
next_maintenance_date date null comment '下次计划维护日期',
del_flag tinyint not null default 0 comment '逻辑删除:0正常/1删除',
create_time datetime null comment '创建时间',
update_time datetime null comment '最后更新时间',
primary key (id),
unique key uk_training_room_equipment_code (room_id, equipment_code),
key idx_training_room_equipment_due (del_flag, status, next_maintenance_date),
key idx_training_room_equipment_room (room_id, del_flag)
) engine=InnoDB default charset=utf8mb4 comment='实训室设备及维护日期';
delimiter $$
drop procedure if exists migrate_home_dashboard$$
create procedure migrate_home_dashboard()
begin
-- 班级归档与结课是两个不同状态;首页只统计未归档班级。
if not exists (
select 1 from information_schema.columns
where table_schema = database() and table_name = 'class'
and column_name = 'archived_flag'
) then
alter table `class`
add column archived_flag tinyint not null default 0
comment '是否归档:0未归档/1已归档' after remark;
end if;
if not exists (
select 1 from information_schema.statistics
where table_schema = database() and table_name = 'class'
and index_name = 'idx_class_dashboard_status'
) then
alter table `class`
add index idx_class_dashboard_status (archived_flag, start_date, end_date, id);
end if;
-- 学员首页从student_id反查个人考试,原exam_id前导索引无法覆盖该查询。
if not exists (
select 1 from information_schema.statistics
where table_schema = database() and table_name = 'exam_student'
and index_name = 'idx_exam_student_user_status'
) then
alter table exam_student
add index idx_exam_student_user_status (student_id, submit, mark_flag, exam_id);
end if;
-- 教师首页高频按教师和课程日期读取排课。
if not exists (
select 1 from information_schema.statistics
where table_schema = database() and table_name = 'class_subject'
and index_name = 'idx_class_subject_teacher_date'
) then
alter table class_subject
add index idx_class_subject_teacher_date (teacher_id, date, class_id);
end if;
-- 管理员活跃图按时间范围扫描成功登录,时间必须作为前导列。
if not exists (
select 1 from information_schema.statistics
where table_schema = database() and table_name = 'account_login_log'
and index_name = 'idx_account_login_time_result_user'
) then
alter table account_login_log
add index idx_account_login_time_result_user (login_time, result, user_id);
end if;
-- 原作答索引以practice_id开头,不能支持全平台最近七天活跃统计。
if not exists (
select 1 from information_schema.statistics
where table_schema = database()
and table_name = 'theoretical_practice_answer_record'
and index_name = 'idx_tp_answer_time_student'
) then
alter table theoretical_practice_answer_record
add index idx_tp_answer_time_student (answered_at, student_id);
end if;
end$$
call migrate_home_dashboard()$$
drop procedure if exists migrate_home_dashboard$$
delimiter ;
-- 历史班级没有归档信息,统一视为未归档;不根据结课日期擅自归档。
update `class`
set archived_flag = 0
where archived_flag is null;
-- 发布前只读检查:以下设备已到维护日期,会进入管理员首页“设备到期维护”。
select id, room_id, equipment_code, name, status, next_maintenance_date
from training_room_equipment
where coalesce(del_flag, 0) = 0
and status <> 'DISABLED'
and next_maintenance_date is not null
and next_maintenance_date <= current_date
order by next_maintenance_date asc, id asc;
package com.platform.business.controller;
import org.junit.jupiter.api.Test;
import org.springframework.web.bind.annotation.RequestMapping;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/** 确保三端首页Controller保持独立根路径,防止后续功能再次混入同一控制器。 */
class HomeControllerSeparationTest {
@Test
void roleControllersShouldUseIndependentRoots() {
assertRoot(StudentHomeController.class, "/home/student");
assertRoot(TeacherHomeController.class, "/home/teacher");
assertRoot(AdminHomeController.class, "/home/admin");
assertRoot(AdminHomeLegacyController.class, "/home");
}
private static void assertRoot(Class<?> controller, String expected) {
RequestMapping mapping = controller.getAnnotation(RequestMapping.class);
assertNotNull(mapping);
assertArrayEquals(new String[]{expected}, mapping.value());
}
}
package com.platform.business.mapper;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** 首页增量脚本的幂等保护、关键表和索引静态完整性测试。 */
class HomeDashboardSqlTest {
@Test
void migrationShouldGuardEveryAlterAndNeverDeleteBusinessTables() throws Exception {
String sql = new String(Files.readAllBytes(Paths.get(
"src/main/resources/sql/home_dashboard.sql")), StandardCharsets.UTF_8)
.toLowerCase();
assertTrue(sql.contains("create table if not exists training_room_equipment"));
assertTrue(sql.contains("information_schema.columns"));
assertTrue(sql.contains("information_schema.statistics"));
assertTrue(sql.contains("idx_exam_student_user_status"));
assertTrue(sql.contains("idx_account_login_time_result_user"));
assertTrue(sql.contains("idx_tp_answer_time_student"));
assertFalse(sql.contains("drop table"));
assertFalse(sql.contains("delete from"));
}
}
package com.platform.business.mapper;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.junit.jupiter.api.Test;
import java.io.InputStream;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** 确保三套首页动态SQL均能被MyBatis解析并注册。 */
class HomeMapperXmlTest {
@Test
void allHomeMapperXmlFilesShouldParse() throws Exception {
Configuration configuration = new Configuration();
parse(configuration, "com/platform/business/mapper/StudentHomeMapper.xml");
parse(configuration, "com/platform/business/mapper/TeacherHomeMapper.xml");
parse(configuration, "com/platform/business/mapper/AdminHomeMapper.xml");
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.StudentHomeMapper.selectRecentExamScores"));
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.TeacherHomeMapper.selectTodayAttendance"));
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.AdminHomeMapper.countSevenDayActiveStudents"));
}
private static void parse(Configuration configuration, String resource) throws Exception {
try (InputStream input = Resources.getResourceAsStream(resource)) {
XMLMapperBuilder builder = new XMLMapperBuilder(
input, configuration, resource, configuration.getSqlFragments());
builder.parse();
}
}
}
package com.platform.business.service;
import com.platform.business.model.entity.SysPhoneRoleEntity;
import com.platform.business.model.entity.UserEntity;
import com.platform.exception.BusinessException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.util.ReflectionTestUtils;
import java.util.Collections;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.when;
/** 登录用户服务新增学员角色校验测试。 */
@ExtendWith(MockitoExtension.class)
class AuthenticatedUserServiceTest {
@Mock
private SysPhoneRoleService phoneRoleService;
private AuthenticatedUserService service;
private UserEntity user;
@BeforeEach
void setUp() {
service = new AuthenticatedUserService();
ReflectionTestUtils.setField(service, "phoneRoleService", phoneRoleService);
user = new UserEntity();
user.setPhoneNumber("13800000000");
}
@Test
void requireStudentShouldAcceptBothHistoricalStudentRoleNames() {
when(phoneRoleService.queryByPhone(user.getPhoneNumber()))
.thenReturn(Collections.singletonList(role("学员")))
.thenReturn(Collections.singletonList(role("学生")));
assertDoesNotThrow(() -> service.requireStudent(user));
assertDoesNotThrow(() -> service.requireStudent(user));
}
@Test
void requireStudentShouldRejectTeacherRole() {
when(phoneRoleService.queryByPhone(user.getPhoneNumber()))
.thenReturn(Collections.singletonList(role("教师")));
assertThrows(BusinessException.class, () -> service.requireStudent(user));
}
private static SysPhoneRoleEntity role(String roleName) {
SysPhoneRoleEntity role = new SysPhoneRoleEntity();
role.setRoleName(roleName);
return role;
}
}
package com.platform.business.service.impl;
import com.platform.business.mapper.AdminHomeMapper;
import com.platform.business.model.vo.AdminHomeVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.util.ReflectionTestUtils;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
/** 管理员首页班级状态和七日活跃补零测试。 */
@ExtendWith(MockitoExtension.class)
class AdminHomeServiceImplTest {
@Mock
private AdminHomeMapper mapper;
private FixedAdminHomeService service;
@BeforeEach
void setUp() throws Exception {
service = new FixedAdminHomeService(date("2026-08-19 12:00"));
ReflectionTestUtils.setField(service, "adminHomeMapper", mapper);
}
@Test
void classStatusShouldUseGraduationBeforeDateState() throws Exception {
AdminHomeVO.ClassStatusRaw future = row("2026-09-01", "2026-10-01", 10, 0);
AdminHomeVO.ClassStatusRaw ongoing = row("2026-08-01", "2026-09-01", 10, 0);
AdminHomeVO.ClassStatusRaw finished = row("2026-07-01", "2026-08-01", 10, 8);
AdminHomeVO.ClassStatusRaw graduated = row("2026-07-01", "2026-08-01", 10, 10);
when(mapper.selectClassStatusRows()).thenReturn(Arrays.asList(
future, ongoing, finished, graduated));
AdminHomeVO.ClassStatus result = service.classStatus();
assertEquals(4, result.getTotalCount());
assertEquals(1, result.getItems().get(0).getCount());
assertEquals(1, result.getItems().get(1).getCount());
assertEquals(1, result.getItems().get(2).getCount());
assertEquals(1, result.getItems().get(3).getCount());
assertEquals("25.0", result.getItems().get(3).getPercentage().toPlainString());
}
@Test
void activityShouldReturnSevenDaysAndCalculateDormantStudents() throws Exception {
AdminHomeVO.DailyCount todayLogin = daily("2026-08-19", 5);
AdminHomeVO.DailyCount answer = daily("2026-08-17", 3);
when(mapper.selectDailyLoginCounts(any(Date.class), any(Date.class)))
.thenReturn(Collections.singletonList(todayLogin));
when(mapper.selectDailyAnswerCounts(any(Date.class), any(Date.class)))
.thenReturn(Collections.singletonList(answer));
when(mapper.countSevenDayActiveStudents(any(Date.class), any(Date.class))).thenReturn(7);
when(mapper.countStudyingStudents()).thenReturn(20);
AdminHomeVO.StudentActivity result = service.studentActivity();
assertEquals(7, result.getDays().size());
assertEquals(5, result.getTodayLoginCount());
assertEquals(7, result.getSevenDayActiveCount());
assertEquals(13, result.getDormantStudentCount());
}
private static AdminHomeVO.ClassStatusRaw row(String start, String end,
int students, int graduated) throws Exception {
AdminHomeVO.ClassStatusRaw row = new AdminHomeVO.ClassStatusRaw();
row.setStartDate(day(start));
row.setEndDate(day(end));
row.setStudentCount(students);
row.setGraduatedStudentCount(graduated);
return row;
}
private static AdminHomeVO.DailyCount daily(String day, int count) throws Exception {
AdminHomeVO.DailyCount row = new AdminHomeVO.DailyCount();
row.setDate(day(day));
row.setCount(count);
return row;
}
private static Date day(String value) throws Exception {
return new SimpleDateFormat("yyyy-MM-dd").parse(value);
}
private static Date date(String value) throws Exception {
return new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(value);
}
private static class FixedAdminHomeService extends AdminHomeServiceImpl {
private final Date fixedNow;
private FixedAdminHomeService(Date fixedNow) {
this.fixedNow = fixedNow;
}
@Override
Date now() {
return fixedNow;
}
}
}
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 org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.util.ReflectionTestUtils;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.when;
/** 学员首页时间状态、成绩合并和空日期分组规则测试。 */
@ExtendWith(MockitoExtension.class)
class StudentHomeServiceImplTest {
@Mock
private StudentHomeMapper mapper;
private FixedStudentHomeService service;
private UserEntity student;
@BeforeEach
void setUp() throws Exception {
service = new FixedStudentHomeService(date("2026-08-19 09:00"));
ReflectionTestUtils.setField(service, "studentHomeMapper", mapper);
student = new UserEntity();
student.setId("student-1");
StudentHomeVO.Profile profile = new StudentHomeVO.Profile();
profile.setName("张同学");
profile.setClassId(10);
lenient().when(mapper.selectProfile(eq("student-1"), any(Date.class))).thenReturn(profile);
}
@Test
void coursesShouldAlwaysReturnThreeDaysAndCalculateUpcoming() throws Exception {
StudentHomeVO.Course course = new StudentHomeVO.Course();
course.setSubjectId(1);
course.setDate(date("2026-08-19 00:00"));
course.setTimeFrame("09:30-10:30");
when(mapper.selectCourses(eq(10), any(Date.class), any(Date.class)))
.thenReturn(Collections.singletonList(course));
List<StudentHomeVO.CourseDay> result = service.nextThreeDayCourses(student);
assertEquals(3, result.size());
assertEquals("TODAY", result.get(0).getDayType());
assertEquals("UPCOMING", result.get(0).getCourses().get(0).getStatus());
assertTrue(result.get(1).getCourses().isEmpty());
assertTrue(result.get(2).getCourses().isEmpty());
}
@Test
void recentScoresShouldMergeSortAndLimitFive() throws Exception {
when(mapper.selectRecentExamScores("student-1")).thenReturn(Arrays.asList(
score("e1", "2026-08-19 08:00"), score("e2", "2026-08-17 08:00"),
score("e3", "2026-08-15 08:00")));
when(mapper.selectRecentSimulationScores("student-1")).thenReturn(Arrays.asList(
score("s1", "2026-08-18 08:00"), score("s2", "2026-08-16 08:00"),
score("s3", "2026-08-14 08:00")));
List<StudentHomeVO.Score> result = service.recentScores(student);
assertEquals(5, result.size());
assertEquals(Arrays.asList("e1", "s1", "e2", "s2", "e3"),
Arrays.asList(result.get(0).getRecordId(), result.get(1).getRecordId(),
result.get(2).getRecordId(), result.get(3).getRecordId(),
result.get(4).getRecordId()));
}
@Test
void courseStatusShouldHandleMultiplePeriods() throws Exception {
Date courseDate = date("2026-08-19 00:00");
assertEquals("IN_PROGRESS", StudentHomeServiceImpl.resolveCourseStatus(
courseDate, "08:30-10:00,10:30-12:00", date("2026-08-19 10:15")));
assertEquals("PENDING", StudentHomeServiceImpl.resolveCourseStatus(
courseDate, "14:00-15:00", date("2026-08-19 09:00")));
}
private static StudentHomeVO.Score score(String id, String time) throws Exception {
StudentHomeVO.Score score = new StudentHomeVO.Score();
score.setRecordId(id);
score.setScoreTime(date(time));
return score;
}
private static Date date(String value) throws Exception {
return new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(value);
}
/** 固定服务器时间,避免测试结果随运行日期变化。 */
private static class FixedStudentHomeService extends StudentHomeServiceImpl {
private final Date fixedNow;
private FixedStudentHomeService(Date fixedNow) {
this.fixedNow = fixedNow;
}
@Override
Date now() {
return fixedNow;
}
}
}
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