1、sql输出调整,否则会占满资源;
2、添加组织角色管理模块; 3、后台管理样式调整,改为左侧边栏
This commit is contained in:
@@ -1,6 +1,9 @@
|
||||
package com.banben.config;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.banben.modules.admin.entity.SysRole;
|
||||
import com.banben.modules.admin.mapper.SysRoleMapper;
|
||||
import com.banben.modules.admin.service.RoleService;
|
||||
import com.banben.modules.auth.entity.SysUser;
|
||||
import com.banben.modules.auth.mapper.SysUserMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -21,28 +24,56 @@ import org.springframework.stereotype.Component;
|
||||
public class DataInitializer implements ApplicationRunner {
|
||||
|
||||
private final SysUserMapper sysUserMapper;
|
||||
private final SysRoleMapper sysRoleMapper;
|
||||
private final RoleService roleService;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
@Override
|
||||
public void run(ApplicationArguments args) {
|
||||
ensureRoles();
|
||||
try {
|
||||
LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(SysUser::getUsername, "admin");
|
||||
Long count = sysUserMapper.selectCount(wrapper);
|
||||
if (count != null && count > 0) {
|
||||
return;
|
||||
if (count == null || count == 0) {
|
||||
SysUser admin = new SysUser();
|
||||
admin.setUsername("admin");
|
||||
admin.setPassword(passwordEncoder.encode("admin123"));
|
||||
admin.setRealName("系统管理员");
|
||||
admin.setRole("ADMIN");
|
||||
admin.setOrgName("版本资源联合服务中心");
|
||||
admin.setStatus(1);
|
||||
sysUserMapper.insert(admin);
|
||||
log.info("已创建默认管理员账号:admin / admin123");
|
||||
}
|
||||
SysUser admin = new SysUser();
|
||||
admin.setUsername("admin");
|
||||
admin.setPassword(passwordEncoder.encode("admin123"));
|
||||
admin.setRealName("系统管理员");
|
||||
admin.setRole("ADMIN");
|
||||
admin.setOrgName("版本资源联合服务中心");
|
||||
admin.setStatus(1);
|
||||
sysUserMapper.insert(admin);
|
||||
log.info("已创建默认管理员账号:admin / admin123");
|
||||
} catch (Exception e) {
|
||||
log.warn("初始化默认管理员失败(可能表未创建):{}", e.getMessage());
|
||||
}
|
||||
bindAdminRole();
|
||||
}
|
||||
|
||||
private void ensureRoles() {
|
||||
try {
|
||||
roleService.ensureBuiltin();
|
||||
} catch (Exception e) {
|
||||
log.warn("初始化内置角色失败(可能表未创建):{}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void bindAdminRole() {
|
||||
try {
|
||||
SysRole adminRole = sysRoleMapper.selectOne(new LambdaQueryWrapper<SysRole>().eq(SysRole::getCode, "ADMIN"));
|
||||
if (adminRole == null) {
|
||||
return;
|
||||
}
|
||||
SysUser admin = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, "admin"));
|
||||
if (admin != null && admin.getRoleId() == null) {
|
||||
admin.setRoleId(adminRole.getId());
|
||||
admin.setRole("ADMIN");
|
||||
sysUserMapper.updateById(admin);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("回填管理员角色失败:{}", e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.banben.modules.admin.controller;
|
||||
|
||||
import com.banben.common.Result;
|
||||
import com.banben.modules.admin.dto.OrgSaveRequest;
|
||||
import com.banben.modules.admin.dto.OrgTreeVO;
|
||||
import com.banben.modules.admin.service.OrgService;
|
||||
import com.banben.modules.admin.support.AdminAccess;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
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.RestController;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 多层级组织管理。
|
||||
*/
|
||||
@Tag(name = "后台管理-组织")
|
||||
@RestController
|
||||
@RequestMapping("/api/admin/orgs")
|
||||
@RequiredArgsConstructor
|
||||
public class OrgController {
|
||||
|
||||
private final OrgService orgService;
|
||||
private final AdminAccess adminAccess;
|
||||
|
||||
@Operation(summary = "组织树")
|
||||
@GetMapping("/tree")
|
||||
public Result<List<OrgTreeVO>> tree() {
|
||||
adminAccess.require();
|
||||
return Result.success(orgService.tree());
|
||||
}
|
||||
|
||||
@Operation(summary = "新增组织")
|
||||
@PostMapping
|
||||
public Result<Void> create(@Valid @RequestBody OrgSaveRequest request) {
|
||||
adminAccess.require();
|
||||
orgService.create(request);
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
@Operation(summary = "修改组织")
|
||||
@PutMapping("/{id}")
|
||||
public Result<Void> update(@PathVariable Long id, @Valid @RequestBody OrgSaveRequest request) {
|
||||
adminAccess.require();
|
||||
orgService.update(id, request);
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
@Operation(summary = "删除组织")
|
||||
@DeleteMapping("/{id}")
|
||||
public Result<Void> remove(@PathVariable Long id) {
|
||||
adminAccess.require();
|
||||
orgService.remove(id);
|
||||
return Result.success();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.banben.modules.admin.controller;
|
||||
|
||||
import com.banben.common.Result;
|
||||
import com.banben.modules.admin.dto.RoleSaveRequest;
|
||||
import com.banben.modules.admin.entity.SysRole;
|
||||
import com.banben.modules.admin.service.RoleService;
|
||||
import com.banben.modules.admin.support.AdminAccess;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
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.RestController;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 角色管理。
|
||||
*/
|
||||
@Tag(name = "后台管理-角色")
|
||||
@RestController
|
||||
@RequestMapping("/api/admin/roles")
|
||||
@RequiredArgsConstructor
|
||||
public class RoleController {
|
||||
|
||||
private final RoleService roleService;
|
||||
private final AdminAccess adminAccess;
|
||||
|
||||
@Operation(summary = "角色列表")
|
||||
@GetMapping
|
||||
public Result<List<SysRole>> list() {
|
||||
adminAccess.require();
|
||||
return Result.success(roleService.listAll());
|
||||
}
|
||||
|
||||
@Operation(summary = "新增角色")
|
||||
@PostMapping
|
||||
public Result<Void> create(@Valid @RequestBody RoleSaveRequest request) {
|
||||
adminAccess.require();
|
||||
roleService.create(request);
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
@Operation(summary = "修改角色")
|
||||
@PutMapping("/{id}")
|
||||
public Result<Void> update(@PathVariable Long id, @Valid @RequestBody RoleSaveRequest request) {
|
||||
adminAccess.require();
|
||||
roleService.update(id, request);
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
@Operation(summary = "删除角色")
|
||||
@DeleteMapping("/{id}")
|
||||
public Result<Void> remove(@PathVariable Long id) {
|
||||
adminAccess.require();
|
||||
roleService.remove(id);
|
||||
return Result.success();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.banben.modules.admin.controller;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.banben.common.Result;
|
||||
import com.banben.modules.admin.dto.UserSaveRequest;
|
||||
import com.banben.modules.admin.dto.UserVO;
|
||||
import com.banben.modules.admin.service.UserAdminService;
|
||||
import com.banben.modules.admin.service.UserExcelService;
|
||||
import com.banben.modules.admin.support.AdminAccess;
|
||||
import com.banben.modules.resource.dto.ImportResult;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
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 java.io.IOException;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* 用户管理,含导入模板导出和批量导入。
|
||||
*/
|
||||
@Tag(name = "后台管理-用户")
|
||||
@RestController
|
||||
@RequestMapping("/api/admin/users")
|
||||
@RequiredArgsConstructor
|
||||
public class UserAdminController {
|
||||
|
||||
private final UserAdminService userAdminService;
|
||||
private final UserExcelService userExcelService;
|
||||
private final AdminAccess adminAccess;
|
||||
|
||||
@Operation(summary = "分页查询用户")
|
||||
@GetMapping("/page")
|
||||
public Result<Page<UserVO>> page(@RequestParam(defaultValue = "1") long current,
|
||||
@RequestParam(defaultValue = "10") long size,
|
||||
@RequestParam(required = false) String keyword,
|
||||
@RequestParam(required = false) Long orgId,
|
||||
@RequestParam(required = false) Long roleId) {
|
||||
adminAccess.require();
|
||||
return Result.success(userAdminService.page(current, size, keyword, orgId, roleId));
|
||||
}
|
||||
|
||||
@Operation(summary = "新增用户")
|
||||
@PostMapping
|
||||
public Result<Void> create(@Valid @RequestBody UserSaveRequest request) {
|
||||
adminAccess.require();
|
||||
userAdminService.create(request);
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
@Operation(summary = "修改用户")
|
||||
@PutMapping("/{id}")
|
||||
public Result<Void> update(@PathVariable Long id, @Valid @RequestBody UserSaveRequest request) {
|
||||
adminAccess.require();
|
||||
userAdminService.update(id, request);
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
@Operation(summary = "删除用户")
|
||||
@DeleteMapping("/{id}")
|
||||
public Result<Void> remove(@PathVariable Long id) {
|
||||
adminAccess.require();
|
||||
userAdminService.remove(id);
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
@Operation(summary = "导出用户导入模板")
|
||||
@GetMapping("/import-template")
|
||||
public void template(jakarta.servlet.http.HttpServletResponse response) throws IOException {
|
||||
adminAccess.require();
|
||||
String fileName = URLEncoder.encode("用户导入模板.xlsx", StandardCharsets.UTF_8);
|
||||
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
response.setHeader("Content-Disposition",
|
||||
"attachment; filename=" + fileName + "; filename*=UTF-8''" + fileName);
|
||||
userExcelService.writeTemplate(response.getOutputStream());
|
||||
}
|
||||
|
||||
@Operation(summary = "批量导入用户")
|
||||
@PostMapping("/import")
|
||||
public Result<ImportResult> importExcel(@RequestParam("file") MultipartFile file) throws IOException {
|
||||
adminAccess.require();
|
||||
return Result.success(userExcelService.importExcel(file));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.banben.modules.admin.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 新增或修改组织。
|
||||
*/
|
||||
@Data
|
||||
public class OrgSaveRequest {
|
||||
|
||||
/** 上级组织,空表示顶级 */
|
||||
private Long parentId;
|
||||
|
||||
@NotBlank(message = "请填写组织名称")
|
||||
@Size(max = 128, message = "组织名称不能超过128字")
|
||||
private String name;
|
||||
|
||||
@Size(max = 64, message = "组织编码不能超过64字")
|
||||
private String code;
|
||||
|
||||
private Integer sortNo;
|
||||
|
||||
/** 1启用 0停用 */
|
||||
private Integer status;
|
||||
|
||||
@Size(max = 256, message = "备注不能超过256字")
|
||||
private String remark;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.banben.modules.admin.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 组织树节点。叶子节点不带 children。
|
||||
*/
|
||||
@Data
|
||||
public class OrgTreeVO {
|
||||
|
||||
private Long id;
|
||||
private Long parentId;
|
||||
private String name;
|
||||
private String code;
|
||||
private Integer sortNo;
|
||||
private Integer status;
|
||||
private String remark;
|
||||
private List<OrgTreeVO> children;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.banben.modules.admin.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 新增或修改角色。
|
||||
*/
|
||||
@Data
|
||||
public class RoleSaveRequest {
|
||||
|
||||
@NotBlank(message = "请填写角色编码")
|
||||
@Size(max = 32, message = "角色编码不能超过32字")
|
||||
@Pattern(regexp = "[A-Za-z][A-Za-z0-9_]{0,31}", message = "角色编码需以字母开头,只能包含字母、数字和下划线")
|
||||
private String code;
|
||||
|
||||
@NotBlank(message = "请填写角色名称")
|
||||
@Size(max = 64, message = "角色名称不能超过64字")
|
||||
private String name;
|
||||
|
||||
@Size(max = 256, message = "备注不能超过256字")
|
||||
private String remark;
|
||||
|
||||
/** 1启用 0停用 */
|
||||
private Integer status;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.banben.modules.admin.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 新增或修改用户。修改时密码留空表示不改密码。
|
||||
*/
|
||||
@Data
|
||||
public class UserSaveRequest {
|
||||
|
||||
@NotBlank(message = "请填写登录账号")
|
||||
@Size(max = 64, message = "登录账号不能超过64字")
|
||||
private String username;
|
||||
|
||||
@Size(max = 64, message = "密码不能超过64字")
|
||||
private String password;
|
||||
|
||||
@NotBlank(message = "请填写姓名")
|
||||
@Size(max = 128, message = "姓名不能超过128字")
|
||||
private String realName;
|
||||
|
||||
@NotNull(message = "请选择角色")
|
||||
private Long roleId;
|
||||
|
||||
private Long orgId;
|
||||
|
||||
/** 1启用 0停用 */
|
||||
private Integer status;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.banben.modules.admin.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 用户列表行,不包含密码。
|
||||
*/
|
||||
@Data
|
||||
public class UserVO {
|
||||
|
||||
private Long id;
|
||||
private String username;
|
||||
private String realName;
|
||||
private Long roleId;
|
||||
private String roleCode;
|
||||
private String roleName;
|
||||
private Long orgId;
|
||||
private String orgName;
|
||||
private Integer status;
|
||||
private LocalDateTime lastLoginTime;
|
||||
private LocalDateTime createTime;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.banben.modules.admin.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 多层级组织。
|
||||
*/
|
||||
@Data
|
||||
@TableName("sys_org")
|
||||
@Schema(description = "组织")
|
||||
public class SysOrg implements Serializable {
|
||||
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@Schema(description = "上级组织,空为顶级")
|
||||
private Long parentId;
|
||||
|
||||
@Schema(description = "组织名称")
|
||||
private String name;
|
||||
|
||||
@Schema(description = "组织编码")
|
||||
private String code;
|
||||
|
||||
@Schema(description = "同级排序,小的在前")
|
||||
private Integer sortNo;
|
||||
|
||||
@Schema(description = "1启用 0停用")
|
||||
private Integer status;
|
||||
|
||||
@Schema(description = "备注")
|
||||
private String remark;
|
||||
|
||||
@TableField(fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
|
||||
@TableLogic
|
||||
private Integer deleted;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.banben.modules.admin.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 角色。内置角色不可删除,编码供登录令牌使用。
|
||||
*/
|
||||
@Data
|
||||
@TableName("sys_role")
|
||||
@Schema(description = "角色")
|
||||
public class SysRole implements Serializable {
|
||||
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@Schema(description = "角色编码")
|
||||
private String code;
|
||||
|
||||
@Schema(description = "角色名称")
|
||||
private String name;
|
||||
|
||||
@Schema(description = "备注")
|
||||
private String remark;
|
||||
|
||||
@Schema(description = "1启用 0停用")
|
||||
private Integer status;
|
||||
|
||||
@Schema(description = "1内置 0自建")
|
||||
private Integer builtin;
|
||||
|
||||
@TableField(fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
|
||||
@TableLogic
|
||||
private Integer deleted;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.banben.modules.admin.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.banben.modules.admin.entity.SysOrg;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
/**
|
||||
* 组织 Mapper。
|
||||
*/
|
||||
@Mapper
|
||||
public interface SysOrgMapper extends BaseMapper<SysOrg> {
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.banben.modules.admin.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.banben.modules.admin.entity.SysRole;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
/**
|
||||
* 角色 Mapper。
|
||||
*/
|
||||
@Mapper
|
||||
public interface SysRoleMapper extends BaseMapper<SysRole> {
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.banben.modules.admin.service;
|
||||
|
||||
import com.banben.modules.admin.dto.OrgSaveRequest;
|
||||
import com.banben.modules.admin.dto.OrgTreeVO;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 多层级组织。
|
||||
*/
|
||||
public interface OrgService {
|
||||
|
||||
List<OrgTreeVO> tree();
|
||||
|
||||
void create(OrgSaveRequest request);
|
||||
|
||||
void update(Long id, OrgSaveRequest request);
|
||||
|
||||
void remove(Long id);
|
||||
|
||||
/** 本级及全部下级的 id,含自身。 */
|
||||
Set<Long> subtreeIds(Long orgId);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.banben.modules.admin.service;
|
||||
|
||||
import com.banben.modules.admin.dto.RoleSaveRequest;
|
||||
import com.banben.modules.admin.entity.SysRole;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 角色维护。内置角色不可删除,编码变更时同步用户表上的角色编码。
|
||||
*/
|
||||
public interface RoleService {
|
||||
|
||||
List<SysRole> listAll();
|
||||
|
||||
void create(RoleSaveRequest request);
|
||||
|
||||
void update(Long id, RoleSaveRequest request);
|
||||
|
||||
void remove(Long id);
|
||||
|
||||
void ensureBuiltin();
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.banben.modules.admin.service;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.banben.modules.admin.dto.UserSaveRequest;
|
||||
import com.banben.modules.admin.dto.UserVO;
|
||||
|
||||
/**
|
||||
* 用户管理。
|
||||
*/
|
||||
public interface UserAdminService {
|
||||
|
||||
Page<UserVO> page(long current, long size, String keyword, Long orgId, Long roleId);
|
||||
|
||||
void create(UserSaveRequest request);
|
||||
|
||||
void update(Long id, UserSaveRequest request);
|
||||
|
||||
void remove(Long id);
|
||||
}
|
||||
@@ -0,0 +1,376 @@
|
||||
package com.banben.modules.admin.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.banben.common.BusinessException;
|
||||
import com.banben.modules.admin.dto.UserSaveRequest;
|
||||
import com.banben.modules.admin.entity.SysOrg;
|
||||
import com.banben.modules.admin.entity.SysRole;
|
||||
import com.banben.modules.admin.mapper.SysOrgMapper;
|
||||
import com.banben.modules.admin.mapper.SysRoleMapper;
|
||||
import com.banben.modules.auth.entity.SysUser;
|
||||
import com.banben.modules.auth.mapper.SysUserMapper;
|
||||
import com.banben.modules.resource.dto.ImportResult;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
import org.apache.poi.ss.usermodel.CellStyle;
|
||||
import org.apache.poi.ss.usermodel.DataFormatter;
|
||||
import org.apache.poi.ss.usermodel.DataValidation;
|
||||
import org.apache.poi.ss.usermodel.DataValidationConstraint;
|
||||
import org.apache.poi.ss.usermodel.DataValidationHelper;
|
||||
import org.apache.poi.ss.usermodel.FillPatternType;
|
||||
import org.apache.poi.ss.usermodel.Font;
|
||||
import org.apache.poi.ss.usermodel.HorizontalAlignment;
|
||||
import org.apache.poi.ss.usermodel.IndexedColors;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.ss.usermodel.VerticalAlignment;
|
||||
import org.apache.poi.ss.usermodel.Workbook;
|
||||
import org.apache.poi.ss.usermodel.WorkbookFactory;
|
||||
import org.apache.poi.ss.util.CellRangeAddressList;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 用户导入模板与批量导入。
|
||||
*
|
||||
* <p>模板第 1 行是表头,第 2 行是说明,第 3 行起为数据。账号已存在时更新该用户,密码留空则不改原密码。</p>
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class UserExcelService {
|
||||
|
||||
private static final String[] HEADERS = {"登录账号*", "姓名*", "初始密码", "角色编码*", "组织编码", "状态"};
|
||||
private static final String[] HINTS = {
|
||||
"必填。示例行以「示例:」开头,导入时自动跳过",
|
||||
"必填",
|
||||
"选填。新增留空则为 123456;更新留空则不修改密码",
|
||||
"必填。填角色编码,见「可选数据」页",
|
||||
"选填。填组织编码,或「上级/本级」路径",
|
||||
"选填。启用 或 停用,默认启用"
|
||||
};
|
||||
private static final String[] SAMPLE = {"示例:zhangsan", "张三", "123456", "USER", "", "启用"};
|
||||
|
||||
private final SysUserMapper userMapper;
|
||||
private final SysRoleMapper roleMapper;
|
||||
private final SysOrgMapper orgMapper;
|
||||
private final UserAdminService userAdminService;
|
||||
private final DataFormatter formatter = new DataFormatter();
|
||||
|
||||
public void writeTemplate(OutputStream out) throws IOException {
|
||||
List<SysRole> roles = roleMapper.selectList(new LambdaQueryWrapper<SysRole>().orderByAsc(SysRole::getId));
|
||||
List<SysOrg> orgs = orgMapper.selectList(new LambdaQueryWrapper<SysOrg>().orderByAsc(SysOrg::getSortNo).orderByAsc(SysOrg::getId));
|
||||
Map<Long, SysOrg> byId = new HashMap<>();
|
||||
for (SysOrg org : orgs) {
|
||||
byId.put(org.getId(), org);
|
||||
}
|
||||
|
||||
try (XSSFWorkbook wb = new XSSFWorkbook()) {
|
||||
Sheet sheet = wb.createSheet("用户");
|
||||
CellStyle headStyle = headStyle(wb);
|
||||
CellStyle hintStyle = hintStyle(wb);
|
||||
Row head = sheet.createRow(0);
|
||||
Row hint = sheet.createRow(1);
|
||||
head.setHeightInPoints(22);
|
||||
hint.setHeightInPoints(32);
|
||||
int[] widths = {22, 16, 28, 22, 28, 16};
|
||||
for (int i = 0; i < HEADERS.length; i++) {
|
||||
Cell h = head.createCell(i);
|
||||
h.setCellValue(HEADERS[i]);
|
||||
h.setCellStyle(headStyle);
|
||||
Cell t = hint.createCell(i);
|
||||
t.setCellValue(HINTS[i]);
|
||||
t.setCellStyle(hintStyle);
|
||||
sheet.setColumnWidth(i, widths[i] * 256);
|
||||
}
|
||||
Row sample = sheet.createRow(2);
|
||||
for (int i = 0; i < SAMPLE.length; i++) {
|
||||
sample.createCell(i).setCellValue(SAMPLE[i]);
|
||||
}
|
||||
sheet.createFreezePane(0, 2);
|
||||
|
||||
Sheet dict = wb.createSheet("可选数据");
|
||||
Row dictHead = dict.createRow(0);
|
||||
dictHead.createCell(0).setCellValue("角色编码");
|
||||
dictHead.createCell(1).setCellValue("角色名称");
|
||||
dictHead.createCell(2).setCellValue("组织编码");
|
||||
dictHead.createCell(3).setCellValue("组织路径");
|
||||
for (int i = 0; i < roles.size(); i++) {
|
||||
Row row = dict.createRow(i + 1);
|
||||
row.createCell(0).setCellValue(roles.get(i).getCode());
|
||||
row.createCell(1).setCellValue(roles.get(i).getName());
|
||||
}
|
||||
int orgRow = 1;
|
||||
for (SysOrg org : orgs) {
|
||||
Row row = dict.getRow(orgRow);
|
||||
if (row == null) {
|
||||
row = dict.createRow(orgRow);
|
||||
}
|
||||
row.createCell(2).setCellValue(org.getCode() == null ? "" : org.getCode());
|
||||
row.createCell(3).setCellValue(pathOf(org, byId));
|
||||
orgRow++;
|
||||
}
|
||||
dict.setColumnWidth(0, 18 * 256);
|
||||
dict.setColumnWidth(1, 18 * 256);
|
||||
dict.setColumnWidth(2, 18 * 256);
|
||||
dict.setColumnWidth(3, 36 * 256);
|
||||
|
||||
if (!roles.isEmpty()) {
|
||||
dropdown(sheet, 3, "'可选数据'!$A$2:$A$" + (roles.size() + 1));
|
||||
}
|
||||
dropdown(sheet, 5, "\"启用,停用\"");
|
||||
wb.setActiveSheet(0);
|
||||
wb.write(out);
|
||||
}
|
||||
}
|
||||
|
||||
public ImportResult importExcel(MultipartFile file) throws IOException {
|
||||
ImportResult result = new ImportResult();
|
||||
if (file == null || file.isEmpty()) {
|
||||
result.addError(0, "请选择要导入的 Excel 文件");
|
||||
return result;
|
||||
}
|
||||
List<SysRole> roles = roleMapper.selectList(new LambdaQueryWrapper<>());
|
||||
List<SysOrg> orgs = orgMapper.selectList(new LambdaQueryWrapper<>());
|
||||
Map<Long, SysOrg> byId = new HashMap<>();
|
||||
for (SysOrg org : orgs) {
|
||||
byId.put(org.getId(), org);
|
||||
}
|
||||
try (Workbook wb = WorkbookFactory.create(file.getInputStream())) {
|
||||
Sheet sheet = wb.getNumberOfSheets() == 0 ? null : wb.getSheetAt(0);
|
||||
if (sheet == null || sheet.getLastRowNum() < 1) {
|
||||
result.addError(0, "表格为空,请使用系统导出的导入模板");
|
||||
return result;
|
||||
}
|
||||
Map<String, Integer> columns = headerIndex(sheet.getRow(0));
|
||||
if (!columns.containsKey("登录账号") || !columns.containsKey("姓名") || !columns.containsKey("角色编码")) {
|
||||
result.addError(1, "表头缺少登录账号、姓名或角色编码,请使用系统导出的导入模板");
|
||||
return result;
|
||||
}
|
||||
int start = hintRow(sheet) ? 2 : 1;
|
||||
for (int r = start; r <= sheet.getLastRowNum(); r++) {
|
||||
Row row = sheet.getRow(r);
|
||||
if (row == null) {
|
||||
continue;
|
||||
}
|
||||
String username = cell(row, columns.get("登录账号"));
|
||||
String realName = cell(row, columns.get("姓名"));
|
||||
String password = cell(row, columns.get("初始密码"));
|
||||
String roleText = cell(row, columns.get("角色编码"));
|
||||
String orgText = cell(row, columns.get("组织编码"));
|
||||
String statusText = cell(row, columns.get("状态"));
|
||||
if (!StringUtils.hasText(username) && !StringUtils.hasText(realName)
|
||||
&& !StringUtils.hasText(roleText)) {
|
||||
continue;
|
||||
}
|
||||
int excelRow = r + 1;
|
||||
if (isSample(username) || isSample(realName)) {
|
||||
result.setSkipped(result.getSkipped() + 1);
|
||||
continue;
|
||||
}
|
||||
result.setTotal(result.getTotal() + 1);
|
||||
try {
|
||||
importRow(username, realName, password, roleText, orgText, statusText, roles, orgs, byId, result);
|
||||
} catch (BusinessException e) {
|
||||
result.addError(excelRow, e.getMessage());
|
||||
}
|
||||
}
|
||||
if (result.getTotal() == 0 && result.getFailed() == 0) {
|
||||
result.addError(0, result.getSkipped() > 0
|
||||
? "仅读取到模板示例数据,请填写实际数据后再导入"
|
||||
: "未读取到有效数据行,请从第 3 行开始填写");
|
||||
}
|
||||
return result;
|
||||
} catch (BusinessException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
result.addError(0, "文件解析失败:" + e.getMessage());
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
private void importRow(String username, String realName, String password, String roleText, String orgText,
|
||||
String statusText, List<SysRole> roles, List<SysOrg> orgs, Map<Long, SysOrg> byId,
|
||||
ImportResult result) {
|
||||
if (!StringUtils.hasText(username)) {
|
||||
throw new BusinessException("登录账号不能为空");
|
||||
}
|
||||
if (!StringUtils.hasText(realName)) {
|
||||
throw new BusinessException("姓名不能为空");
|
||||
}
|
||||
SysRole role = matchRole(roleText, roles);
|
||||
if (role == null) {
|
||||
throw new BusinessException("角色不存在:" + roleText);
|
||||
}
|
||||
Long orgId = matchOrg(orgText, orgs, byId);
|
||||
Integer status = parseStatus(statusText);
|
||||
SysUser existing = userMapper.selectOne(new LambdaQueryWrapper<SysUser>()
|
||||
.eq(SysUser::getUsername, username.trim()));
|
||||
UserSaveRequest request = new UserSaveRequest();
|
||||
request.setUsername(username.trim());
|
||||
request.setRealName(realName.trim());
|
||||
request.setPassword(StringUtils.hasText(password) ? password.trim() : null);
|
||||
request.setRoleId(role.getId());
|
||||
request.setOrgId(orgId);
|
||||
request.setStatus(status);
|
||||
if (existing == null) {
|
||||
userAdminService.create(request);
|
||||
result.setInserted(result.getInserted() + 1);
|
||||
} else {
|
||||
userAdminService.update(existing.getId(), request);
|
||||
result.setUpdated(result.getUpdated() + 1);
|
||||
}
|
||||
}
|
||||
|
||||
private SysRole matchRole(String text, List<SysRole> roles) {
|
||||
if (!StringUtils.hasText(text)) {
|
||||
throw new BusinessException("角色编码不能为空");
|
||||
}
|
||||
String value = text.trim();
|
||||
for (SysRole role : roles) {
|
||||
if (role.getCode() != null && role.getCode().equalsIgnoreCase(value)) {
|
||||
return role;
|
||||
}
|
||||
}
|
||||
for (SysRole role : roles) {
|
||||
if (value.equals(role.getName())) {
|
||||
return role;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private Long matchOrg(String text, List<SysOrg> orgs, Map<Long, SysOrg> byId) {
|
||||
if (!StringUtils.hasText(text)) {
|
||||
return null;
|
||||
}
|
||||
String value = text.trim();
|
||||
for (SysOrg org : orgs) {
|
||||
if (value.equals(org.getCode())) {
|
||||
return org.getId();
|
||||
}
|
||||
}
|
||||
List<SysOrg> byPath = new ArrayList<>();
|
||||
List<SysOrg> byName = new ArrayList<>();
|
||||
for (SysOrg org : orgs) {
|
||||
if (value.equals(pathOf(org, byId))) {
|
||||
byPath.add(org);
|
||||
}
|
||||
if (value.equals(org.getName())) {
|
||||
byName.add(org);
|
||||
}
|
||||
}
|
||||
if (byPath.size() == 1) {
|
||||
return byPath.get(0).getId();
|
||||
}
|
||||
if (byName.size() == 1) {
|
||||
return byName.get(0).getId();
|
||||
}
|
||||
if (byName.size() > 1) {
|
||||
throw new BusinessException("组织名称不唯一,请填写组织编码");
|
||||
}
|
||||
throw new BusinessException("组织不存在:" + value);
|
||||
}
|
||||
|
||||
private Integer parseStatus(String text) {
|
||||
if (!StringUtils.hasText(text) || "启用".equals(text.trim()) || "1".equals(text.trim())) {
|
||||
return 1;
|
||||
}
|
||||
if ("停用".equals(text.trim()) || "0".equals(text.trim())) {
|
||||
return 0;
|
||||
}
|
||||
throw new BusinessException("状态只能填启用或停用");
|
||||
}
|
||||
|
||||
private String pathOf(SysOrg org, Map<Long, SysOrg> byId) {
|
||||
LinkedHashMap<Long, String> guard = new LinkedHashMap<>();
|
||||
List<String> parts = new ArrayList<>();
|
||||
SysOrg cursor = org;
|
||||
while (cursor != null && guard.put(cursor.getId(), cursor.getName()) == null) {
|
||||
parts.add(0, cursor.getName());
|
||||
cursor = cursor.getParentId() == null ? null : byId.get(cursor.getParentId());
|
||||
}
|
||||
return String.join("/", parts);
|
||||
}
|
||||
|
||||
private Map<String, Integer> headerIndex(Row head) {
|
||||
Map<String, Integer> columns = new HashMap<>();
|
||||
if (head == null) {
|
||||
return columns;
|
||||
}
|
||||
for (Cell cell : head) {
|
||||
String name = formatter.formatCellValue(cell).replace("*", "").replace("*", "").trim();
|
||||
if (StringUtils.hasText(name)) {
|
||||
columns.put(name, cell.getColumnIndex());
|
||||
}
|
||||
}
|
||||
return columns;
|
||||
}
|
||||
|
||||
private boolean hintRow(Sheet sheet) {
|
||||
Row second = sheet.getRow(1);
|
||||
if (second == null) {
|
||||
return false;
|
||||
}
|
||||
String first = formatter.formatCellValue(second.getCell(0));
|
||||
return first.startsWith("必填") || first.startsWith("选填");
|
||||
}
|
||||
|
||||
private String cell(Row row, Integer index) {
|
||||
if (index == null) {
|
||||
return "";
|
||||
}
|
||||
return formatter.formatCellValue(row.getCell(index)).trim();
|
||||
}
|
||||
|
||||
private boolean isSample(String value) {
|
||||
return value != null && (value.startsWith("示例:") || value.startsWith("示例:"));
|
||||
}
|
||||
|
||||
private void dropdown(Sheet sheet, int column, String formula) {
|
||||
DataValidationHelper helper = sheet.getDataValidationHelper();
|
||||
DataValidationConstraint constraint = formula.startsWith("\"")
|
||||
? helper.createExplicitListConstraint(new String[]{"启用", "停用"})
|
||||
: helper.createFormulaListConstraint(formula);
|
||||
CellRangeAddressList range = new CellRangeAddressList(2, 5000, column, column);
|
||||
DataValidation validation = helper.createValidation(constraint, range);
|
||||
validation.setSuppressDropDownArrow(true);
|
||||
validation.setShowErrorBox(true);
|
||||
sheet.addValidationData(validation);
|
||||
}
|
||||
|
||||
private CellStyle headStyle(Workbook wb) {
|
||||
CellStyle style = wb.createCellStyle();
|
||||
Font font = wb.createFont();
|
||||
font.setBold(true);
|
||||
font.setColor(IndexedColors.WHITE.getIndex());
|
||||
style.setFont(font);
|
||||
style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
|
||||
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
|
||||
style.setAlignment(HorizontalAlignment.CENTER);
|
||||
style.setVerticalAlignment(VerticalAlignment.CENTER);
|
||||
return style;
|
||||
}
|
||||
|
||||
private CellStyle hintStyle(Workbook wb) {
|
||||
CellStyle style = wb.createCellStyle();
|
||||
Font font = wb.createFont();
|
||||
font.setFontHeightInPoints((short) 9);
|
||||
font.setColor(IndexedColors.GREY_50_PERCENT.getIndex());
|
||||
style.setFont(font);
|
||||
style.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());
|
||||
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
|
||||
style.setWrapText(true);
|
||||
style.setVerticalAlignment(VerticalAlignment.CENTER);
|
||||
return style;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package com.banben.modules.admin.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.banben.common.BusinessException;
|
||||
import com.banben.modules.admin.dto.OrgSaveRequest;
|
||||
import com.banben.modules.admin.dto.OrgTreeVO;
|
||||
import com.banben.modules.admin.entity.SysOrg;
|
||||
import com.banben.modules.admin.mapper.SysOrgMapper;
|
||||
import com.banben.modules.admin.service.OrgService;
|
||||
import com.banben.modules.auth.entity.SysUser;
|
||||
import com.banben.modules.auth.mapper.SysUserMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 组织树的增删改。删除时若仍有下级或用户则拒绝。
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class OrgServiceImpl implements OrgService {
|
||||
|
||||
private final SysOrgMapper orgMapper;
|
||||
private final SysUserMapper userMapper;
|
||||
|
||||
@Override
|
||||
public List<OrgTreeVO> tree() {
|
||||
List<SysOrg> all = orgMapper.selectList(new LambdaQueryWrapper<SysOrg>()
|
||||
.orderByAsc(SysOrg::getSortNo)
|
||||
.orderByAsc(SysOrg::getId));
|
||||
Map<Long, OrgTreeVO> nodes = new HashMap<>();
|
||||
for (SysOrg org : all) {
|
||||
nodes.put(org.getId(), toVo(org));
|
||||
}
|
||||
List<OrgTreeVO> roots = new ArrayList<>();
|
||||
for (SysOrg org : all) {
|
||||
OrgTreeVO node = nodes.get(org.getId());
|
||||
OrgTreeVO parent = org.getParentId() == null ? null : nodes.get(org.getParentId());
|
||||
if (parent == null) {
|
||||
roots.add(node);
|
||||
} else {
|
||||
if (parent.getChildren() == null) {
|
||||
parent.setChildren(new ArrayList<>());
|
||||
}
|
||||
parent.getChildren().add(node);
|
||||
}
|
||||
}
|
||||
sortTree(roots);
|
||||
return roots;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void create(OrgSaveRequest request) {
|
||||
SysOrg org = new SysOrg();
|
||||
fill(org, request, null);
|
||||
orgMapper.insert(org);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update(Long id, OrgSaveRequest request) {
|
||||
SysOrg org = require(id);
|
||||
fill(org, request, id);
|
||||
orgMapper.update(null, new LambdaUpdateWrapper<SysOrg>()
|
||||
.eq(SysOrg::getId, id)
|
||||
.set(SysOrg::getParentId, org.getParentId())
|
||||
.set(SysOrg::getName, org.getName())
|
||||
.set(SysOrg::getCode, org.getCode())
|
||||
.set(SysOrg::getSortNo, org.getSortNo())
|
||||
.set(SysOrg::getStatus, org.getStatus())
|
||||
.set(SysOrg::getRemark, org.getRemark()));
|
||||
syncUserOrgName(org);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(Long id) {
|
||||
require(id);
|
||||
Long children = orgMapper.selectCount(new LambdaQueryWrapper<SysOrg>().eq(SysOrg::getParentId, id));
|
||||
if (children != null && children > 0) {
|
||||
throw new BusinessException("请先删除下级组织");
|
||||
}
|
||||
Long users = userMapper.selectCount(new LambdaQueryWrapper<SysUser>().eq(SysUser::getOrgId, id));
|
||||
if (users != null && users > 0) {
|
||||
throw new BusinessException("该组织下还有用户,不能删除");
|
||||
}
|
||||
orgMapper.deleteById(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Long> subtreeIds(Long orgId) {
|
||||
require(orgId);
|
||||
List<SysOrg> all = orgMapper.selectList(new LambdaQueryWrapper<>());
|
||||
Map<Long, List<Long>> children = new HashMap<>();
|
||||
for (SysOrg org : all) {
|
||||
if (org.getParentId() != null) {
|
||||
children.computeIfAbsent(org.getParentId(), key -> new ArrayList<>()).add(org.getId());
|
||||
}
|
||||
}
|
||||
Set<Long> ids = new HashSet<>();
|
||||
collect(orgId, children, ids);
|
||||
return ids;
|
||||
}
|
||||
|
||||
private void collect(Long id, Map<Long, List<Long>> children, Set<Long> ids) {
|
||||
if (!ids.add(id)) {
|
||||
return;
|
||||
}
|
||||
for (Long child : children.getOrDefault(id, List.of())) {
|
||||
collect(child, children, ids);
|
||||
}
|
||||
}
|
||||
|
||||
private void fill(SysOrg org, OrgSaveRequest request, Long selfId) {
|
||||
Long parentId = request.getParentId();
|
||||
if (parentId != null) {
|
||||
if (parentId.equals(selfId)) {
|
||||
throw new BusinessException("上级组织不能是自己");
|
||||
}
|
||||
require(parentId);
|
||||
assertNoCycle(selfId, parentId);
|
||||
}
|
||||
String code = blankToNull(request.getCode());
|
||||
assertCodeUnique(code, selfId);
|
||||
org.setParentId(parentId);
|
||||
org.setName(request.getName().trim());
|
||||
org.setCode(code);
|
||||
org.setSortNo(request.getSortNo() == null ? 0 : request.getSortNo());
|
||||
org.setStatus(request.getStatus() != null && request.getStatus() == 0 ? 0 : 1);
|
||||
org.setRemark(blankToNull(request.getRemark()));
|
||||
}
|
||||
|
||||
private void assertNoCycle(Long selfId, Long parentId) {
|
||||
if (selfId == null) {
|
||||
return;
|
||||
}
|
||||
Long cursor = parentId;
|
||||
Set<Long> seen = new HashSet<>();
|
||||
while (cursor != null) {
|
||||
if (cursor.equals(selfId)) {
|
||||
throw new BusinessException("不能把组织移动到自己的下级");
|
||||
}
|
||||
if (!seen.add(cursor)) {
|
||||
break;
|
||||
}
|
||||
SysOrg parent = orgMapper.selectById(cursor);
|
||||
cursor = parent == null ? null : parent.getParentId();
|
||||
}
|
||||
}
|
||||
|
||||
private void assertCodeUnique(String code, Long selfId) {
|
||||
if (code == null) {
|
||||
return;
|
||||
}
|
||||
LambdaQueryWrapper<SysOrg> query = new LambdaQueryWrapper<SysOrg>().eq(SysOrg::getCode, code);
|
||||
if (selfId != null) {
|
||||
query.ne(SysOrg::getId, selfId);
|
||||
}
|
||||
Long count = orgMapper.selectCount(query);
|
||||
if (count != null && count > 0) {
|
||||
throw new BusinessException("组织编码已存在");
|
||||
}
|
||||
}
|
||||
|
||||
private void syncUserOrgName(SysOrg org) {
|
||||
SysUser patch = new SysUser();
|
||||
patch.setOrgName(org.getName());
|
||||
userMapper.update(patch, new LambdaQueryWrapper<SysUser>().eq(SysUser::getOrgId, org.getId()));
|
||||
}
|
||||
|
||||
private SysOrg require(Long id) {
|
||||
SysOrg org = orgMapper.selectById(id);
|
||||
if (org == null) {
|
||||
throw new BusinessException("组织不存在");
|
||||
}
|
||||
return org;
|
||||
}
|
||||
|
||||
private OrgTreeVO toVo(SysOrg org) {
|
||||
OrgTreeVO vo = new OrgTreeVO();
|
||||
vo.setId(org.getId());
|
||||
vo.setParentId(org.getParentId());
|
||||
vo.setName(org.getName());
|
||||
vo.setCode(org.getCode());
|
||||
vo.setSortNo(org.getSortNo());
|
||||
vo.setStatus(org.getStatus());
|
||||
vo.setRemark(org.getRemark());
|
||||
return vo;
|
||||
}
|
||||
|
||||
private void sortTree(List<OrgTreeVO> nodes) {
|
||||
nodes.sort(Comparator
|
||||
.comparing((OrgTreeVO node) -> node.getSortNo() == null ? 0 : node.getSortNo())
|
||||
.thenComparing(OrgTreeVO::getId));
|
||||
for (OrgTreeVO node : nodes) {
|
||||
if (node.getChildren() != null) {
|
||||
sortTree(node.getChildren());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String blankToNull(String value) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
return null;
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package com.banben.modules.admin.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.banben.common.BusinessException;
|
||||
import com.banben.modules.admin.dto.RoleSaveRequest;
|
||||
import com.banben.modules.admin.entity.SysRole;
|
||||
import com.banben.modules.admin.mapper.SysRoleMapper;
|
||||
import com.banben.modules.admin.service.RoleService;
|
||||
import com.banben.modules.auth.entity.SysUser;
|
||||
import com.banben.modules.auth.mapper.SysUserMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 角色增删改。ADMIN、USER 为内置角色。
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class RoleServiceImpl implements RoleService {
|
||||
|
||||
private final SysRoleMapper roleMapper;
|
||||
private final SysUserMapper userMapper;
|
||||
|
||||
@Override
|
||||
public List<SysRole> listAll() {
|
||||
return roleMapper.selectList(new LambdaQueryWrapper<SysRole>()
|
||||
.orderByDesc(SysRole::getBuiltin)
|
||||
.orderByAsc(SysRole::getId));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void create(RoleSaveRequest request) {
|
||||
SysRole role = new SysRole();
|
||||
role.setBuiltin(0);
|
||||
fill(role, request, null);
|
||||
roleMapper.insert(role);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update(Long id, RoleSaveRequest request) {
|
||||
SysRole role = require(id);
|
||||
String previousCode = role.getCode();
|
||||
if (isBuiltin(role) && !previousCode.equalsIgnoreCase(request.getCode().trim())) {
|
||||
throw new BusinessException("内置角色不能修改编码");
|
||||
}
|
||||
fill(role, request, id);
|
||||
roleMapper.update(null, new LambdaUpdateWrapper<SysRole>()
|
||||
.eq(SysRole::getId, id)
|
||||
.set(SysRole::getCode, role.getCode())
|
||||
.set(SysRole::getName, role.getName())
|
||||
.set(SysRole::getRemark, role.getRemark())
|
||||
.set(SysRole::getStatus, role.getStatus()));
|
||||
if (!previousCode.equals(role.getCode())) {
|
||||
userMapper.update(null, new LambdaUpdateWrapper<SysUser>()
|
||||
.set(SysUser::getRole, role.getCode())
|
||||
.eq(SysUser::getRoleId, id));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(Long id) {
|
||||
SysRole role = require(id);
|
||||
if (isBuiltin(role)) {
|
||||
throw new BusinessException("内置角色不能删除");
|
||||
}
|
||||
Long users = userMapper.selectCount(new LambdaQueryWrapper<SysUser>().eq(SysUser::getRoleId, id));
|
||||
if (users != null && users > 0) {
|
||||
throw new BusinessException("该角色下还有用户,不能删除");
|
||||
}
|
||||
roleMapper.deleteById(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void ensureBuiltin() {
|
||||
ensure("ADMIN", "系统管理员", "系统内置,可管理组织、用户与角色");
|
||||
ensure("USER", "普通用户", "系统内置普通用户");
|
||||
}
|
||||
|
||||
private void ensure(String code, String name, String remark) {
|
||||
Long count = roleMapper.selectCount(new LambdaQueryWrapper<SysRole>().eq(SysRole::getCode, code));
|
||||
if (count != null && count > 0) {
|
||||
return;
|
||||
}
|
||||
SysRole role = new SysRole();
|
||||
role.setCode(code);
|
||||
role.setName(name);
|
||||
role.setRemark(remark);
|
||||
role.setStatus(1);
|
||||
role.setBuiltin(1);
|
||||
roleMapper.insert(role);
|
||||
}
|
||||
|
||||
private void fill(SysRole role, RoleSaveRequest request, Long selfId) {
|
||||
String code = request.getCode().trim().toUpperCase();
|
||||
LambdaQueryWrapper<SysRole> query = new LambdaQueryWrapper<SysRole>().eq(SysRole::getCode, code);
|
||||
if (selfId != null) {
|
||||
query.ne(SysRole::getId, selfId);
|
||||
}
|
||||
Long count = roleMapper.selectCount(query);
|
||||
if (count != null && count > 0) {
|
||||
throw new BusinessException("角色编码已存在");
|
||||
}
|
||||
role.setCode(code);
|
||||
role.setName(request.getName().trim());
|
||||
role.setRemark(StringUtils.hasText(request.getRemark()) ? request.getRemark().trim() : null);
|
||||
role.setStatus(request.getStatus() != null && request.getStatus() == 0 ? 0 : 1);
|
||||
}
|
||||
|
||||
private SysRole require(Long id) {
|
||||
SysRole role = roleMapper.selectById(id);
|
||||
if (role == null) {
|
||||
throw new BusinessException("角色不存在");
|
||||
}
|
||||
return role;
|
||||
}
|
||||
|
||||
private boolean isBuiltin(SysRole role) {
|
||||
return role.getBuiltin() != null && role.getBuiltin() == 1;
|
||||
}
|
||||
}
|
||||
+216
@@ -0,0 +1,216 @@
|
||||
package com.banben.modules.admin.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.banben.common.BusinessException;
|
||||
import com.banben.modules.admin.dto.UserSaveRequest;
|
||||
import com.banben.modules.admin.dto.UserVO;
|
||||
import com.banben.modules.admin.entity.SysOrg;
|
||||
import com.banben.modules.admin.entity.SysRole;
|
||||
import com.banben.modules.admin.mapper.SysOrgMapper;
|
||||
import com.banben.modules.admin.mapper.SysRoleMapper;
|
||||
import com.banben.modules.admin.service.OrgService;
|
||||
import com.banben.modules.admin.service.UserAdminService;
|
||||
import com.banben.modules.auth.context.UserContext;
|
||||
import com.banben.modules.auth.entity.SysUser;
|
||||
import com.banben.modules.auth.mapper.SysUserMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 用户新增、修改、删除。密码留空时,新增使用 123456,修改则保持原密码。
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class UserAdminServiceImpl implements UserAdminService {
|
||||
|
||||
static final String DEFAULT_PASSWORD = "123456";
|
||||
|
||||
private final SysUserMapper userMapper;
|
||||
private final SysRoleMapper roleMapper;
|
||||
private final SysOrgMapper orgMapper;
|
||||
private final OrgService orgService;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
@Override
|
||||
public Page<UserVO> page(long current, long size, String keyword, Long orgId, Long roleId) {
|
||||
LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<>();
|
||||
if (StringUtils.hasText(keyword)) {
|
||||
String word = keyword.trim();
|
||||
query.and(w -> w.like(SysUser::getUsername, word).or().like(SysUser::getRealName, word));
|
||||
}
|
||||
if (orgId != null) {
|
||||
query.in(SysUser::getOrgId, orgService.subtreeIds(orgId));
|
||||
}
|
||||
if (roleId != null) {
|
||||
query.eq(SysUser::getRoleId, roleId);
|
||||
}
|
||||
query.orderByDesc(SysUser::getId);
|
||||
Page<SysUser> raw = userMapper.selectPage(new Page<>(current, size), query);
|
||||
|
||||
Map<Long, SysRole> roles = roleMapper.selectList(new LambdaQueryWrapper<>()).stream()
|
||||
.collect(Collectors.toMap(SysRole::getId, role -> role, (a, b) -> a));
|
||||
Map<Long, SysOrg> orgs = orgMapper.selectList(new LambdaQueryWrapper<>()).stream()
|
||||
.collect(Collectors.toMap(SysOrg::getId, org -> org, (a, b) -> a));
|
||||
|
||||
Page<UserVO> page = new Page<>(raw.getCurrent(), raw.getSize(), raw.getTotal());
|
||||
page.setRecords(raw.getRecords().stream().map(user -> toVo(user, roles, orgs)).toList());
|
||||
return page;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void create(UserSaveRequest request) {
|
||||
SysRole role = requireRole(request.getRoleId());
|
||||
SysOrg org = optionalOrg(request.getOrgId());
|
||||
assertUsernameFree(request.getUsername().trim(), null);
|
||||
assertPassword(request.getPassword(), true);
|
||||
SysUser user = new SysUser();
|
||||
user.setUsername(request.getUsername().trim());
|
||||
user.setPassword(passwordEncoder.encode(passwordOrDefault(request.getPassword())));
|
||||
user.setRealName(request.getRealName().trim());
|
||||
user.setRoleId(role.getId());
|
||||
user.setRole(role.getCode());
|
||||
user.setOrgId(org == null ? null : org.getId());
|
||||
user.setOrgName(org == null ? null : org.getName());
|
||||
user.setStatus(statusOf(request.getStatus()));
|
||||
try {
|
||||
userMapper.insert(user);
|
||||
} catch (DuplicateKeyException e) {
|
||||
throw new BusinessException("登录账号已存在");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update(Long id, UserSaveRequest request) {
|
||||
SysUser existing = requireUser(id);
|
||||
SysRole role = requireRole(request.getRoleId());
|
||||
SysOrg org = optionalOrg(request.getOrgId());
|
||||
assertUsernameFree(request.getUsername().trim(), id);
|
||||
assertPassword(request.getPassword(), false);
|
||||
guardLastAdmin(existing, role.getCode(), statusOf(request.getStatus()), false);
|
||||
LambdaUpdateWrapper<SysUser> update = new LambdaUpdateWrapper<SysUser>()
|
||||
.eq(SysUser::getId, id)
|
||||
.set(SysUser::getUsername, request.getUsername().trim())
|
||||
.set(SysUser::getRealName, request.getRealName().trim())
|
||||
.set(SysUser::getRoleId, role.getId())
|
||||
.set(SysUser::getRole, role.getCode())
|
||||
.set(SysUser::getOrgId, org == null ? null : org.getId())
|
||||
.set(SysUser::getOrgName, org == null ? null : org.getName())
|
||||
.set(SysUser::getStatus, statusOf(request.getStatus()));
|
||||
if (StringUtils.hasText(request.getPassword())) {
|
||||
update.set(SysUser::getPassword, passwordEncoder.encode(request.getPassword().trim()));
|
||||
}
|
||||
try {
|
||||
userMapper.update(null, update);
|
||||
} catch (DuplicateKeyException e) {
|
||||
throw new BusinessException("登录账号已存在");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(Long id) {
|
||||
SysUser existing = requireUser(id);
|
||||
if (id.equals(UserContext.currentUserId())) {
|
||||
throw new BusinessException("不能删除当前登录账号");
|
||||
}
|
||||
guardLastAdmin(existing, null, 0, true);
|
||||
userMapper.deleteById(id);
|
||||
}
|
||||
|
||||
private void guardLastAdmin(SysUser existing, String nextRole, int nextStatus, boolean deleting) {
|
||||
if (!"ADMIN".equalsIgnoreCase(existing.getRole())) {
|
||||
return;
|
||||
}
|
||||
boolean stillAdmin = !deleting && "ADMIN".equalsIgnoreCase(nextRole) && nextStatus == 1;
|
||||
if (stillAdmin) {
|
||||
return;
|
||||
}
|
||||
Long admins = userMapper.selectCount(new LambdaQueryWrapper<SysUser>()
|
||||
.eq(SysUser::getRole, "ADMIN")
|
||||
.eq(SysUser::getStatus, 1)
|
||||
.ne(SysUser::getId, existing.getId()));
|
||||
if (admins == null || admins == 0) {
|
||||
throw new BusinessException("至少保留一个启用的系统管理员");
|
||||
}
|
||||
}
|
||||
|
||||
private void assertUsernameFree(String username, Long selfId) {
|
||||
LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username);
|
||||
if (selfId != null) {
|
||||
query.ne(SysUser::getId, selfId);
|
||||
}
|
||||
Long count = userMapper.selectCount(query);
|
||||
if (count != null && count > 0) {
|
||||
throw new BusinessException("登录账号已存在");
|
||||
}
|
||||
}
|
||||
|
||||
private SysUser requireUser(Long id) {
|
||||
SysUser user = userMapper.selectById(id);
|
||||
if (user == null) {
|
||||
throw new BusinessException("用户不存在");
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
private SysRole requireRole(Long roleId) {
|
||||
SysRole role = roleMapper.selectById(roleId);
|
||||
if (role == null) {
|
||||
throw new BusinessException("角色不存在");
|
||||
}
|
||||
return role;
|
||||
}
|
||||
|
||||
private SysOrg optionalOrg(Long orgId) {
|
||||
if (orgId == null) {
|
||||
return null;
|
||||
}
|
||||
SysOrg org = orgMapper.selectById(orgId);
|
||||
if (org == null) {
|
||||
throw new BusinessException("组织不存在");
|
||||
}
|
||||
return org;
|
||||
}
|
||||
|
||||
private int statusOf(Integer status) {
|
||||
return status != null && status == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
private String passwordOrDefault(String password) {
|
||||
return StringUtils.hasText(password) ? password.trim() : DEFAULT_PASSWORD;
|
||||
}
|
||||
|
||||
private void assertPassword(String password, boolean creating) {
|
||||
if (!StringUtils.hasText(password)) {
|
||||
return;
|
||||
}
|
||||
if (password.trim().length() < 6) {
|
||||
throw new BusinessException(creating ? "密码至少 6 位,留空则使用 123456" : "密码至少 6 位");
|
||||
}
|
||||
}
|
||||
|
||||
private UserVO toVo(SysUser user, Map<Long, SysRole> roles, Map<Long, SysOrg> orgs) {
|
||||
UserVO vo = new UserVO();
|
||||
vo.setId(user.getId());
|
||||
vo.setUsername(user.getUsername());
|
||||
vo.setRealName(user.getRealName());
|
||||
vo.setRoleId(user.getRoleId());
|
||||
vo.setRoleCode(user.getRole());
|
||||
SysRole role = user.getRoleId() == null ? null : roles.get(user.getRoleId());
|
||||
vo.setRoleName(role == null ? user.getRole() : role.getName());
|
||||
vo.setOrgId(user.getOrgId());
|
||||
SysOrg org = user.getOrgId() == null ? null : orgs.get(user.getOrgId());
|
||||
vo.setOrgName(org == null ? user.getOrgName() : org.getName());
|
||||
vo.setStatus(user.getStatus());
|
||||
vo.setLastLoginTime(user.getLastLoginTime());
|
||||
vo.setCreateTime(user.getCreateTime());
|
||||
return vo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.banben.modules.admin.support;
|
||||
|
||||
import com.banben.common.BusinessException;
|
||||
import com.banben.modules.auth.context.LoginUser;
|
||||
import com.banben.modules.auth.context.UserContext;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 组织、角色、用户管理只允许管理员调用。
|
||||
*/
|
||||
@Component
|
||||
public class AdminAccess {
|
||||
|
||||
public void require() {
|
||||
LoginUser user = UserContext.get();
|
||||
if (user == null || user.role() == null || !"ADMIN".equalsIgnoreCase(user.role())) {
|
||||
throw new BusinessException(403, "需要管理员权限");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
@@ -26,18 +27,25 @@ public class SysUser implements Serializable {
|
||||
@Schema(description = "登录账号")
|
||||
private String username;
|
||||
|
||||
@JsonIgnore
|
||||
@Schema(description = "BCrypt 加密后的密码")
|
||||
private String password;
|
||||
|
||||
@Schema(description = "姓名")
|
||||
private String realName;
|
||||
|
||||
@Schema(description = "角色:ADMIN / USER")
|
||||
@Schema(description = "角色编码,与 sys_role.code 一致,写入登录令牌")
|
||||
private String role;
|
||||
|
||||
@Schema(description = "所属单位")
|
||||
@Schema(description = "角色,对应 sys_role.id")
|
||||
private Long roleId;
|
||||
|
||||
@Schema(description = "所属单位名称,与组织名称同步")
|
||||
private String orgName;
|
||||
|
||||
@Schema(description = "所属组织,对应 sys_org.id")
|
||||
private Long orgId;
|
||||
|
||||
@Schema(description = "状态:1启用 0停用")
|
||||
private Integer status;
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@ import com.banben.common.BusinessException;
|
||||
import com.banben.modules.auth.context.UserContext;
|
||||
import com.banben.modules.auth.dto.LoginRequest;
|
||||
import com.banben.modules.auth.dto.LoginResponse;
|
||||
import com.banben.modules.admin.entity.SysRole;
|
||||
import com.banben.modules.admin.mapper.SysRoleMapper;
|
||||
import com.banben.modules.auth.entity.SysUser;
|
||||
import com.banben.modules.auth.mapper.SysUserMapper;
|
||||
import com.banben.modules.auth.service.AuthService;
|
||||
@@ -25,6 +27,7 @@ import java.time.LocalDateTime;
|
||||
public class AuthServiceImpl implements AuthService {
|
||||
|
||||
private final SysUserMapper sysUserMapper;
|
||||
private final SysRoleMapper sysRoleMapper;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final JwtUtil jwtUtil;
|
||||
|
||||
@@ -40,6 +43,13 @@ public class AuthServiceImpl implements AuthService {
|
||||
if (user.getStatus() != null && user.getStatus() == 0) {
|
||||
throw new BusinessException("账号已停用,请联系管理员");
|
||||
}
|
||||
if (user.getRoleId() != null) {
|
||||
SysRole role = sysRoleMapper.selectById(user.getRoleId());
|
||||
if (role == null || (role.getStatus() != null && role.getStatus() == 0)) {
|
||||
throw new BusinessException("角色已停用,请联系管理员");
|
||||
}
|
||||
user.setRole(role.getCode());
|
||||
}
|
||||
|
||||
user.setLastLoginTime(LocalDateTime.now());
|
||||
sysUserMapper.updateById(user);
|
||||
|
||||
+237
-2
@@ -78,6 +78,30 @@ public class GovernanceServiceImpl extends ServiceImpl<GovernanceJobMapper, Gove
|
||||
|
||||
private static final int BATCH = 500;
|
||||
|
||||
/** 不超过该行数时,提示和提纯仍在内存里做题名包含等细查。超过后改走数据库聚合,避免整表进堆。 */
|
||||
private static final int FULL_SCAN_MAX = 20000;
|
||||
|
||||
/** 清单返回给页面的上限。条数仍按全库统计。 */
|
||||
private static final int HINT_LIST_LIMIT = 200;
|
||||
|
||||
/**
|
||||
* 与 {@link #defectsOf} 一致的错漏条件。只在超过 {@link #FULL_SCAN_MAX} 时使用,
|
||||
* 用来计数和打标,不再把整表装进内存。
|
||||
*/
|
||||
private static final String DEFECT_SQL = """
|
||||
(btrim(coalesce(clc_code, '')) = ''
|
||||
OR btrim(coalesce(keywords, '')) = ''
|
||||
OR char_length(btrim(coalesce(summary, ''))) < 100
|
||||
OR btrim(coalesce(publish_year, '')) !~ '^[0-9]{4}$'
|
||||
OR btrim(coalesce(media_type, '')) NOT IN ('纸质', '电子')
|
||||
OR btrim(coalesce(language, '')) !~ '^[A-Za-z]{3}$'
|
||||
OR btrim(coalesce(page_count, '')) !~ '^[0-9]+$'
|
||||
OR btrim(coalesce(author, '')) = ''
|
||||
OR btrim(coalesce(fulltext_url, '')) = ''
|
||||
OR btrim(coalesce(source_library, '')) = ''
|
||||
OR (btrim(coalesce(isbn, '')) <> '' AND btrim(isbn) !~ '^97[89](-[0-9]+){4}$'))
|
||||
""";
|
||||
|
||||
private final VersionResourceMapper resourceMapper;
|
||||
|
||||
@Override
|
||||
@@ -117,9 +141,14 @@ public class GovernanceServiceImpl extends ServiceImpl<GovernanceJobMapper, Gove
|
||||
try {
|
||||
vo = buildHints(true);
|
||||
job.setAffectedCount(vo.getDuplicateGroupCount() + vo.getDefectCount());
|
||||
job.setResultSummary(String.format(
|
||||
String summary = String.format(
|
||||
"疑似同一文献 %d 组;疑似元数据错漏 %d 条(错漏记录已标记,请人工核验)",
|
||||
vo.getDuplicateGroupCount(), vo.getDefectCount()));
|
||||
vo.getDuplicateGroupCount(), vo.getDefectCount());
|
||||
if (vo.getDuplicateGroups().size() < vo.getDuplicateGroupCount()
|
||||
|| vo.getDefects().size() < vo.getDefectCount()) {
|
||||
summary += "。清单过长,页面只展示前 " + HINT_LIST_LIMIT + " 条";
|
||||
}
|
||||
job.setResultSummary(summary);
|
||||
job.setStatus("SUCCESS");
|
||||
vo.setJob(job);
|
||||
} catch (Exception e) {
|
||||
@@ -428,6 +457,9 @@ public class GovernanceServiceImpl extends ServiceImpl<GovernanceJobMapper, Gove
|
||||
* 疑似错漏:必备要素缺失、摘要不足 100 字、年份/语种/页码/ISBN 格式不正确。
|
||||
*/
|
||||
private GovernanceHintVO buildHints(boolean persistFlag) {
|
||||
if (countActive() > FULL_SCAN_MAX) {
|
||||
return buildHintsForLargeTable(persistFlag);
|
||||
}
|
||||
List<VersionResource> active = loadActive();
|
||||
GovernanceHintVO vo = new GovernanceHintVO();
|
||||
vo.setDuplicateGroups(findSuspectedDuplicates(active));
|
||||
@@ -454,6 +486,103 @@ public class GovernanceServiceImpl extends ServiceImpl<GovernanceJobMapper, Gove
|
||||
return vo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 大表不再整表读入。疑似重复只按 ISBN、或无 ISBN 时的书名+作者+出版社+出版年份在库里聚合;
|
||||
* 题名互相包含这类细查只在 {@link #FULL_SCAN_MAX} 以内做。错漏用 {@link #DEFECT_SQL} 计数和打标,
|
||||
* 页面只带回前 {@link #HINT_LIST_LIMIT} 条。
|
||||
*/
|
||||
private GovernanceHintVO buildHintsForLargeTable(boolean persistFlag) {
|
||||
GovernanceHintVO vo = new GovernanceHintVO();
|
||||
List<DuplicateGroupVO> groups = new ArrayList<>();
|
||||
vo.setDuplicateGroupCount(appendExactDuplicateGroups(groups, HINT_LIST_LIMIT));
|
||||
vo.setDuplicateGroups(groups);
|
||||
|
||||
long defectCount = countDefects();
|
||||
vo.setDefectCount(defectCount > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) defectCount);
|
||||
vo.setDefects(sampleDefects(HINT_LIST_LIMIT));
|
||||
if (persistFlag) {
|
||||
markDefectsBySql();
|
||||
}
|
||||
return vo;
|
||||
}
|
||||
|
||||
private int appendExactDuplicateGroups(List<DuplicateGroupVO> groups, int limit) {
|
||||
int count = 0;
|
||||
for (Map<String, Object> group : isbnDuplicateGroups()) {
|
||||
count++;
|
||||
if (groups.size() >= limit) {
|
||||
continue;
|
||||
}
|
||||
Object isbn = group.get("isbn");
|
||||
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
|
||||
query.eq(VersionResource::getIsbn, isbn)
|
||||
.and(this::notMergedOut)
|
||||
.orderByAsc(VersionResource::getId);
|
||||
groups.add(toDuplicateGroup("ISBN 相同,疑似同一文献", String.valueOf(isbn), resourceMapper.selectList(query)));
|
||||
}
|
||||
for (Map<String, Object> group : fieldDuplicateGroups()) {
|
||||
count++;
|
||||
if (groups.size() >= limit) {
|
||||
continue;
|
||||
}
|
||||
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
|
||||
query.eq(VersionResource::getTitle, group.get("title"));
|
||||
eqOrIsNull(query, VersionResource::getAuthor, group.get("author"));
|
||||
eqOrIsNull(query, VersionResource::getPublisher, group.get("publisher"));
|
||||
eqOrIsNull(query, VersionResource::getPublishYear, group.get("publish_year"));
|
||||
query.and(x -> x.isNull(VersionResource::getIsbn).or().eq(VersionResource::getIsbn, ""))
|
||||
.and(this::notMergedOut)
|
||||
.orderByAsc(VersionResource::getId);
|
||||
String key = text(group.get("title") == null ? null : String.valueOf(group.get("title")));
|
||||
groups.add(toDuplicateGroup("书名、责任者、出版社、出版年份一致,疑似同一文献", key, resourceMapper.selectList(query)));
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
private long countDefects() {
|
||||
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
|
||||
query.and(this::notMergedOut).apply(DEFECT_SQL);
|
||||
Long count = resourceMapper.selectCount(query);
|
||||
return count == null ? 0 : count;
|
||||
}
|
||||
|
||||
private List<DefectItemVO> sampleDefects(int limit) {
|
||||
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
|
||||
query.and(this::notMergedOut)
|
||||
.apply(DEFECT_SQL)
|
||||
.orderByAsc(VersionResource::getId)
|
||||
.last("LIMIT " + limit);
|
||||
List<DefectItemVO> defects = new ArrayList<>();
|
||||
for (VersionResource resource : resourceMapper.selectList(query)) {
|
||||
List<String> issues = defectsOf(resource);
|
||||
if (!issues.isEmpty()) {
|
||||
defects.add(toDefect(resource, issues));
|
||||
}
|
||||
}
|
||||
return defects;
|
||||
}
|
||||
|
||||
private void markDefectsBySql() {
|
||||
LambdaUpdateWrapper<VersionResource> mark = new LambdaUpdateWrapper<>();
|
||||
mark.set(VersionResource::getAbnormalFlag, 1)
|
||||
.and(this::notMergedOutUpdate)
|
||||
.apply(DEFECT_SQL);
|
||||
resourceMapper.update(null, mark);
|
||||
|
||||
LambdaUpdateWrapper<VersionResource> clear = new LambdaUpdateWrapper<>();
|
||||
clear.set(VersionResource::getAbnormalFlag, 0)
|
||||
.eq(VersionResource::getAbnormalFlag, 1)
|
||||
.and(this::notMergedOutUpdate)
|
||||
.apply("NOT (" + DEFECT_SQL + ")");
|
||||
resourceMapper.update(null, clear);
|
||||
}
|
||||
|
||||
private void notMergedOutUpdate(LambdaUpdateWrapper<VersionResource> query) {
|
||||
query.isNull(VersionResource::getGovernStatus)
|
||||
.or()
|
||||
.ne(VersionResource::getGovernStatus, GovernStatus.MERGED_OUT.getCode());
|
||||
}
|
||||
|
||||
private List<DuplicateGroupVO> findSuspectedDuplicates(List<VersionResource> active) {
|
||||
List<DuplicateGroupVO> groups = new ArrayList<>();
|
||||
Set<Long> emitted = new HashSet<>();
|
||||
@@ -606,6 +735,10 @@ public class GovernanceServiceImpl extends ServiceImpl<GovernanceJobMapper, Gove
|
||||
* 尚未聚同的重复文献、已聚同但还没优化的主记录、仍有错漏的记录。
|
||||
*/
|
||||
private void runPurify(GovernanceJob job) {
|
||||
if (countActive() > FULL_SCAN_MAX) {
|
||||
runPurifyInBatches(job);
|
||||
return;
|
||||
}
|
||||
List<VersionResource> active = loadActive();
|
||||
Set<Long> unresolved = unresolvedDuplicateIds(active);
|
||||
|
||||
@@ -691,6 +824,108 @@ public class GovernanceServiceImpl extends ServiceImpl<GovernanceJobMapper, Gove
|
||||
|
||||
// ==================== 公共方法 ====================
|
||||
|
||||
private void runPurifyInBatches(GovernanceJob job) {
|
||||
Set<Long> unresolved = duplicateIdsBySql();
|
||||
int nonBook = 0;
|
||||
int sensitive = 0;
|
||||
int blocked = 0;
|
||||
int duplicated = 0;
|
||||
int waitOptimize = 0;
|
||||
int defect = 0;
|
||||
List<Long> accepted = new ArrayList<>();
|
||||
long lastId = 0;
|
||||
while (true) {
|
||||
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
|
||||
query.and(this::notMergedOut)
|
||||
.gt(VersionResource::getId, lastId)
|
||||
.orderByAsc(VersionResource::getId)
|
||||
.last("LIMIT " + BATCH);
|
||||
List<VersionResource> batch = resourceMapper.selectList(query);
|
||||
if (batch.isEmpty()) {
|
||||
break;
|
||||
}
|
||||
lastId = batch.get(batch.size() - 1).getId();
|
||||
for (VersionResource resource : batch) {
|
||||
if (GovernStatus.FINAL.getCode().equals(resource.getGovernStatus())) {
|
||||
continue;
|
||||
}
|
||||
if (!paperElectronicBook(resource)) {
|
||||
nonBook++;
|
||||
continue;
|
||||
}
|
||||
if (resource.getSensitiveFlag() != null && resource.getSensitiveFlag() == 1) {
|
||||
sensitive++;
|
||||
continue;
|
||||
}
|
||||
if (resource.getManageStatus() != null && resource.getManageStatus() != 0) {
|
||||
blocked++;
|
||||
continue;
|
||||
}
|
||||
if (unresolved.contains(resource.getId())) {
|
||||
duplicated++;
|
||||
continue;
|
||||
}
|
||||
if (GovernStatus.MERGED.getCode().equals(resource.getGovernStatus())) {
|
||||
waitOptimize++;
|
||||
continue;
|
||||
}
|
||||
if (!defectsOf(resource).isEmpty()) {
|
||||
defect++;
|
||||
continue;
|
||||
}
|
||||
accepted.add(resource.getId());
|
||||
}
|
||||
}
|
||||
updateStatus(accepted, GovernStatus.FINAL.getCode());
|
||||
job.setAffectedCount(accepted.size());
|
||||
job.setResultSummary(String.format(
|
||||
"已将 %d 条纸电图书纳入版本资源数据集。"
|
||||
+ "未纳入:非纸电图书 %d 条,敏感 %d 条,已屏蔽或下架 %d 条,"
|
||||
+ "尚未聚同的重复文献 %d 条,已聚同但未优化 %d 条,仍有错漏 %d 条",
|
||||
accepted.size(), nonBook, sensitive, blocked, duplicated, waitOptimize, defect));
|
||||
}
|
||||
|
||||
private Set<Long> duplicateIdsBySql() {
|
||||
Set<Long> ids = new HashSet<>();
|
||||
QueryWrapper<VersionResource> byIsbn = new QueryWrapper<>();
|
||||
byIsbn.select("id")
|
||||
.apply("btrim(coalesce(isbn, '')) <> ''")
|
||||
.and(w -> w.isNull("govern_status").or().ne("govern_status", GovernStatus.MERGED_OUT.getCode()))
|
||||
.inSql("isbn", "SELECT isbn FROM version_resource WHERE deleted = 0 "
|
||||
+ "AND (govern_status IS NULL OR govern_status <> 'MERGED_OUT') "
|
||||
+ "AND btrim(coalesce(isbn, '')) <> '' "
|
||||
+ "GROUP BY isbn HAVING COUNT(*) > 1");
|
||||
collectIds(ids, resourceMapper.selectMaps(byIsbn));
|
||||
|
||||
QueryWrapper<VersionResource> byField = new QueryWrapper<>();
|
||||
byField.select("id")
|
||||
.apply("btrim(coalesce(isbn, '')) = ''")
|
||||
.and(w -> w.isNull("govern_status").or().ne("govern_status", GovernStatus.MERGED_OUT.getCode()))
|
||||
.apply("(title, author, publisher, publish_year) IN ("
|
||||
+ "SELECT title, author, publisher, publish_year FROM version_resource "
|
||||
+ "WHERE deleted = 0 AND (govern_status IS NULL OR govern_status <> 'MERGED_OUT') "
|
||||
+ "AND btrim(coalesce(isbn, '')) = '' AND title IS NOT NULL "
|
||||
+ "GROUP BY title, author, publisher, publish_year HAVING COUNT(*) > 1)");
|
||||
collectIds(ids, resourceMapper.selectMaps(byField));
|
||||
return ids;
|
||||
}
|
||||
|
||||
private void collectIds(Set<Long> ids, List<Map<String, Object>> rows) {
|
||||
for (Map<String, Object> row : rows) {
|
||||
Object id = row.get("id");
|
||||
if (id instanceof Number number) {
|
||||
ids.add(number.longValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private long countActive() {
|
||||
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
|
||||
query.and(this::notMergedOut);
|
||||
Long count = resourceMapper.selectCount(query);
|
||||
return count == null ? 0 : count;
|
||||
}
|
||||
|
||||
private List<VersionResource> loadActive() {
|
||||
LambdaQueryWrapper<VersionResource> query = new LambdaQueryWrapper<>();
|
||||
query.and(this::notMergedOut).orderByAsc(VersionResource::getId);
|
||||
|
||||
@@ -23,7 +23,8 @@ mybatis-plus:
|
||||
mapper-locations: classpath*:mapper/**/*.xml
|
||||
configuration:
|
||||
map-underscore-to-camel-case: true
|
||||
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
|
||||
# 使用 SLF4J,不要换成 StdOutImpl。StdOutImpl 会把结果集每一列打到 System.out,
|
||||
# 大查询占住控制台锁后,登录等其它请求会一起卡住。
|
||||
global-config:
|
||||
banner: false
|
||||
db-config:
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
-- 组织、角色,以及用户与二者的关联。可重复执行。
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sys_org
|
||||
(
|
||||
id BIGSERIAL NOT NULL PRIMARY KEY,
|
||||
parent_id BIGINT,
|
||||
name VARCHAR(128) NOT NULL,
|
||||
code VARCHAR(64),
|
||||
sort_no INT DEFAULT 0,
|
||||
status SMALLINT DEFAULT 1,
|
||||
remark VARCHAR(256),
|
||||
deleted SMALLINT DEFAULT 0,
|
||||
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_sys_org_parent ON sys_org (parent_id);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uk_sys_org_code
|
||||
ON sys_org (code) WHERE deleted = 0 AND code IS NOT NULL AND code <> '';
|
||||
|
||||
COMMENT ON TABLE sys_org IS '组织,parent_id 为空表示顶级';
|
||||
COMMENT ON COLUMN sys_org.parent_id IS '上级组织,空为顶级';
|
||||
COMMENT ON COLUMN sys_org.name IS '组织名称';
|
||||
COMMENT ON COLUMN sys_org.code IS '组织编码,未删除时唯一';
|
||||
COMMENT ON COLUMN sys_org.sort_no IS '同级排序,小的在前';
|
||||
COMMENT ON COLUMN sys_org.status IS '1启用 0停用';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sys_role
|
||||
(
|
||||
id BIGSERIAL NOT NULL PRIMARY KEY,
|
||||
code VARCHAR(32) NOT NULL,
|
||||
name VARCHAR(64) NOT NULL,
|
||||
remark VARCHAR(256),
|
||||
status SMALLINT DEFAULT 1,
|
||||
builtin SMALLINT DEFAULT 0,
|
||||
deleted SMALLINT DEFAULT 0,
|
||||
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uk_sys_role_code
|
||||
ON sys_role (code) WHERE deleted = 0;
|
||||
|
||||
COMMENT ON TABLE sys_role IS '角色。builtin=1 为内置角色,不可删除';
|
||||
COMMENT ON COLUMN sys_role.code IS '角色编码,登录令牌沿用该编码';
|
||||
COMMENT ON COLUMN sys_role.builtin IS '1内置 0自建';
|
||||
|
||||
INSERT INTO sys_role (code, name, remark, status, builtin)
|
||||
SELECT 'ADMIN', '系统管理员', '系统内置,可管理组织、用户与角色', 1, 1
|
||||
WHERE NOT EXISTS (SELECT 1 FROM sys_role WHERE code = 'ADMIN' AND deleted = 0);
|
||||
|
||||
INSERT INTO sys_role (code, name, remark, status, builtin)
|
||||
SELECT 'USER', '普通用户', '系统内置普通用户', 1, 1
|
||||
WHERE NOT EXISTS (SELECT 1 FROM sys_role WHERE code = 'USER' AND deleted = 0);
|
||||
|
||||
ALTER TABLE sys_user ADD COLUMN IF NOT EXISTS org_id BIGINT;
|
||||
ALTER TABLE sys_user ADD COLUMN IF NOT EXISTS role_id BIGINT;
|
||||
CREATE INDEX IF NOT EXISTS idx_sys_user_org ON sys_user (org_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_sys_user_role ON sys_user (role_id);
|
||||
|
||||
COMMENT ON COLUMN sys_user.org_id IS '所属组织,对应 sys_org.id';
|
||||
COMMENT ON COLUMN sys_user.role_id IS '角色,对应 sys_role.id;role 列保存角色编码供登录使用';
|
||||
|
||||
UPDATE sys_user u
|
||||
SET role_id = r.id
|
||||
FROM sys_role r
|
||||
WHERE u.role_id IS NULL
|
||||
AND u.deleted = 0
|
||||
AND r.deleted = 0
|
||||
AND upper(u.role) = upper(r.code);
|
||||
Reference in New Issue
Block a user