Skip to content
GitLab
Menu
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Menu
Open sidebar
邬吉朋
practical_train
Commits
dd2bf60f
"...src/main/resources/mapper/SysRolePermissionMapper.xml" did not exist on "aacb89eaed7ecafbc624b01ec71da8e4c68b564a"
Commit
dd2bf60f
authored
Aug 19, 2026
by
wujipeng
Browse files
管理员-系统管理-账户管理
parent
9fc77652
Changes
32
Show whitespace changes
Inline
Side-by-side
practical-auth/src/main/resources/com/platform/auth/mapper/USerMapper.xml
0 → 100644
View file @
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.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>
practical-business/src/main/java/com/platform/business/constant/AccountAdminConstants.java
0 → 100644
View file @
dd2bf60f
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
;
}
}
practical-business/src/main/java/com/platform/business/controller/AccountAdminController.java
0 → 100644
View file @
dd2bf60f
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
;
}
}
practical-business/src/main/java/com/platform/business/mapper/AccountAdminMapper.java
0 → 100644
View file @
dd2bf60f
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
);
}
practical-business/src/main/java/com/platform/business/service/AccountAdminService.java
0 → 100644
View file @
dd2bf60f
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
);
}
practical-business/src/main/java/com/platform/business/service/impl/AccountAdminServiceImpl.java
0 → 100644
View file @
dd2bf60f
package
com.platform.business.service.impl
;
import
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper
;
import
com.platform.business.constant.AccountAdminConstants
;
import
com.platform.business.mapper.AccountAdminMapper
;
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.AccountImportRowDTO
;
import
com.platform.business.model.entity.ClassEntity
;
import
com.platform.business.model.entity.ClassStudentEntity
;
import
com.platform.business.model.entity.SysPhoneRoleEntity
;
import
com.platform.business.model.entity.SysRoleEntity
;
import
com.platform.business.model.entity.SysUserAndRoleEntity
;
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
com.platform.business.service.AccountAdminService
;
import
com.platform.business.service.ClassStudentService
;
import
com.platform.business.service.SysPhoneRoleService
;
import
com.platform.business.service.SysRoleService
;
import
com.platform.business.service.SysUserAndRoleService
;
import
com.platform.business.service.UserService
;
import
com.platform.business.utils.PasswordUtil
;
import
com.platform.exception.BusinessException
;
import
org.apache.poi.ss.usermodel.Cell
;
import
org.apache.poi.ss.usermodel.DataFormatter
;
import
org.apache.poi.ss.usermodel.Row
;
import
org.apache.poi.ss.usermodel.Sheet
;
import
org.apache.poi.ss.usermodel.Workbook
;
import
org.apache.poi.ss.usermodel.WorkbookFactory
;
import
org.apache.poi.xssf.usermodel.XSSFWorkbook
;
import
org.springframework.stereotype.Service
;
import
org.springframework.transaction.annotation.Transactional
;
import
org.springframework.web.multipart.MultipartFile
;
import
javax.annotation.Resource
;
import
javax.servlet.http.HttpServletResponse
;
import
java.io.IOException
;
import
java.io.OutputStream
;
import
java.net.URLEncoder
;
import
java.time.LocalDate
;
import
java.time.ZoneId
;
import
java.util.ArrayList
;
import
java.util.Collections
;
import
java.util.Date
;
import
java.util.HashSet
;
import
java.util.List
;
import
java.util.Locale
;
import
java.util.Set
;
import
java.util.regex.Pattern
;
/**
* 管理员端账户管理实现。
*
* <p>该实现刻意不复用历史 {@link UserServiceImpl#saveOrUpdateUser}:旧方法会把所有新用户
* 写成“管理员”大类角色,也缺少班级、状态和唯一性校验。独立实现能够保证账户页面的
* 状态机、关系表和认证服务的del_flag始终同步,同时不改变旧页面的调用契约。</p>
*/
@Service
public
class
AccountAdminServiceImpl
implements
AccountAdminService
{
private
static
final
ZoneId
BUSINESS_ZONE
=
ZoneId
.
of
(
"Asia/Shanghai"
);
private
static
final
Pattern
PHONE_PATTERN
=
Pattern
.
compile
(
"^1[3-9]\\d{9}$"
);
private
static
final
Pattern
ACCOUNT_PATTERN
=
Pattern
.
compile
(
"^[A-Za-z0-9._-]{3,50}$"
);
private
static
final
int
LOGIN_LOG_LIMIT
=
100
;
@Resource
private
AccountAdminMapper
accountAdminMapper
;
@Resource
private
UserService
userService
;
@Resource
private
SysPhoneRoleService
phoneRoleService
;
@Resource
private
SysUserAndRoleService
userRoleService
;
@Resource
private
SysRoleService
roleService
;
@Resource
private
ClassStudentService
classStudentService
;
@Resource
private
com
.
platform
.
business
.
mapper
.
ClassMapper
classMapper
;
@Resource
private
PasswordUtil
passwordUtil
;
@Override
@Transactional
(
readOnly
=
true
)
public
List
<
AccountAdminListVO
>
page
(
AccountAdminQueryDTO
query
,
String
currentUserId
)
{
AccountAdminQueryDTO
normalized
=
normalizeQuery
(
query
);
List
<
AccountAdminListVO
>
rows
=
accountAdminMapper
.
selectAccounts
(
normalized
,
AccountAdminConstants
.
broadRoleName
(
normalized
.
getAccountType
()),
sixMonthsAgo
());
if
(
rows
==
null
)
{
return
Collections
.
emptyList
();
}
for
(
AccountAdminListVO
row
:
rows
)
{
row
.
setCurrentUser
(
row
.
getId
()
!=
null
&&
row
.
getId
().
equals
(
currentUserId
));
}
return
rows
;
}
@Override
@Transactional
(
readOnly
=
true
)
public
AccountAdminStatisticsVO
statistics
()
{
AccountAdminStatisticsVO
result
=
accountAdminMapper
.
selectStatistics
();
return
result
==
null
?
new
AccountAdminStatisticsVO
()
:
result
;
}
@Override
@Transactional
(
readOnly
=
true
)
public
AccountAdminOptionsVO
options
()
{
AccountAdminOptionsVO
result
=
new
AccountAdminOptionsVO
();
result
.
setClasses
(
accountAdminMapper
.
selectClassOptions
());
result
.
setTeacherRoles
(
accountAdminMapper
.
selectRoleOptions
(
AccountAdminConstants
.
TYPE_TEACHER
));
result
.
setAdminRoles
(
accountAdminMapper
.
selectRoleOptions
(
AccountAdminConstants
.
TYPE_ADMIN
));
return
result
;
}
@Override
@Transactional
(
readOnly
=
true
)
public
AccountAdminDetailVO
detail
(
String
id
,
String
currentUserId
)
{
requireId
(
id
);
AccountAdminDetailVO
detail
=
accountAdminMapper
.
selectDetail
(
id
);
if
(
detail
==
null
||
detail
.
getAccountType
()
==
null
)
{
throw
new
BusinessException
(
"账户不存在或未配置账户类型"
);
}
detail
.
setCurrentUser
(
id
.
equals
(
currentUserId
));
if
(
AccountAdminConstants
.
TYPE_STUDENT
.
equals
(
detail
.
getAccountType
()))
{
detail
.
setAttendanceRecords
(
accountAdminMapper
.
selectAttendance
(
id
));
}
else
{
detail
.
setAttendanceRecords
(
Collections
.
emptyList
());
}
detail
.
setLoginLogs
(
accountAdminMapper
.
selectLoginLogs
(
id
,
LOGIN_LOG_LIMIT
));
return
detail
;
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
AccountAdminDetailVO
create
(
AccountAdminSaveDTO
request
,
UserEntity
operator
)
{
validateAndNormalizeSave
(
request
,
null
,
true
);
String
type
=
request
.
getAccountType
();
String
status
=
defaultStatus
(
type
,
request
.
getStatus
());
UserEntity
user
=
new
UserEntity
();
applyEditableFields
(
user
,
request
,
type
);
user
.
setPassword
(
passwordUtil
.
encodePassword
(
defaultPassword
(
request
.
getInitialPassword
())));
user
.
setLoginFailNum
(
0
);
user
.
setFirstLoginFlag
(
true
);
user
.
setAccountStatus
(
status
);
user
.
setDelFlag
(
isLoginDisabled
(
status
));
user
.
setCreateTime
(
new
Date
());
user
.
setUpdateTime
(
new
Date
());
user
.
setIdType
(
idType
(
type
));
if
(!
userService
.
save
(
user
)
||
user
.
getId
()
==
null
)
{
throw
new
BusinessException
(
"账户创建失败,请稍后重试"
);
}
saveBroadRole
(
user
.
getPhoneNumber
(),
type
);
saveRelations
(
user
.
getId
(),
request
,
type
);
writeAudit
(
operator
,
user
.
getId
(),
"CREATE"
,
"新增"
+
typeLabel
(
type
)
+
"账户"
);
return
detail
(
user
.
getId
(),
operator
==
null
?
null
:
operator
.
getId
());
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
AccountAdminDetailVO
update
(
String
id
,
AccountAdminSaveDTO
request
,
UserEntity
operator
)
{
requireId
(
id
);
UserEntity
existing
=
requireUser
(
id
);
String
storedType
=
requireAccountType
(
id
);
if
(
request
==
null
)
{
throw
new
BusinessException
(
"账户信息不能为空"
);
}
if
(
request
.
getAccountType
()
==
null
||
request
.
getAccountType
().
trim
().
isEmpty
())
{
request
.
setAccountType
(
storedType
);
}
validateAndNormalizeSave
(
request
,
id
,
false
);
if
(!
storedType
.
equals
(
request
.
getAccountType
()))
{
throw
new
BusinessException
(
"账户类型创建后不可修改"
);
}
String
oldPhone
=
existing
.
getPhoneNumber
();
applyEditableFields
(
existing
,
request
,
storedType
);
if
(
request
.
getStatus
()
!=
null
)
{
String
normalizedStatus
=
normalizeStatus
(
storedType
,
request
.
getStatus
());
existing
.
setAccountStatus
(
normalizedStatus
);
existing
.
setDelFlag
(
isLoginDisabled
(
normalizedStatus
));
}
existing
.
setUpdateTime
(
new
Date
());
if
(!
userService
.
updateById
(
existing
))
{
throw
new
BusinessException
(
"账户更新失败,请刷新后重试"
);
}
// 手机号是phone_role的关联键,编辑手机号时必须同步迁移大类角色映射。
if
(!
oldPhone
.
equals
(
existing
.
getPhoneNumber
()))
{
phoneRoleService
.
remove
(
new
LambdaQueryWrapper
<
SysPhoneRoleEntity
>()
.
eq
(
SysPhoneRoleEntity:
:
getPhone
,
oldPhone
)
.
eq
(
SysPhoneRoleEntity:
:
getRoleName
,
AccountAdminConstants
.
broadRoleName
(
storedType
)));
saveBroadRole
(
existing
.
getPhoneNumber
(),
storedType
);
}
saveRelations
(
id
,
request
,
storedType
);
writeAudit
(
operator
,
id
,
"UPDATE"
,
"编辑"
+
typeLabel
(
storedType
)
+
"账户"
);
return
detail
(
id
,
operator
==
null
?
null
:
operator
.
getId
());
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
void
changeStatus
(
String
id
,
String
status
,
UserEntity
operator
)
{
requireId
(
id
);
UserEntity
user
=
requireUser
(
id
);
String
type
=
requireAccountType
(
id
);
String
target
=
normalizeStatus
(
type
,
status
);
if
(
operator
!=
null
&&
id
.
equals
(
operator
.
getId
())
&&
isLoginDisabled
(
target
))
{
throw
new
BusinessException
(
"不能禁用或归档当前登录账户"
);
}
String
current
=
effectiveStatus
(
user
,
type
);
if
(
AccountAdminConstants
.
TYPE_STUDENT
.
equals
(
type
))
{
validateStudentTransition
(
current
,
target
);
if
(
AccountAdminConstants
.
STATUS_GRADUATED
.
equals
(
target
)
&&
user
.
getGraduationTime
()
==
null
)
{
user
.
setGraduationTime
(
new
Date
());
}
if
(
AccountAdminConstants
.
STATUS_ARCHIVED
.
equals
(
target
)
&&
user
.
getArchiveTime
()
==
null
)
{
user
.
setArchiveTime
(
new
Date
());
}
}
user
.
setAccountStatus
(
target
);
user
.
setDelFlag
(
isLoginDisabled
(
target
));
user
.
setUpdateTime
(
new
Date
());
if
(!
userService
.
updateById
(
user
))
{
throw
new
BusinessException
(
"账户状态更新失败,请刷新后重试"
);
}
writeAudit
(
operator
,
id
,
"CHANGE_STATUS"
,
current
+
" -> "
+
target
);
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
void
resetPassword
(
String
id
,
UserEntity
operator
)
{
requireId
(
id
);
UserEntity
user
=
requireUser
(
id
);
user
.
setPassword
(
passwordUtil
.
encodePassword
(
AccountAdminConstants
.
DEFAULT_PASSWORD
));
user
.
setLoginFailNum
(
0
);
user
.
setFirstLoginFlag
(
true
);
user
.
setUpdateTime
(
new
Date
());
if
(!
userService
.
updateById
(
user
))
{
throw
new
BusinessException
(
"密码重置失败,请刷新后重试"
);
}
writeAudit
(
operator
,
id
,
"RESET_PASSWORD"
,
"密码已重置为系统初始密码"
);
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
int
batch
(
AccountBatchActionDTO
request
,
UserEntity
operator
)
{
if
(
request
==
null
||
request
.
getIds
()
==
null
||
request
.
getIds
().
isEmpty
())
{
throw
new
BusinessException
(
"请至少选择一个账户"
);
}
if
(
request
.
getIds
().
size
()
>
AccountAdminConstants
.
MAX_BATCH_SIZE
)
{
throw
new
BusinessException
(
"单次批量操作不能超过500个账户"
);
}
String
action
=
upper
(
request
.
getAction
());
if
(!
AccountAdminConstants
.
BATCH_ACTIONS
.
contains
(
action
))
{
throw
new
BusinessException
(
"批量操作类型无效"
);
}
// 去重后执行,避免前端重复ID导致同一状态迁移两次或统计数量错误。
Set
<
String
>
uniqueIds
=
new
HashSet
<>(
request
.
getIds
());
int
changed
=
0
;
for
(
String
id
:
uniqueIds
)
{
if
(
AccountAdminConstants
.
ACTION_RESET_PASSWORD
.
equals
(
action
))
{
resetPassword
(
id
,
operator
);
}
else
if
(
AccountAdminConstants
.
ACTION_GRADUATE
.
equals
(
action
))
{
changeStatus
(
id
,
AccountAdminConstants
.
STATUS_GRADUATED
,
operator
);
}
else
if
(
AccountAdminConstants
.
ACTION_ARCHIVE
.
equals
(
action
))
{
changeStatus
(
id
,
AccountAdminConstants
.
STATUS_ARCHIVED
,
operator
);
}
else
if
(
AccountAdminConstants
.
ACTION_ENABLE
.
equals
(
action
))
{
changeStatus
(
id
,
AccountAdminConstants
.
STATUS_ENABLED
,
operator
);
}
else
{
changeStatus
(
id
,
AccountAdminConstants
.
STATUS_DISABLED
,
operator
);
}
changed
++;
}
return
changed
;
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
AccountImportResultVO
importAccounts
(
String
accountType
,
Integer
classId
,
boolean
preview
,
MultipartFile
file
,
UserEntity
operator
)
{
String
type
=
normalizeType
(
accountType
);
validateImportFile
(
file
);
if
(
AccountAdminConstants
.
TYPE_STUDENT
.
equals
(
type
))
{
requireClass
(
classId
);
}
List
<
AccountImportRowDTO
>
rows
=
parseImportRows
(
type
,
file
);
validateImportRows
(
rows
,
type
);
int
validCount
=
(
int
)
rows
.
stream
().
filter
(
row
->
Boolean
.
TRUE
.
equals
(
row
.
getValid
())).
count
();
int
imported
=
0
;
if
(!
preview
)
{
for
(
AccountImportRowDTO
row
:
rows
)
{
if
(!
Boolean
.
TRUE
.
equals
(
row
.
getValid
()))
{
continue
;
}
AccountAdminSaveDTO
request
=
new
AccountAdminSaveDTO
();
request
.
setAccountType
(
type
);
request
.
setName
(
row
.
getName
());
request
.
setPhoneNumber
(
row
.
getPhoneNumber
());
request
.
setUsername
(
row
.
getUsername
());
request
.
setEmployeeNo
(
row
.
getEmployeeNo
());
request
.
setRoleId
(
row
.
getRoleId
());
request
.
setClassId
(
classId
);
request
.
setRemark
(
row
.
getRemark
());
create
(
request
,
operator
);
imported
++;
}
}
AccountImportResultVO
result
=
new
AccountImportResultVO
();
result
.
setTotalCount
(
rows
.
size
());
result
.
setValidCount
(
validCount
);
result
.
setInvalidCount
(
rows
.
size
()
-
validCount
);
result
.
setImportedCount
(
imported
);
result
.
setPreview
(
preview
);
result
.
setRows
(
rows
);
return
result
;
}
@Override
public
void
downloadTemplate
(
String
accountType
,
HttpServletResponse
response
)
{
String
type
=
normalizeType
(
accountType
);
try
(
Workbook
workbook
=
new
XSSFWorkbook
())
{
Sheet
sheet
=
workbook
.
createSheet
(
"账户导入"
);
List
<
String
>
headers
=
importHeaders
(
type
);
writeRow
(
sheet
.
createRow
(
0
),
headers
);
Row
example
=
sheet
.
createRow
(
1
);
if
(
AccountAdminConstants
.
TYPE_STUDENT
.
equals
(
type
))
{
writeRow
(
example
,
asList
(
"张三"
,
"13800138000"
,
"可选备注"
));
}
else
if
(
AccountAdminConstants
.
TYPE_TEACHER
.
equals
(
type
))
{
writeRow
(
example
,
asList
(
"王老师"
,
"T-2026-001"
,
"13800138000"
,
"理论讲师"
,
"可选备注"
));
}
else
{
writeRow
(
example
,
asList
(
"管理员"
,
"admin01"
,
"13800138000"
,
"机构管理员"
,
"可选备注"
));
}
autoSize
(
sheet
,
headers
.
size
());
writeWorkbook
(
response
,
workbook
,
typeLabel
(
type
)
+
"账户批量导入模板.xlsx"
);
}
catch
(
IOException
e
)
{
throw
new
BusinessException
(
"账户导入模板生成失败"
);
}
}
@Override
@Transactional
(
readOnly
=
true
)
public
void
export
(
AccountAdminQueryDTO
query
,
HttpServletResponse
response
)
{
AccountAdminQueryDTO
normalized
=
normalizeQuery
(
query
);
List
<
AccountAdminListVO
>
rows
=
accountAdminMapper
.
selectAccounts
(
normalized
,
AccountAdminConstants
.
broadRoleName
(
normalized
.
getAccountType
()),
sixMonthsAgo
());
try
(
Workbook
workbook
=
new
XSSFWorkbook
())
{
Sheet
sheet
=
workbook
.
createSheet
(
"账户清单"
);
List
<
String
>
headers
=
asList
(
"姓名"
,
"登录账号"
,
"工号"
,
"手机号"
,
"班级"
,
"职业等级"
,
"角色"
,
"状态"
,
"最后登录时间"
);
writeRow
(
sheet
.
createRow
(
0
),
headers
);
int
rowIndex
=
1
;
if
(
rows
!=
null
)
{
for
(
AccountAdminListVO
item
:
rows
)
{
writeRow
(
sheet
.
createRow
(
rowIndex
++),
asList
(
item
.
getName
(),
item
.
getUsername
(),
item
.
getEmployeeNo
(),
item
.
getPhoneNumber
(),
item
.
getClassName
(),
item
.
getLevelName
(),
item
.
getRoleName
(),
item
.
getStatus
(),
item
.
getLastLoginTime
()
==
null
?
""
:
item
.
getLastLoginTime
().
toString
()));
}
}
autoSize
(
sheet
,
headers
.
size
());
writeWorkbook
(
response
,
workbook
,
typeLabel
(
normalized
.
getAccountType
())
+
"账户清单.xlsx"
);
}
catch
(
IOException
e
)
{
throw
new
BusinessException
(
"账户清单导出失败"
);
}
}
/** 统一清理和校验查询参数,分页参数由控制器另外处理。 */
AccountAdminQueryDTO
normalizeQuery
(
AccountAdminQueryDTO
query
)
{
if
(
query
==
null
)
{
throw
new
BusinessException
(
"查询条件不能为空"
);
}
query
.
setAccountType
(
normalizeType
(
query
.
getAccountType
()));
query
.
setKeyword
(
optionalText
(
query
.
getKeyword
(),
"关键字"
,
100
));
query
.
setStatus
(
query
.
getStatus
()
==
null
?
null
:
normalizeStatus
(
query
.
getAccountType
(),
query
.
getStatus
()));
if
(
query
.
getStartDate
()
!=
null
&&
query
.
getEndDate
()
!=
null
&&
query
.
getStartDate
().
after
(
query
.
getEndDate
()))
{
throw
new
BusinessException
(
"结束日期不能早于开始日期"
);
}
if
(!
AccountAdminConstants
.
TYPE_STUDENT
.
equals
(
query
.
getAccountType
()))
{
query
.
setClassId
(
null
);
query
.
setArchiveOverSixMonths
(
false
);
}
else
{
query
.
setRoleId
(
null
);
}
return
query
;
}
private
void
validateAndNormalizeSave
(
AccountAdminSaveDTO
request
,
String
excludeId
,
boolean
creating
)
{
if
(
request
==
null
)
{
throw
new
BusinessException
(
"账户信息不能为空"
);
}
String
type
=
normalizeType
(
request
.
getAccountType
());
request
.
setAccountType
(
type
);
request
.
setName
(
requireText
(
request
.
getName
(),
"姓名"
,
50
));
request
.
setPhoneNumber
(
requireText
(
request
.
getPhoneNumber
(),
"手机号"
,
20
));
if
(!
PHONE_PATTERN
.
matcher
(
request
.
getPhoneNumber
()).
matches
())
{
throw
new
BusinessException
(
"手机号格式不正确"
);
}
if
(
accountAdminMapper
.
countPhone
(
request
.
getPhoneNumber
(),
excludeId
)
>
0
)
{
throw
new
BusinessException
(
"手机号已被其他账户使用"
);
}
request
.
setIdCard
(
optionalText
(
request
.
getIdCard
(),
"身份证号"
,
30
));
request
.
setCompanyName
(
optionalText
(
request
.
getCompanyName
(),
"单位名称"
,
200
));
request
.
setRemark
(
optionalText
(
request
.
getRemark
(),
"备注"
,
500
));
request
.
setStatus
(
request
.
getStatus
()
==
null
?
null
:
normalizeStatus
(
type
,
request
.
getStatus
()));
if
(
AccountAdminConstants
.
TYPE_STUDENT
.
equals
(
type
))
{
requireClass
(
request
.
getClassId
());
request
.
setUsername
(
request
.
getPhoneNumber
());
request
.
setEmployeeNo
(
null
);
request
.
setRoleId
(
null
);
}
else
{
if
(
request
.
getRoleId
()
==
null
)
{
throw
new
BusinessException
(
"角色不能为空"
);
}
validateRole
(
request
.
getRoleId
(),
type
);
if
(
AccountAdminConstants
.
TYPE_TEACHER
.
equals
(
type
))
{
String
employeeNo
=
requireText
(
request
.
getEmployeeNo
(),
"教师工号"
,
50
);
if
(!
ACCOUNT_PATTERN
.
matcher
(
employeeNo
).
matches
())
{
throw
new
BusinessException
(
"教师工号只能包含字母、数字、点、横线或下划线"
);
}
if
(
accountAdminMapper
.
countEmployeeNo
(
employeeNo
,
excludeId
)
>
0
)
{
throw
new
BusinessException
(
"教师工号已存在"
);
}
request
.
setEmployeeNo
(
employeeNo
);
request
.
setUsername
(
employeeNo
);
}
else
{
String
username
=
requireText
(
request
.
getUsername
(),
"登录账号"
,
50
);
if
(!
ACCOUNT_PATTERN
.
matcher
(
username
).
matches
())
{
throw
new
BusinessException
(
"登录账号只能包含字母、数字、点、横线或下划线"
);
}
request
.
setUsername
(
username
);
request
.
setEmployeeNo
(
null
);
}
if
(
accountAdminMapper
.
countUsername
(
request
.
getUsername
(),
excludeId
)
>
0
)
{
throw
new
BusinessException
(
"登录账号已存在"
);
}
}
if
(
creating
)
{
String
password
=
defaultPassword
(
request
.
getInitialPassword
());
if
(
password
.
length
()
<
8
||
password
.
length
()
>
32
)
{
throw
new
BusinessException
(
"初始密码长度必须为8到32位"
);
}
request
.
setInitialPassword
(
password
);
}
}
private
void
applyEditableFields
(
UserEntity
user
,
AccountAdminSaveDTO
request
,
String
type
)
{
user
.
setNickName
(
request
.
getName
());
user
.
setPhoneNumber
(
request
.
getPhoneNumber
());
user
.
setUsername
(
request
.
getUsername
());
user
.
setEmployeeNo
(
request
.
getEmployeeNo
());
user
.
setIdCard
(
request
.
getIdCard
());
user
.
setCompanyName2
(
request
.
getCompanyName
());
user
.
setRemark
(
request
.
getRemark
());
if
(
AccountAdminConstants
.
TYPE_STUDENT
.
equals
(
type
))
{
ClassEntity
clazz
=
requireClass
(
request
.
getClassId
());
user
.
setLevel
(
clazz
.
getLevel
());
}
}
private
void
saveRelations
(
String
userId
,
AccountAdminSaveDTO
request
,
String
type
)
{
if
(
AccountAdminConstants
.
TYPE_STUDENT
.
equals
(
type
))
{
classStudentService
.
remove
(
new
LambdaQueryWrapper
<
ClassStudentEntity
>()
.
eq
(
ClassStudentEntity:
:
getUserId
,
userId
));
ClassStudentEntity
relation
=
new
ClassStudentEntity
();
relation
.
setUserId
(
userId
);
relation
.
setClassId
(
request
.
getClassId
());
if
(!
classStudentService
.
save
(
relation
))
{
throw
new
BusinessException
(
"学员班级绑定失败"
);
}
userRoleService
.
remove
(
new
LambdaQueryWrapper
<
SysUserAndRoleEntity
>()
.
eq
(
SysUserAndRoleEntity:
:
getUserId
,
userId
));
return
;
}
userRoleService
.
remove
(
new
LambdaQueryWrapper
<
SysUserAndRoleEntity
>()
.
eq
(
SysUserAndRoleEntity:
:
getUserId
,
userId
));
SysUserAndRoleEntity
relation
=
new
SysUserAndRoleEntity
();
relation
.
setUserId
(
userId
);
relation
.
setRoleId
(
request
.
getRoleId
());
if
(!
userRoleService
.
save
(
relation
))
{
throw
new
BusinessException
(
"账户角色绑定失败"
);
}
classStudentService
.
remove
(
new
LambdaQueryWrapper
<
ClassStudentEntity
>()
.
eq
(
ClassStudentEntity:
:
getUserId
,
userId
));
}
private
void
saveBroadRole
(
String
phone
,
String
type
)
{
String
broadRole
=
AccountAdminConstants
.
broadRoleName
(
type
);
long
count
=
phoneRoleService
.
count
(
new
LambdaQueryWrapper
<
SysPhoneRoleEntity
>()
.
eq
(
SysPhoneRoleEntity:
:
getPhone
,
phone
)
.
eq
(
SysPhoneRoleEntity:
:
getRoleName
,
broadRole
));
if
(
count
==
0
)
{
SysPhoneRoleEntity
relation
=
new
SysPhoneRoleEntity
();
relation
.
setPhone
(
phone
);
relation
.
setRoleName
(
broadRole
);
if
(!
phoneRoleService
.
save
(
relation
))
{
throw
new
BusinessException
(
"账户类型绑定失败"
);
}
}
}
private
List
<
AccountImportRowDTO
>
parseImportRows
(
String
type
,
MultipartFile
file
)
{
try
(
Workbook
workbook
=
WorkbookFactory
.
create
(
file
.
getInputStream
()))
{
Sheet
sheet
=
workbook
.
getSheetAt
(
0
);
if
(
sheet
==
null
||
sheet
.
getLastRowNum
()
<
1
)
{
throw
new
BusinessException
(
"Excel中没有可导入的数据"
);
}
validateHeaders
(
sheet
.
getRow
(
0
),
importHeaders
(
type
));
DataFormatter
formatter
=
new
DataFormatter
(
Locale
.
CHINA
);
List
<
AccountImportRowDTO
>
rows
=
new
ArrayList
<>();
for
(
int
i
=
1
;
i
<=
sheet
.
getLastRowNum
();
i
++)
{
Row
excelRow
=
sheet
.
getRow
(
i
);
if
(
excelRow
==
null
||
isBlankRow
(
excelRow
,
formatter
))
{
continue
;
}
AccountImportRowDTO
row
=
new
AccountImportRowDTO
();
row
.
setRowNumber
(
i
+
1
);
row
.
setName
(
cell
(
excelRow
,
0
,
formatter
));
if
(
AccountAdminConstants
.
TYPE_STUDENT
.
equals
(
type
))
{
row
.
setPhoneNumber
(
cell
(
excelRow
,
1
,
formatter
));
row
.
setUsername
(
row
.
getPhoneNumber
());
row
.
setRemark
(
cell
(
excelRow
,
2
,
formatter
));
}
else
if
(
AccountAdminConstants
.
TYPE_TEACHER
.
equals
(
type
))
{
row
.
setEmployeeNo
(
cell
(
excelRow
,
1
,
formatter
));
row
.
setUsername
(
row
.
getEmployeeNo
());
row
.
setPhoneNumber
(
cell
(
excelRow
,
2
,
formatter
));
row
.
setRoleName
(
cell
(
excelRow
,
3
,
formatter
));
row
.
setRemark
(
cell
(
excelRow
,
4
,
formatter
));
}
else
{
row
.
setUsername
(
cell
(
excelRow
,
1
,
formatter
));
row
.
setPhoneNumber
(
cell
(
excelRow
,
2
,
formatter
));
row
.
setRoleName
(
cell
(
excelRow
,
3
,
formatter
));
row
.
setRemark
(
cell
(
excelRow
,
4
,
formatter
));
}
rows
.
add
(
row
);
if
(
rows
.
size
()
>
AccountAdminConstants
.
MAX_BATCH_SIZE
)
{
throw
new
BusinessException
(
"单次导入不能超过500条账户"
);
}
}
if
(
rows
.
isEmpty
())
{
throw
new
BusinessException
(
"Excel中没有可导入的数据"
);
}
return
rows
;
}
catch
(
BusinessException
e
)
{
throw
e
;
}
catch
(
Exception
e
)
{
throw
new
BusinessException
(
"Excel文件无法解析,请使用下载的模板重新填写"
);
}
}
private
void
validateImportRows
(
List
<
AccountImportRowDTO
>
rows
,
String
type
)
{
Set
<
String
>
phones
=
new
HashSet
<>();
Set
<
String
>
accounts
=
new
HashSet
<>();
for
(
AccountImportRowDTO
row
:
rows
)
{
List
<
String
>
errors
=
new
ArrayList
<>();
row
.
setName
(
trimToNull
(
row
.
getName
()));
row
.
setPhoneNumber
(
trimToNull
(
row
.
getPhoneNumber
()));
row
.
setUsername
(
trimToNull
(
row
.
getUsername
()));
row
.
setEmployeeNo
(
trimToNull
(
row
.
getEmployeeNo
()));
row
.
setRoleName
(
trimToNull
(
row
.
getRoleName
()));
row
.
setRemark
(
trimToNull
(
row
.
getRemark
()));
if
(
row
.
getName
()
==
null
)
errors
.
add
(
"姓名为空"
);
else
if
(
row
.
getName
().
length
()
>
50
)
errors
.
add
(
"姓名超过50个字符"
);
if
(
row
.
getPhoneNumber
()
==
null
||
!
PHONE_PATTERN
.
matcher
(
row
.
getPhoneNumber
()).
matches
())
{
errors
.
add
(
"手机号格式错误"
);
}
else
{
if
(!
phones
.
add
(
row
.
getPhoneNumber
()))
errors
.
add
(
"文件内手机号重复"
);
if
(
accountAdminMapper
.
countPhone
(
row
.
getPhoneNumber
(),
null
)
>
0
)
errors
.
add
(
"手机号已存在"
);
}
if
(!
AccountAdminConstants
.
TYPE_STUDENT
.
equals
(
type
))
{
String
account
=
AccountAdminConstants
.
TYPE_TEACHER
.
equals
(
type
)
?
row
.
getEmployeeNo
()
:
row
.
getUsername
();
if
(
account
==
null
||
!
ACCOUNT_PATTERN
.
matcher
(
account
).
matches
())
{
errors
.
add
(
AccountAdminConstants
.
TYPE_TEACHER
.
equals
(
type
)
?
"工号格式错误"
:
"登录账号格式错误"
);
}
else
{
if
(!
accounts
.
add
(
account
))
errors
.
add
(
"文件内账号重复"
);
if
(
accountAdminMapper
.
countUsername
(
account
,
null
)
>
0
)
errors
.
add
(
"登录账号已存在"
);
if
(
AccountAdminConstants
.
TYPE_TEACHER
.
equals
(
type
)
&&
accountAdminMapper
.
countEmployeeNo
(
account
,
null
)
>
0
)
errors
.
add
(
"教师工号已存在"
);
}
if
(
row
.
getRoleName
()
==
null
)
{
errors
.
add
(
"角色为空"
);
}
else
{
Integer
roleId
=
accountAdminMapper
.
selectRoleIdByName
(
row
.
getRoleName
(),
type
);
if
(
roleId
==
null
)
errors
.
add
(
"角色不存在或不适用于该账户类型"
);
row
.
setRoleId
(
roleId
);
}
}
row
.
setValid
(
errors
.
isEmpty
());
row
.
setErrorMessage
(
errors
.
isEmpty
()
?
null
:
String
.
join
(
";"
,
errors
));
}
}
private
void
validateImportFile
(
MultipartFile
file
)
{
if
(
file
==
null
||
file
.
isEmpty
())
throw
new
BusinessException
(
"请选择Excel文件"
);
if
(
file
.
getSize
()
>
AccountAdminConstants
.
MAX_IMPORT_BYTES
)
{
throw
new
BusinessException
(
"Excel文件大小不能超过5MB"
);
}
String
name
=
file
.
getOriginalFilename
();
String
lower
=
name
==
null
?
""
:
name
.
toLowerCase
(
Locale
.
ROOT
);
if
(!
lower
.
endsWith
(
".xlsx"
)
&&
!
lower
.
endsWith
(
".xls"
))
{
throw
new
BusinessException
(
"仅支持.xlsx或.xls格式文件"
);
}
}
private
void
validateHeaders
(
Row
row
,
List
<
String
>
expected
)
{
if
(
row
==
null
)
throw
new
BusinessException
(
"Excel缺少表头"
);
DataFormatter
formatter
=
new
DataFormatter
(
Locale
.
CHINA
);
for
(
int
i
=
0
;
i
<
expected
.
size
();
i
++)
{
String
actual
=
cell
(
row
,
i
,
formatter
);
if
(!
expected
.
get
(
i
).
equals
(
actual
))
{
throw
new
BusinessException
(
"Excel表头不正确,第"
+
(
i
+
1
)
+
"列应为“"
+
expected
.
get
(
i
)
+
"”"
);
}
}
}
private
List
<
String
>
importHeaders
(
String
type
)
{
if
(
AccountAdminConstants
.
TYPE_STUDENT
.
equals
(
type
))
{
return
asList
(
"姓名"
,
"手机号"
,
"备注"
);
}
if
(
AccountAdminConstants
.
TYPE_TEACHER
.
equals
(
type
))
{
return
asList
(
"姓名"
,
"工号"
,
"手机号"
,
"角色"
,
"备注"
);
}
return
asList
(
"姓名"
,
"登录账号"
,
"手机号"
,
"角色"
,
"备注"
);
}
private
void
validateRole
(
Integer
roleId
,
String
type
)
{
SysRoleEntity
role
=
roleService
.
getById
(
roleId
);
if
(
role
==
null
||
!
type
.
equals
(
upper
(
role
.
getAccountType
())))
{
throw
new
BusinessException
(
"所选角色不存在或不适用于该账户类型"
);
}
}
private
ClassEntity
requireClass
(
Integer
classId
)
{
if
(
classId
==
null
)
throw
new
BusinessException
(
"所属班级不能为空"
);
ClassEntity
clazz
=
classMapper
.
selectById
(
classId
);
if
(
clazz
==
null
)
throw
new
BusinessException
(
"所属班级不存在"
);
return
clazz
;
}
private
UserEntity
requireUser
(
String
id
)
{
UserEntity
user
=
userService
.
getById
(
id
);
if
(
user
==
null
)
throw
new
BusinessException
(
"账户不存在或已删除"
);
return
user
;
}
private
String
requireAccountType
(
String
id
)
{
String
type
=
accountAdminMapper
.
selectAccountType
(
id
);
if
(
type
==
null
)
throw
new
BusinessException
(
"账户未配置有效的账户类型"
);
return
type
;
}
private
String
normalizeType
(
String
value
)
{
String
type
=
upper
(
value
);
if
(!
AccountAdminConstants
.
ACCOUNT_TYPES
.
contains
(
type
))
{
throw
new
BusinessException
(
"账户类型只支持STUDENT、TEACHER或ADMIN"
);
}
return
type
;
}
private
String
normalizeStatus
(
String
type
,
String
value
)
{
String
status
=
upper
(
value
);
Set
<
String
>
allowed
=
AccountAdminConstants
.
TYPE_STUDENT
.
equals
(
type
)
?
AccountAdminConstants
.
STUDENT_STATUSES
:
AccountAdminConstants
.
STAFF_STATUSES
;
if
(!
allowed
.
contains
(
status
))
throw
new
BusinessException
(
"账户状态参数无效"
);
return
status
;
}
private
String
defaultStatus
(
String
type
,
String
value
)
{
if
(
value
!=
null
)
return
normalizeStatus
(
type
,
value
);
return
AccountAdminConstants
.
TYPE_STUDENT
.
equals
(
type
)
?
AccountAdminConstants
.
STATUS_PENDING
:
AccountAdminConstants
.
STATUS_ENABLED
;
}
private
void
validateStudentTransition
(
String
current
,
String
target
)
{
if
(
target
.
equals
(
current
))
return
;
boolean
valid
=
(
AccountAdminConstants
.
STATUS_PENDING
.
equals
(
current
)
||
AccountAdminConstants
.
STATUS_STUDYING
.
equals
(
current
))
&&
(
AccountAdminConstants
.
STATUS_STUDYING
.
equals
(
target
)
||
AccountAdminConstants
.
STATUS_GRADUATED
.
equals
(
target
)
||
AccountAdminConstants
.
STATUS_ARCHIVED
.
equals
(
target
));
valid
=
valid
||
(
AccountAdminConstants
.
STATUS_GRADUATED
.
equals
(
current
)
&&
AccountAdminConstants
.
STATUS_ARCHIVED
.
equals
(
target
));
if
(!
valid
)
{
throw
new
BusinessException
(
"学员状态只能按待激活→在读→已结业→已归档方向变更"
);
}
}
private
String
effectiveStatus
(
UserEntity
user
,
String
type
)
{
String
stored
=
trimToNull
(
user
.
getAccountStatus
());
if
(
stored
!=
null
)
return
upper
(
stored
);
if
(
AccountAdminConstants
.
TYPE_STUDENT
.
equals
(
type
))
{
if
(
Boolean
.
TRUE
.
equals
(
user
.
getDelFlag
()))
return
AccountAdminConstants
.
STATUS_ARCHIVED
;
if
(
Boolean
.
TRUE
.
equals
(
user
.
getFirstLoginFlag
()))
return
AccountAdminConstants
.
STATUS_PENDING
;
return
AccountAdminConstants
.
STATUS_STUDYING
;
}
return
Boolean
.
TRUE
.
equals
(
user
.
getDelFlag
())
?
AccountAdminConstants
.
STATUS_DISABLED
:
AccountAdminConstants
.
STATUS_ENABLED
;
}
private
boolean
isLoginDisabled
(
String
status
)
{
return
AccountAdminConstants
.
STATUS_ARCHIVED
.
equals
(
status
)
||
AccountAdminConstants
.
STATUS_DISABLED
.
equals
(
status
);
}
private
void
writeAudit
(
UserEntity
operator
,
String
targetId
,
String
action
,
String
detail
)
{
accountAdminMapper
.
insertOperationLog
(
operator
==
null
?
null
:
operator
.
getId
(),
operator
==
null
?
null
:
operator
.
getNickName
(),
targetId
,
action
,
detail
,
new
Date
());
}
private
Date
sixMonthsAgo
()
{
LocalDate
date
=
LocalDate
.
now
(
BUSINESS_ZONE
).
minusMonths
(
6
);
return
Date
.
from
(
date
.
atStartOfDay
(
BUSINESS_ZONE
).
toInstant
());
}
private
String
idType
(
String
type
)
{
if
(
AccountAdminConstants
.
TYPE_STUDENT
.
equals
(
type
))
return
"学生"
;
if
(
AccountAdminConstants
.
TYPE_TEACHER
.
equals
(
type
))
return
"教师"
;
return
"管理员"
;
}
private
String
typeLabel
(
String
type
)
{
if
(
AccountAdminConstants
.
TYPE_STUDENT
.
equals
(
type
))
return
"学员"
;
if
(
AccountAdminConstants
.
TYPE_TEACHER
.
equals
(
type
))
return
"教师"
;
return
"管理员"
;
}
private
String
defaultPassword
(
String
password
)
{
String
normalized
=
trimToNull
(
password
);
return
normalized
==
null
?
AccountAdminConstants
.
DEFAULT_PASSWORD
:
normalized
;
}
private
String
requireText
(
String
value
,
String
field
,
int
maxLength
)
{
String
normalized
=
trimToNull
(
value
);
if
(
normalized
==
null
)
throw
new
BusinessException
(
field
+
"不能为空"
);
if
(
normalized
.
length
()
>
maxLength
)
throw
new
BusinessException
(
field
+
"不能超过"
+
maxLength
+
"个字符"
);
return
normalized
;
}
private
String
optionalText
(
String
value
,
String
field
,
int
maxLength
)
{
String
normalized
=
trimToNull
(
value
);
if
(
normalized
!=
null
&&
normalized
.
length
()
>
maxLength
)
{
throw
new
BusinessException
(
field
+
"不能超过"
+
maxLength
+
"个字符"
);
}
return
normalized
;
}
private
String
trimToNull
(
String
value
)
{
if
(
value
==
null
)
return
null
;
String
trimmed
=
value
.
trim
();
return
trimmed
.
isEmpty
()
?
null
:
trimmed
;
}
private
String
upper
(
String
value
)
{
String
normalized
=
trimToNull
(
value
);
return
normalized
==
null
?
null
:
normalized
.
toUpperCase
(
Locale
.
ROOT
);
}
private
void
requireId
(
String
id
)
{
if
(
trimToNull
(
id
)
==
null
)
throw
new
BusinessException
(
"账户ID不能为空"
);
}
private
String
cell
(
Row
row
,
int
index
,
DataFormatter
formatter
)
{
Cell
cell
=
row
.
getCell
(
index
);
return
cell
==
null
?
""
:
formatter
.
formatCellValue
(
cell
).
trim
();
}
private
boolean
isBlankRow
(
Row
row
,
DataFormatter
formatter
)
{
for
(
int
i
=
0
;
i
<
row
.
getLastCellNum
();
i
++)
{
if
(!
cell
(
row
,
i
,
formatter
).
isEmpty
())
return
false
;
}
return
true
;
}
private
List
<
String
>
asList
(
String
...
values
)
{
List
<
String
>
result
=
new
ArrayList
<>();
Collections
.
addAll
(
result
,
values
);
return
result
;
}
private
void
writeRow
(
Row
row
,
List
<
String
>
values
)
{
for
(
int
i
=
0
;
i
<
values
.
size
();
i
++)
{
row
.
createCell
(
i
).
setCellValue
(
values
.
get
(
i
)
==
null
?
""
:
values
.
get
(
i
));
}
}
private
void
autoSize
(
Sheet
sheet
,
int
columnCount
)
{
for
(
int
i
=
0
;
i
<
columnCount
;
i
++)
{
sheet
.
autoSizeColumn
(
i
);
sheet
.
setColumnWidth
(
i
,
Math
.
min
(
sheet
.
getColumnWidth
(
i
)
+
512
,
50
*
256
));
}
}
private
void
writeWorkbook
(
HttpServletResponse
response
,
Workbook
workbook
,
String
filename
)
throws
IOException
{
String
encoded
=
URLEncoder
.
encode
(
filename
,
"UTF-8"
).
replace
(
"+"
,
"%20"
);
response
.
setCharacterEncoding
(
"UTF-8"
);
response
.
setContentType
(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
);
response
.
setHeader
(
"Content-Disposition"
,
"attachment; filename*=UTF-8''"
+
encoded
);
try
(
OutputStream
output
=
response
.
getOutputStream
())
{
workbook
.
write
(
output
);
output
.
flush
();
}
}
}
practical-business/src/main/resources/account-management-api.md
0 → 100644
View file @
dd2bf60f
# 管理员端账户管理接口
接口前缀:
`/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`
。脚本新增账户状态、工号、结业/归档时间、
角色适用端字段,以及登录日志和账户操作审计表;脚本可重复执行,并在末尾输出需要人工处理的
未分类角色和历史重复账号。
practical-business/src/main/resources/com/platform/business/mapper/AccountAdminMapper.xml
0 → 100644
View file @
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.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
>
= #{query.startDate}
</if>
<if
test=
"query.endDate != null"
>
and c.end_date
<
= #{query.endDate}
</if>
</when>
<otherwise>
<if
test=
"query.startDate != null"
>
and u.login_date
>
= #{query.startDate}
</if>
<!-- 结束日期加一天后使用小于比较,确保包含结束日全天。 -->
<if
test=
"query.endDate != null"
>
and u.login_date
<
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)
<
= #{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>
practical-business/src/main/resources/sql/account_management.sql
0 → 100644
View file @
dd2bf60f
-- 管理员端“系统管理-账户管理”增量数据库脚本(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
;
practical-business/src/test/java/com/platform/business/controller/AccountAdminControllerTest.java
0 → 100644
View file @
dd2bf60f
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
));
}
}
practical-business/src/test/java/com/platform/business/mapper/AccountAdminMapperXmlTest.java
0 → 100644
View file @
dd2bf60f
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"
));
}
}
}
practical-business/src/test/java/com/platform/business/service/impl/AccountAdminServiceImplTest.java
0 → 100644
View file @
dd2bf60f
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
));
}
}
Prev
1
2
Next
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment