"src/main/java/com/git@gitlab.ruzhoukj.com:wujipeng/ops.git" did not exist on "c075730a10e06d45c77374351f2062871cfa0fe9"
Commit dd2bf60f authored by wujipeng's avatar wujipeng
Browse files

管理员-系统管理-账户管理

parent 9fc77652
<?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.auth.mapper.USerMapper">
<insert id="insertLoginLog">
insert into account_login_log
(user_id, login_name, login_time, ip_address, device, result, failure_reason)
values
(#{userId}, #{loginName}, now(), #{ipAddress}, #{device}, #{result}, #{failureReason})
</insert>
</mapper>
package com.platform.business.constant;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/** 管理员端账户管理使用的稳定代码和边界值。 */
public final class AccountAdminConstants {
public static final String TYPE_STUDENT = "STUDENT";
public static final String TYPE_TEACHER = "TEACHER";
public static final String TYPE_ADMIN = "ADMIN";
public static final String ROLE_STUDENT = "学生";
public static final String ROLE_TEACHER = "教师";
public static final String ROLE_ADMIN = "管理员";
public static final String STATUS_PENDING = "PENDING";
public static final String STATUS_STUDYING = "STUDYING";
public static final String STATUS_GRADUATED = "GRADUATED";
public static final String STATUS_ARCHIVED = "ARCHIVED";
public static final String STATUS_ENABLED = "ENABLED";
public static final String STATUS_DISABLED = "DISABLED";
public static final String ACTION_GRADUATE = "GRADUATE";
public static final String ACTION_ARCHIVE = "ARCHIVE";
public static final String ACTION_RESET_PASSWORD = "RESET_PASSWORD";
public static final String ACTION_ENABLE = "ENABLE";
public static final String ACTION_DISABLE = "DISABLE";
public static final String DEFAULT_PASSWORD = "Wssg@2026";
public static final int DEFAULT_PAGE_NUM = 1;
public static final int DEFAULT_PAGE_SIZE = 20;
public static final int MAX_PAGE_SIZE = 100;
public static final int MAX_BATCH_SIZE = 500;
public static final long MAX_IMPORT_BYTES = 5L * 1024L * 1024L;
public static final Set<String> ACCOUNT_TYPES = Collections.unmodifiableSet(
new HashSet<>(Arrays.asList(TYPE_STUDENT, TYPE_TEACHER, TYPE_ADMIN)));
public static final Set<String> STUDENT_STATUSES = Collections.unmodifiableSet(
new HashSet<>(Arrays.asList(STATUS_PENDING, STATUS_STUDYING,
STATUS_GRADUATED, STATUS_ARCHIVED)));
public static final Set<String> STAFF_STATUSES = Collections.unmodifiableSet(
new HashSet<>(Arrays.asList(STATUS_ENABLED, STATUS_DISABLED)));
public static final Set<String> BATCH_ACTIONS = Collections.unmodifiableSet(
new HashSet<>(Arrays.asList(ACTION_GRADUATE, ACTION_ARCHIVE,
ACTION_RESET_PASSWORD, ACTION_ENABLE, ACTION_DISABLE)));
private AccountAdminConstants() {
}
/** 将稳定账户类型映射为项目现有phone_role表使用的中文大类角色。 */
public static String broadRoleName(String accountType) {
if (TYPE_STUDENT.equals(accountType)) return ROLE_STUDENT;
if (TYPE_TEACHER.equals(accountType)) return ROLE_TEACHER;
if (TYPE_ADMIN.equals(accountType)) return ROLE_ADMIN;
return null;
}
}
package com.platform.business.controller;
import com.github.pagehelper.PageHelper;
import com.platform.business.constant.AccountAdminConstants;
import com.platform.business.model.dto.AccountAdminQueryDTO;
import com.platform.business.model.dto.AccountAdminSaveDTO;
import com.platform.business.model.dto.AccountBatchActionDTO;
import com.platform.business.model.dto.AccountStatusDTO;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.AccountAdminDetailVO;
import com.platform.business.model.vo.AccountAdminOptionsVO;
import com.platform.business.model.vo.AccountAdminStatisticsVO;
import com.platform.business.model.vo.AccountImportResultVO;
import com.platform.business.service.AccountAdminService;
import com.platform.business.service.AuthenticatedUserService;
import com.platform.controller.BaseController;
import com.platform.exception.BusinessException;
import com.platform.model.resp.Result;
import com.platform.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 管理员端“系统管理-账户管理”接口。
*
* <p>所有入口都从Authorization解析真实登录用户并执行管理员角色校验;请求体中的账户ID
* 只表示被管理对象,绝不参与权限判断。分页、导出和详情使用同一业务服务,确保页面展示与
* 下载结果保持一致。</p>
*/
@Api(tags = "管理员端-账户管理")
@RestController
@RequestMapping("/account/admin")
public class AccountAdminController extends BaseController {
@Resource
private AccountAdminService accountAdminService;
@Resource
private AuthenticatedUserService authenticatedUserService;
@ApiOperation("账户分页列表")
@PostMapping("/page")
public TableDataInfo page(@RequestBody AccountAdminQueryDTO query,
HttpServletRequest request) {
UserEntity operator = requireAdmin(request);
if (query == null) {
throw new BusinessException("查询条件不能为空");
}
normalizePage(query);
startPage(query.getPageNum(), query.getPageSize());
try {
return getDataTable(accountAdminService.page(query, operator.getId()));
} finally {
// 无论参数校验或SQL是否抛错,都清理ThreadLocal分页上下文,避免污染后续请求。
PageHelper.clearPage();
}
}
@ApiOperation("账户类型统计")
@GetMapping("/statistics")
public Result<AccountAdminStatisticsVO> statistics(HttpServletRequest request) {
requireAdmin(request);
return Result.data(accountAdminService.statistics());
}
@ApiOperation("账户表单班级及角色选项")
@GetMapping("/options")
public Result<AccountAdminOptionsVO> options(HttpServletRequest request) {
requireAdmin(request);
return Result.data(accountAdminService.options());
}
@ApiOperation("账户详情")
@GetMapping("/{id}")
public Result<AccountAdminDetailVO> detail(@PathVariable("id") String id,
HttpServletRequest request) {
UserEntity operator = requireAdmin(request);
return Result.data(accountAdminService.detail(id, operator.getId()));
}
@ApiOperation("新增账户")
@PostMapping
public Result<AccountAdminDetailVO> create(@RequestBody AccountAdminSaveDTO body,
HttpServletRequest request) {
UserEntity operator = requireAdmin(request);
return Result.data(accountAdminService.create(body, operator));
}
@ApiOperation("编辑账户")
@PutMapping("/{id}")
public Result<AccountAdminDetailVO> update(@PathVariable("id") String id,
@RequestBody AccountAdminSaveDTO body,
HttpServletRequest request) {
UserEntity operator = requireAdmin(request);
return Result.data(accountAdminService.update(id, body, operator));
}
@ApiOperation("修改单个账户状态")
@PutMapping("/{id}/status")
public Result<Void> changeStatus(@PathVariable("id") String id,
@RequestBody AccountStatusDTO body,
HttpServletRequest request) {
UserEntity operator = requireAdmin(request);
accountAdminService.changeStatus(id, body == null ? null : body.getStatus(), operator);
return Result.data(null);
}
@ApiOperation("重置单个账户密码")
@PostMapping("/{id}/reset-password")
public Result<Void> resetPassword(@PathVariable("id") String id,
HttpServletRequest request) {
UserEntity operator = requireAdmin(request);
accountAdminService.resetPassword(id, operator);
return Result.data(null);
}
@ApiOperation("批量结业、归档、启禁用或重置密码")
@PostMapping("/batch")
public Result<Integer> batch(@RequestBody AccountBatchActionDTO body,
HttpServletRequest request) {
UserEntity operator = requireAdmin(request);
return Result.data(accountAdminService.batch(body, operator));
}
@ApiOperation("预览或确认批量导入账户")
@PostMapping("/import")
public Result<AccountImportResultVO> importAccounts(
@RequestParam("accountType") String accountType,
@RequestParam(value = "classId", required = false) Integer classId,
@RequestParam(value = "preview", defaultValue = "true") boolean preview,
@RequestParam("file") MultipartFile file,
HttpServletRequest request) {
UserEntity operator = requireAdmin(request);
return Result.data(accountAdminService.importAccounts(
accountType, classId, preview, file, operator));
}
@ApiOperation("下载账户批量导入模板")
@GetMapping("/import/template")
public void downloadTemplate(@RequestParam("accountType") String accountType,
HttpServletRequest request,
HttpServletResponse response) {
requireAdmin(request);
accountAdminService.downloadTemplate(accountType, response);
}
@ApiOperation("按当前筛选条件导出全部账户")
@PostMapping("/export")
public void export(@RequestBody AccountAdminQueryDTO query,
HttpServletRequest request,
HttpServletResponse response) {
requireAdmin(request);
accountAdminService.export(query, response);
}
/** 将异常分页值限制在页面支持的1~100条范围。 */
void normalizePage(AccountAdminQueryDTO query) {
if (query.getPageNum() == null || query.getPageNum() < 1) {
query.setPageNum(AccountAdminConstants.DEFAULT_PAGE_NUM);
}
if (query.getPageSize() == null || query.getPageSize() < 1) {
query.setPageSize(AccountAdminConstants.DEFAULT_PAGE_SIZE);
} else if (query.getPageSize() > AccountAdminConstants.MAX_PAGE_SIZE) {
query.setPageSize(AccountAdminConstants.MAX_PAGE_SIZE);
}
}
/** 统一执行JWT解析和管理员鉴权,新增接口时只需复用本方法。 */
private UserEntity requireAdmin(HttpServletRequest request) {
UserEntity operator = authenticatedUserService.current(request);
authenticatedUserService.requireAdmin(operator);
return operator;
}
}
package com.platform.business.mapper;
import com.platform.business.model.dto.AccountAdminQueryDTO;
import com.platform.business.model.vo.AccountAdminDetailVO;
import com.platform.business.model.vo.AccountAdminListVO;
import com.platform.business.model.vo.AccountAdminStatisticsVO;
import com.platform.business.model.vo.AccountAttendanceVO;
import com.platform.business.model.vo.AccountLoginLogVO;
import com.platform.business.model.vo.AccountOptionVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.Date;
import java.util.List;
/** 账户管理专用聚合查询及审计写入Mapper。 */
@Mapper
public interface AccountAdminMapper {
List<AccountAdminListVO> selectAccounts(@Param("query") AccountAdminQueryDTO query,
@Param("broadRole") String broadRole,
@Param("sixMonthsAgo") Date sixMonthsAgo);
AccountAdminDetailVO selectDetail(@Param("id") String id);
List<AccountAttendanceVO> selectAttendance(@Param("userId") String userId);
List<AccountLoginLogVO> selectLoginLogs(@Param("userId") String userId,
@Param("limit") int limit);
AccountAdminStatisticsVO selectStatistics();
List<AccountOptionVO> selectClassOptions();
List<AccountOptionVO> selectRoleOptions(@Param("accountType") String accountType);
Integer selectRoleIdByName(@Param("roleName") String roleName,
@Param("accountType") String accountType);
int countPhone(@Param("phone") String phone, @Param("excludeId") String excludeId);
int countUsername(@Param("username") String username, @Param("excludeId") String excludeId);
int countEmployeeNo(@Param("employeeNo") String employeeNo, @Param("excludeId") String excludeId);
String selectAccountType(@Param("userId") String userId);
int insertOperationLog(@Param("operatorId") String operatorId,
@Param("operatorName") String operatorName,
@Param("targetUserId") String targetUserId,
@Param("action") String action,
@Param("detail") String detail,
@Param("operationTime") Date operationTime);
}
package com.platform.business.service;
import com.platform.business.model.dto.AccountAdminQueryDTO;
import com.platform.business.model.dto.AccountAdminSaveDTO;
import com.platform.business.model.dto.AccountBatchActionDTO;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.AccountAdminDetailVO;
import com.platform.business.model.vo.AccountAdminListVO;
import com.platform.business.model.vo.AccountAdminOptionsVO;
import com.platform.business.model.vo.AccountAdminStatisticsVO;
import com.platform.business.model.vo.AccountImportResultVO;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/** 管理员端“系统管理-账户管理”业务接口。 */
public interface AccountAdminService {
List<AccountAdminListVO> page(AccountAdminQueryDTO query, String currentUserId);
AccountAdminStatisticsVO statistics();
AccountAdminOptionsVO options();
AccountAdminDetailVO detail(String id, String currentUserId);
AccountAdminDetailVO create(AccountAdminSaveDTO request, UserEntity operator);
AccountAdminDetailVO update(String id, AccountAdminSaveDTO request, UserEntity operator);
void changeStatus(String id, String status, UserEntity operator);
void resetPassword(String id, UserEntity operator);
int batch(AccountBatchActionDTO request, UserEntity operator);
AccountImportResultVO importAccounts(String accountType, Integer classId,
boolean preview, MultipartFile file,
UserEntity operator);
void downloadTemplate(String accountType, HttpServletResponse response);
void export(AccountAdminQueryDTO query, HttpServletResponse response);
}
# 管理员端账户管理接口
接口前缀:`/account/admin`。除登录接口外,下面所有接口都必须携带 `Authorization`,
服务端会解析JWT并校验“管理员”大类角色。
## 页面初始化与查询
| 方法 | 路径 | 说明 |
| --- | --- | --- |
| GET | `/statistics` | 返回学员/教师/管理员总数及活跃数,用于Tab角标 |
| GET | `/options` | 返回班级、教师角色、管理员角色选项 |
| POST | `/page` | 三类账户分页筛选 |
| GET | `/{id}` | 账户详情;学员额外返回课程出勤、成绩摘要、登录日志 |
`POST /page` 示例:
```json
{
"pageNum": 1,
"pageSize": 20,
"accountType": "STUDENT",
"keyword": "张",
"classId": 12,
"status": "STUDYING",
"startDate": "2026-01-01",
"endDate": "2026-12-31",
"archiveOverSixMonths": false
}
```
状态约定:学员为 `PENDING / STUDYING / GRADUATED / ARCHIVED`;教师和管理员为
`ENABLED / DISABLED`。`archiveOverSixMonths=true` 时只返回结业满六个月且尚未归档的学员。
## 新增、编辑与状态
| 方法 | 路径 | 说明 |
| --- | --- | --- |
| POST | `/` | 新增学员、教师或管理员 |
| PUT | `/{id}` | 编辑基础信息、班级或角色 |
| PUT | `/{id}/status` | 修改单个账户状态 |
| POST | `/{id}/reset-password` | 重置为 `Wssg@2026` |
| POST | `/batch` | 批量结业、归档、启禁用或重置密码 |
新增教师示例:
```json
{
"accountType": "TEACHER",
"name": "王老师",
"employeeNo": "T-2026-001",
"phoneNumber": "13800138000",
"roleId": 8,
"initialPassword": "Wssg@2026",
"status": "ENABLED"
}
```
新增管理员时以 `username` 作为登录账号;新增教师时以 `employeeNo` 作为登录账号;学员固定以
手机号作为登录账号。认证接口仍接收原字段 `phoneNumber`,但字段值现在可以是手机号、教师工号
或管理员登录账号。
批量请求示例:
```json
{
"ids": ["1912345678901234567", "1912345678901234568"],
"action": "GRADUATE"
}
```
动作支持 `GRADUATE / ARCHIVE / RESET_PASSWORD / ENABLE / DISABLE`,单次最多500个ID。
服务端会阻止管理员禁用当前登录的自己。
## Excel导入与导出
| 方法 | 路径 | 说明 |
| --- | --- | --- |
| GET | `/import/template?accountType=STUDENT` | 下载对应类型模板 |
| POST | `/import` | `multipart/form-data`预览或确认导入 |
| POST | `/export` | 按与分页相同的筛选条件导出全部匹配账户 |
导入参数:`accountType`、学员必填的 `classId`、`preview` 和 `file`。前端先以
`preview=true` 上传并展示逐行校验结果,用户确认后用同一文件以 `preview=false` 再次提交。
服务端只落库校验通过的行,单次最多500条、文件最大5MB。
## 数据库
发布前执行 `src/main/resources/sql/account_management.sql`。脚本新增账户状态、工号、结业/归档时间、
角色适用端字段,以及登录日志和账户操作审计表;脚本可重复执行,并在末尾输出需要人工处理的
未分类角色和历史重复账号。
<?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.AccountAdminMapper">
<!--
每个用户可能存在历史班级或角色关系。账户页面只展示最后创建的一条关系,
详情中的历史课程仍通过出勤表完整查询,避免关系重复导致分页总数膨胀。
-->
<sql id="accountJoins">
left join class_student cs on cs.id = (
select max(cs2.id) from class_student cs2 where cs2.user_id = u.id
)
left join `class` c on c.id = cs.class_id
left join sys_level level_info on cast(level_info.id as char) = c.level
left join sys_user_and_role ur on ur.id = (
select max(ur2.id) from sys_user_and_role ur2 where ur2.user_id = u.id
)
left join role r on r.id = ur.role_id
</sql>
<sql id="statusExpression">
case
when #{query.accountType} = 'STUDENT' then coalesce(
nullif(u.account_status, ''),
case when coalesce(u.del_flag, 0) = 1 then 'ARCHIVED'
when coalesce(u.first_login_flag, 1) = 1 then 'PENDING'
else 'STUDYING' end)
else coalesce(
nullif(u.account_status, ''),
case when coalesce(u.del_flag, 0) = 1 then 'DISABLED' else 'ENABLED' end)
end
</sql>
<select id="selectAccounts" resultType="com.platform.business.model.vo.AccountAdminListVO">
select
u.id,
#{query.accountType} as accountType,
u.nick_name as name,
u.username,
u.employee_no as employeeNo,
u.phone_number as phoneNumber,
c.id as classId,
c.name as className,
coalesce(level_info.name, u.level) as levelName,
r.id as roleId,
r.name as roleName,
<include refid="statusExpression"/> as status,
c.start_date as trainingStartDate,
c.end_date as trainingEndDate,
u.login_date as lastLoginTime,
u.create_time as createTime
from user u
<include refid="accountJoins"/>
where exists (
select 1 from phone_role pr
where pr.phone = u.phone_number and pr.role_name = #{broadRole}
)
<if test="query.keyword != null and query.keyword != ''">
and (u.nick_name like concat('%', #{query.keyword}, '%')
or u.phone_number like concat('%', #{query.keyword}, '%')
or u.username like concat('%', #{query.keyword}, '%')
or u.employee_no like concat('%', #{query.keyword}, '%'))
</if>
<if test="query.classId != null">
and c.id = #{query.classId}
</if>
<if test="query.roleId != null">
and r.id = #{query.roleId}
</if>
<if test="query.status != null and query.status != ''">
and <include refid="statusExpression"/> = #{query.status}
</if>
<choose>
<when test="query.accountType == 'STUDENT'">
<if test="query.startDate != null">and c.start_date &gt;= #{query.startDate}</if>
<if test="query.endDate != null">and c.end_date &lt;= #{query.endDate}</if>
</when>
<otherwise>
<if test="query.startDate != null">and u.login_date &gt;= #{query.startDate}</if>
<!-- 结束日期加一天后使用小于比较,确保包含结束日全天。 -->
<if test="query.endDate != null">and u.login_date &lt; date_add(#{query.endDate}, interval 1 day)</if>
</otherwise>
</choose>
<if test="query.archiveOverSixMonths == true">
and <include refid="statusExpression"/> = 'GRADUATED'
and coalesce(u.graduation_time, c.end_date) &lt;= #{sixMonthsAgo}
</if>
order by coalesce(u.create_time, u.update_time, u.login_date) desc, u.id desc
</select>
<select id="selectDetail" resultType="com.platform.business.model.vo.AccountAdminDetailVO">
select
u.id,
case when exists(select 1 from phone_role p where p.phone=u.phone_number and p.role_name='学生') then 'STUDENT'
when exists(select 1 from phone_role p where p.phone=u.phone_number and p.role_name='教师') then 'TEACHER'
when exists(select 1 from phone_role p where p.phone=u.phone_number and p.role_name='管理员') then 'ADMIN'
else null end as accountType,
u.nick_name as name,
u.username,
u.employee_no as employeeNo,
u.phone_number as phoneNumber,
c.id as classId,
c.name as className,
coalesce(level_info.name, u.level) as levelName,
r.id as roleId,
r.name as roleName,
case
when exists(select 1 from phone_role p where p.phone=u.phone_number and p.role_name='学生')
then coalesce(nullif(u.account_status, ''),
case when coalesce(u.del_flag,0)=1 then 'ARCHIVED'
when coalesce(u.first_login_flag,1)=1 then 'PENDING'
else 'STUDYING' end)
else coalesce(nullif(u.account_status, ''),
case when coalesce(u.del_flag,0)=1 then 'DISABLED' else 'ENABLED' end)
end as status,
c.start_date as trainingStartDate,
c.end_date as trainingEndDate,
u.login_date as lastLoginTime,
u.create_time as createTime,
u.id_card as idCard,
coalesce(u.company_name2, u.company_name1, u.factory) as companyName,
u.remark,
u.cert_no as certificateNo,
u.graduation_time as graduationTime,
u.archive_time as archiveTime,
(select max(es.score) from exam_student es inner join exam e on e.id=es.exam_id
where es.student_id=u.id and es.mark_flag=1 and e.type like '%理论%') as theoryScore,
(select max(es.score) from exam_student es inner join exam e on e.id=es.exam_id
where es.student_id=u.id and es.mark_flag=1 and e.type like '%实训%') as practicalScore,
(select coalesce(sum(s.subject_hour),0) from class_subject s where s.class_id=c.id) as scheduledHours,
(select coalesce(sum(s.subject_hour),0)
from class_subject_attendance a inner join class_subject s on s.id=a.subject_id
where a.user_id=u.id and a.status in ('NORMAL','LATE')) as attendedHours
from user u
<include refid="accountJoins"/>
where u.id = #{id}
</select>
<select id="selectAttendance" resultType="com.platform.business.model.vo.AccountAttendanceVO">
select s.date as courseDate,
s.subject_name as courseName,
s.time_frame as timeFrame,
s.subject_hour as courseHours,
a.status as attendanceStatus,
teacher.nick_name as teacherName
from class_subject_attendance a
inner join class_subject s on s.id = a.subject_id
left join user teacher on teacher.id = s.teacher_id
where a.user_id = #{userId}
order by s.date desc, s.id desc
limit 200
</select>
<select id="selectLoginLogs" resultType="com.platform.business.model.vo.AccountLoginLogVO">
select login_time as loginTime,
ip_address as ipAddress,
device,
result,
failure_reason as failureReason
from account_login_log
where user_id = #{userId}
order by login_time desc, id desc
limit #{limit}
</select>
<select id="selectStatistics" resultType="com.platform.business.model.vo.AccountAdminStatisticsVO">
select
count(distinct case when pr.role_name='学生' then u.id end) as studentTotal,
count(distinct case when pr.role_name='学生' and coalesce(nullif(u.account_status,''),
case when coalesce(u.del_flag,0)=1 then 'ARCHIVED' when coalesce(u.first_login_flag,1)=1 then 'PENDING' else 'STUDYING' end)
in ('PENDING','STUDYING') then u.id end) as studentActive,
count(distinct case when pr.role_name='教师' then u.id end) as teacherTotal,
count(distinct case when pr.role_name='教师' and coalesce(nullif(u.account_status,''),
case when coalesce(u.del_flag,0)=1 then 'DISABLED' else 'ENABLED' end)='ENABLED' then u.id end) as teacherEnabled,
count(distinct case when pr.role_name='管理员' then u.id end) as adminTotal,
count(distinct case when pr.role_name='管理员' and coalesce(nullif(u.account_status,''),
case when coalesce(u.del_flag,0)=1 then 'DISABLED' else 'ENABLED' end)='ENABLED' then u.id end) as adminEnabled
from user u
inner join phone_role pr on pr.phone = u.phone_number
</select>
<select id="selectClassOptions" resultType="com.platform.business.model.vo.AccountOptionVO">
select cast(c.id as char) as value,
c.name as label,
coalesce(level_info.name, cast(c.level as char)) as extra
from `class` c
left join sys_level level_info on cast(level_info.id as char)=c.level
order by c.training_year desc, c.name asc, c.id asc
</select>
<select id="selectRoleOptions" resultType="com.platform.business.model.vo.AccountOptionVO">
select cast(id as char) as value, name as label, description as extra
from role
where account_type = #{accountType}
order by id asc
</select>
<select id="selectRoleIdByName" resultType="java.lang.Integer">
select id from role
where name = #{roleName} and account_type = #{accountType}
order by id asc limit 1
</select>
<select id="countPhone" resultType="int">
select count(*) from user where phone_number=#{phone}
<if test="excludeId != null and excludeId != ''">and id != #{excludeId}</if>
</select>
<select id="countUsername" resultType="int">
select count(*) from user where username=#{username}
<if test="excludeId != null and excludeId != ''">and id != #{excludeId}</if>
</select>
<select id="countEmployeeNo" resultType="int">
select count(*) from user where employee_no=#{employeeNo}
<if test="excludeId != null and excludeId != ''">and id != #{excludeId}</if>
</select>
<select id="selectAccountType" resultType="java.lang.String">
select case pr.role_name when '学生' then 'STUDENT' when '教师' then 'TEACHER'
when '管理员' then 'ADMIN' else null end
from user u inner join phone_role pr on pr.phone=u.phone_number
where u.id=#{userId} and pr.role_name in ('学生','教师','管理员')
order by field(pr.role_name,'管理员','教师','学生') limit 1
</select>
<insert id="insertOperationLog">
insert into account_operation_log
(operator_id, operator_name, target_user_id, action, detail, operation_time)
values
(#{operatorId}, #{operatorName}, #{targetUserId}, #{action}, #{detail}, #{operationTime})
</insert>
</mapper>
-- 管理员端“系统管理-账户管理”增量数据库脚本(MySQL 5.7+/8.0)。
--
-- 执行顺序:先备份数据库,再执行本文件,最后发布practical-auth和practical-business。
-- 设计说明:
-- 1. 脚本通过information_schema逐项判断,可重复执行,不会重复添加字段或索引。
-- 2. del_flag仍由认证服务识别;account_status保存页面业务状态,两者由服务层同步维护。
-- 3. 角色表新增account_type后,角色下拉不再通过中文名称猜测适用范围。
-- 4. 项目现有关系表没有外键,本脚本沿用同一风格,删除/归档采用逻辑状态而非物理删除。
delimiter $$
drop procedure if exists migrate_account_management$$
create procedure migrate_account_management()
begin
if not exists (
select 1 from information_schema.columns
where table_schema=database() and table_name='user' and column_name='create_time'
) then
alter table user add column create_time datetime null comment '账户创建时间' after update_time;
end if;
if not exists (
select 1 from information_schema.columns
where table_schema=database() and table_name='user' and column_name='employee_no'
) then
alter table user add column employee_no varchar(50) null comment '教师工号' after username;
end if;
if not exists (
select 1 from information_schema.columns
where table_schema=database() and table_name='user' and column_name='account_status'
) then
alter table user add column account_status varchar(20) null
comment '学员PENDING/STUDYING/GRADUATED/ARCHIVED;教职工ENABLED/DISABLED'
after first_login_flag;
end if;
if not exists (
select 1 from information_schema.columns
where table_schema=database() and table_name='user' and column_name='graduation_time'
) then
alter table user add column graduation_time datetime null comment '学员结业时间' after account_status;
end if;
if not exists (
select 1 from information_schema.columns
where table_schema=database() and table_name='user' and column_name='archive_time'
) then
alter table user add column archive_time datetime null comment '账户归档时间' after graduation_time;
end if;
if not exists (
select 1 from information_schema.columns
where table_schema=database() and table_name='role' and column_name='account_type'
) then
alter table role add column account_type varchar(20) null
comment '角色适用账户类型:STUDENT/TEACHER/ADMIN' after description;
end if;
if not exists (
select 1 from information_schema.statistics
where table_schema=database() and table_name='user' and index_name='idx_user_account_status'
) then
alter table user add index idx_user_account_status (account_status, del_flag);
end if;
if not exists (
select 1 from information_schema.statistics
where table_schema=database() and table_name='user' and index_name='idx_user_phone'
) then
alter table user add index idx_user_phone (phone_number);
end if;
if not exists (
select 1 from information_schema.statistics
where table_schema=database() and table_name='user' and index_name='idx_user_username'
) then
alter table user add index idx_user_username (username);
end if;
if not exists (
select 1 from information_schema.statistics
where table_schema=database() and table_name='user' and index_name='idx_user_employee_no'
) then
alter table user add index idx_user_employee_no (employee_no);
end if;
end$$
call migrate_account_management()$$
drop procedure if exists migrate_account_management$$
delimiter ;
-- 登录成功和失败均保留日志。user_id允许NULL,以便记录不存在账号的尝试。
create table if not exists account_login_log (
id bigint not null auto_increment comment '日志ID',
user_id varchar(64) null comment '用户ID;用户不存在时为空',
login_name varchar(100) null comment '本次提交的登录账号',
login_time datetime not null default current_timestamp comment '登录时间',
ip_address varchar(64) null comment '服务端识别的客户端IP',
device varchar(255) null comment 'User-Agent/终端描述',
result varchar(20) not null comment 'SUCCESS/FAILED',
failure_reason varchar(255) null comment '失败原因',
primary key (id),
key idx_account_login_user_time (user_id, login_time),
key idx_account_login_name_time (login_name, login_time)
) engine=InnoDB default charset=utf8mb4 comment='账户登录日志';
-- 管理端所有写操作的审计记录,满足批量结业、归档和重置密码的追溯要求。
create table if not exists account_operation_log (
id bigint not null auto_increment comment '日志ID',
operator_id varchar(64) null comment '操作管理员用户ID',
operator_name varchar(100) null comment '操作管理员姓名快照',
target_user_id varchar(64) null comment '被操作账户ID',
action varchar(50) not null comment 'CREATE/UPDATE/CHANGE_STATUS/RESET_PASSWORD',
detail varchar(500) null comment '操作摘要',
operation_time datetime not null default current_timestamp comment '操作时间',
primary key (id),
key idx_account_operation_target_time (target_user_id, operation_time),
key idx_account_operation_operator_time (operator_id, operation_time)
) engine=InnoDB default charset=utf8mb4 comment='账户管理操作审计日志';
-- 兼容旧数据:优先根据phone_role大类角色推导账户状态,不覆盖已经人工维护的状态。
update user u
set u.account_status = case
when exists(select 1 from phone_role p where p.phone=u.phone_number and p.role_name='学生')
then case when coalesce(u.del_flag,0)=1 then 'ARCHIVED'
when coalesce(u.first_login_flag,1)=1 then 'PENDING'
else 'STUDYING' end
when coalesce(u.del_flag,0)=1 then 'DISABLED'
else 'ENABLED'
end
where u.account_status is null or trim(u.account_status)='';
-- 从现有中文角色名尽力标注适用端;无法可靠识别的角色保持NULL,需按下方检查结果人工确认。
update role
set account_type = case
when name in ('学生','学员') then 'STUDENT'
when name like '%管理员%' or name like '%审计%' then 'ADMIN'
when name like '%教师%' or name like '%讲师%' or name like '%教练%'
or name like '%考评员%' or name like '%安全员%' then 'TEACHER'
else account_type
end
where account_type is null or trim(account_type)='';
-- 使用已有时间尽力回填创建时间;完全没有历史时间的账户保留NULL,避免伪造创建日期。
update user
set create_time=coalesce(create_time, update_time, login_date)
where create_time is null;
-- 发布前检查:以下结果应由管理员人工补齐role.account_type,否则对应角色不会出现在新增账户下拉框。
select id, name, description, account_type
from role
where account_type is null
or account_type not in ('STUDENT','TEACHER','ADMIN');
-- 发布前检查:重复手机号/账号不会被脚本强行删除,需确认后人工合并;应用层已阻止新增重复值。
select phone_number, count(*) as duplicate_count
from user
where phone_number is not null and trim(phone_number)<>''
group by phone_number
having count(*) > 1;
select username, count(*) as duplicate_count
from user
where username is not null and trim(username)<>''
group by username
having count(*) > 1;
package com.platform.business.controller;
import com.platform.business.constant.AccountAdminConstants;
import com.platform.business.model.dto.AccountAdminQueryDTO;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.AccountAdminStatisticsVO;
import com.platform.business.service.AccountAdminService;
import com.platform.business.service.AuthenticatedUserService;
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.mock.web.MockHttpServletRequest;
import org.springframework.test.util.ReflectionTestUtils;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** 账户管理控制器的分页边界及管理员鉴权测试。 */
@ExtendWith(MockitoExtension.class)
class AccountAdminControllerTest {
@Mock
private AccountAdminService accountAdminService;
@Mock
private AuthenticatedUserService authenticatedUserService;
private AccountAdminController controller;
@BeforeEach
void setUp() {
controller = new AccountAdminController();
ReflectionTestUtils.setField(controller, "accountAdminService", accountAdminService);
ReflectionTestUtils.setField(controller, "authenticatedUserService", authenticatedUserService);
}
@Test
void normalizePageShouldApplyDefaultsAndMaximum() {
AccountAdminQueryDTO defaults = new AccountAdminQueryDTO();
controller.normalizePage(defaults);
assertEquals(AccountAdminConstants.DEFAULT_PAGE_NUM, defaults.getPageNum());
assertEquals(AccountAdminConstants.DEFAULT_PAGE_SIZE, defaults.getPageSize());
AccountAdminQueryDTO oversized = new AccountAdminQueryDTO();
oversized.setPageNum(2);
oversized.setPageSize(999);
controller.normalizePage(oversized);
assertEquals(2, oversized.getPageNum());
assertEquals(AccountAdminConstants.MAX_PAGE_SIZE, oversized.getPageSize());
}
@Test
void statisticsShouldRequireAdministratorBeforeQueryingData() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserEntity administrator = new UserEntity();
when(authenticatedUserService.current(request)).thenReturn(administrator);
when(accountAdminService.statistics()).thenReturn(new AccountAdminStatisticsVO());
controller.statistics(request);
verify(authenticatedUserService).requireAdmin(administrator);
verify(accountAdminService).statistics();
}
@Test
void statisticsShouldStopWhenCurrentUserIsNotAdministrator() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserEntity student = new UserEntity();
when(authenticatedUserService.current(request)).thenReturn(student);
doThrow(new BusinessException("只有管理员可以访问管理端接口"))
.when(authenticatedUserService).requireAdmin(student);
assertThrows(BusinessException.class, () -> controller.statistics(request));
}
}
package com.platform.business.mapper;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.session.Configuration;
import org.junit.jupiter.api.Test;
import java.io.InputStream;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/** 防止账户管理Mapper XML在合并时出现标签未闭合或关键语句被误删。 */
class AccountAdminMapperXmlTest {
@Test
void mapperXmlShouldBeWellFormedAndContainCoreStatements() throws Exception {
try (InputStream input = getClass().getClassLoader().getResourceAsStream(
"com/platform/business/mapper/AccountAdminMapper.xml")) {
assertNotNull(input);
Configuration configuration = new Configuration();
new XMLMapperBuilder(input, configuration,
"com/platform/business/mapper/AccountAdminMapper.xml",
configuration.getSqlFragments()).parse();
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.AccountAdminMapper.selectAccounts"));
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.AccountAdminMapper.selectDetail"));
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.AccountAdminMapper.insertOperationLog"));
}
}
}
package com.platform.business.service.impl;
import com.platform.business.model.dto.AccountAdminQueryDTO;
import com.platform.exception.BusinessException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Date;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
/** 账户查询参数的类型、状态和日期边界测试。 */
class AccountAdminServiceImplTest {
private AccountAdminServiceImpl service;
@BeforeEach
void setUp() {
service = new AccountAdminServiceImpl();
}
@Test
void normalizeStudentQueryShouldTrimAndRemoveStaffOnlyRoleFilter() {
AccountAdminQueryDTO query = new AccountAdminQueryDTO();
query.setAccountType(" student ");
query.setKeyword(" 张三 ");
query.setStatus(" studying ");
query.setRoleId(9);
service.normalizeQuery(query);
assertEquals("STUDENT", query.getAccountType());
assertEquals("张三", query.getKeyword());
assertEquals("STUDYING", query.getStatus());
assertNull(query.getRoleId());
}
@Test
void normalizeStaffQueryShouldRemoveStudentOnlyFilters() {
AccountAdminQueryDTO query = new AccountAdminQueryDTO();
query.setAccountType("TEACHER");
query.setStatus("ENABLED");
query.setClassId(12);
query.setArchiveOverSixMonths(true);
service.normalizeQuery(query);
assertNull(query.getClassId());
assertFalse(query.getArchiveOverSixMonths());
}
@Test
void normalizeQueryShouldRejectCrossTypeStatusAndReversedDates() {
AccountAdminQueryDTO wrongStatus = new AccountAdminQueryDTO();
wrongStatus.setAccountType("STUDENT");
wrongStatus.setStatus("ENABLED");
assertThrows(BusinessException.class, () -> service.normalizeQuery(wrongStatus));
AccountAdminQueryDTO reversed = new AccountAdminQueryDTO();
reversed.setAccountType("ADMIN");
reversed.setStartDate(new Date(2_000L));
reversed.setEndDate(new Date(1_000L));
assertThrows(BusinessException.class, () -> service.normalizeQuery(reversed));
}
}
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