1
0
mirror of https://github.com/FatttSnake/Pinnacle-OA.git synced 2026-04-04 22:41:24 +08:00

Added UserManagement

This commit is contained in:
2023-05-17 15:39:28 +08:00
parent e1bdb21756
commit e5a3cb83be
13 changed files with 656 additions and 58 deletions

View File

@@ -1,14 +1,13 @@
package com.cfive.pinnacle.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cfive.pinnacle.entity.User;
import com.cfive.pinnacle.entity.common.ResponseCode;
import com.cfive.pinnacle.entity.common.ResponseResult;
import com.cfive.pinnacle.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@@ -32,13 +31,54 @@ public class UserController {
@GetMapping
public ResponseResult getAllUser() {
List<User> users = userService.getBasicInfo();
return ResponseResult.build(ResponseCode.DATABASE_SELECT_OK, "success", users);
List<User> users = userService.getAllUser();
return ResponseResult.databaseSelectSuccess(users);
}
@GetMapping("/{id}")
public ResponseResult getUser(@PathVariable int id) {
User user = userService.getBasicInfo(id);
return ResponseResult.build(ResponseCode.DATABASE_SELECT_OK, "success", user);
public ResponseResult getUser(@PathVariable Long id) {
User user = userService.getUser(id);
return ResponseResult.databaseSelectSuccess(user);
}
@PostMapping
public ResponseResult addUser(@RequestBody User user) {
if (!StringUtils.hasText(user.getUsername())) {
return ResponseResult.build(ResponseCode.DATABASE_SAVE_ERROR, "Username cannot be empty", null);
}
if (!StringUtils.hasText(user.getPasswd())) {
return ResponseResult.build(ResponseCode.DATABASE_SAVE_ERROR, "Password cannot be empty", null);
}
if (userService.addUser(user)) {
return ResponseResult.databaseSaveSuccess(user);
} else {
return ResponseResult.build(ResponseCode.DATABASE_SAVE_ERROR, "error", null);
}
}
@DeleteMapping("/{id}")
public ResponseResult deleteRole(@PathVariable Long id) {
LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(User::getId, id);
if (userService.remove(wrapper)) {
return ResponseResult.databaseDeleteSuccess();
} else {
return ResponseResult.build(ResponseCode.DATABASE_DELETE_ERROR, "error", null);
}
}
@PutMapping()
public ResponseResult modifyRole(@RequestBody User user) {
if (!StringUtils.hasText(user.getUsername())) {
return ResponseResult.build(ResponseCode.DATABASE_UPDATE_ERROR, "Username cannot be empty", null);
}
if (!StringUtils.hasText(user.getPasswd())) {
user.setPasswd(null);
}
if (userService.modifyUser(user)) {
return ResponseResult.databaseUpdateSuccess(user);
} else {
return ResponseResult.build(ResponseCode.DATABASE_UPDATE_ERROR, "error", null);
}
}
}

View File

@@ -2,12 +2,12 @@ package com.cfive.pinnacle.entity;
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.baomidou.mybatisplus.annotation.Version;
import java.io.Serial;
import java.io.Serializable;
import java.util.List;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
@@ -59,9 +59,14 @@ public class User implements Serializable {
@TableField("enable")
private Integer enable;
@TableField(exist = false)
private List<Role> roles;
@TableField(exist = false)
private List<Group> groups;
@TableField("deleted")
@TableLogic
private Integer deleted;
private Long deleted;
@TableField("version")
@Version

View File

@@ -1,6 +1,8 @@
package com.cfive.pinnacle.handler;
import com.cfive.pinnacle.entity.common.ResponseCode;
import com.cfive.pinnacle.entity.common.ResponseResult;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@@ -8,6 +10,9 @@ import org.springframework.web.bind.annotation.RestControllerAdvice;
public class CustomExceptionHandler {
@ExceptionHandler(value = Exception.class)
public ResponseResult exceptionHandler(Exception e) {
if (e instanceof DuplicateKeyException) {
return ResponseResult.build(ResponseCode.DATABASE_SAVE_ERROR, "无法添加重复数据", null);
}
return ResponseResult.fail(e.getClass().toString() + ": " + e.getMessage());
}
}

View File

@@ -3,6 +3,9 @@ package com.cfive.pinnacle.mapper;
import com.cfive.pinnacle.entity.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* <p>
@@ -14,5 +17,7 @@ import org.apache.ibatis.annotations.Mapper;
*/
@Mapper
public interface UserMapper extends BaseMapper<User> {
List<User> getAll();
User getOneById(@Param("id") long id);
}

View File

@@ -14,7 +14,12 @@ import java.util.List;
* @since 2023-04-30
*/
public interface IUserService extends IService<User> {
List<User> getBasicInfo();
User getBasicInfo(int id);
List<User> getAllUser();
User getUser(long id);
boolean addUser(User user);
boolean modifyUser(User user);
}

View File

@@ -1,13 +1,19 @@
package com.cfive.pinnacle.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cfive.pinnacle.entity.User;
import com.cfive.pinnacle.entity.*;
import com.cfive.pinnacle.mapper.UserGroupMapper;
import com.cfive.pinnacle.mapper.UserMapper;
import com.cfive.pinnacle.mapper.UserRoleMapper;
import com.cfive.pinnacle.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.HashSet;
import java.util.List;
/**
@@ -21,28 +27,120 @@ import java.util.List;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
private UserMapper userMapper;
private UserRoleMapper userRoleMapper;
private UserGroupMapper userGroupMapper;
private PasswordEncoder passwordEncoder;
@Autowired
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
@Autowired
public void setUserRoleMapper(UserRoleMapper userRoleMapper) {
this.userRoleMapper = userRoleMapper;
}
@Autowired
public void setUserGroupMapper(UserGroupMapper userGroupMapper) {
this.userGroupMapper = userGroupMapper;
}
@Autowired
public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
@Override
public List<User> getBasicInfo() {
List<User> users = userMapper.selectList(null);
users.forEach(user -> {
user.setPasswd("");
public List<User> getAllUser() {
return userMapper.getAll();
}
@Override
public User getUser(long id) {
return userMapper.getOneById(id);
}
@Override
@Transactional
public boolean addUser(User user) {
String encryptedPassword = passwordEncoder.encode(user.getPasswd());
user.setPasswd(encryptedPassword);
if (userMapper.insert(user) == 1) {
user.getRoles().forEach(role -> {
UserRole userRole = new UserRole();
userRole.setUserId(user.getId());
userRole.setRoleId(role.getId());
if (userRoleMapper.insert(userRole) != 1) {
throw new RuntimeException("Add user_role failure");
}
});
user.getGroups().forEach(group -> {
UserGroup userGroup = new UserGroup();
userGroup.setUserId(user.getId());
userGroup.setGroupId(group.getId());
if (userGroupMapper.insert(userGroup) != 1) {
throw new RuntimeException("Add user_group failure");
}
});
return true;
} else {
throw new RuntimeException("Add group failure");
}
}
@Override
@Transactional
public boolean modifyUser(User user) {
if (StringUtils.hasText(user.getPasswd())) {
String encryptedPassword = passwordEncoder.encode(user.getPasswd());
user.setPasswd(encryptedPassword);
}
userMapper.updateById(user);
User originalUser = getUser(user.getId());
HashSet<Long> newRoleIds = new HashSet<>();
HashSet<Long> newGroupIds = new HashSet<>();
user.getRoles().forEach(role -> newRoleIds.add(role.getId()));
user.getGroups().forEach(group -> newGroupIds.add(group.getId()));
HashSet<Long> addRoleIds = new HashSet<>(newRoleIds);
HashSet<Long> addGroupIds = new HashSet<>(newGroupIds);
if (originalUser != null) {
HashSet<Long> originalRoleIds = new HashSet<>();
HashSet<Long> originalGroupIds = new HashSet<>();
originalUser.getRoles().forEach(role -> originalRoleIds.add(role.getId()));
originalUser.getGroups().forEach(group -> originalGroupIds.add(group.getId()));
HashSet<Long> deleteRoleIds = new HashSet<>(originalRoleIds);
HashSet<Long> deleteGroupIds = new HashSet<>(originalGroupIds);
deleteRoleIds.removeAll(newRoleIds);
deleteGroupIds.removeAll(newGroupIds);
addRoleIds.removeAll(originalRoleIds);
addGroupIds.removeAll(originalGroupIds);
deleteRoleIds.forEach(deleteRoleId -> {
LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(UserRole::getUserId, user.getId())
.eq(UserRole::getRoleId, deleteRoleId);
userRoleMapper.delete(wrapper);
});
deleteGroupIds.forEach(deleteGroupId -> {
LambdaQueryWrapper<UserGroup> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(UserGroup::getUserId, user.getId())
.eq(UserGroup::getGroupId, deleteGroupId);
userGroupMapper.delete(wrapper);
});
}
addRoleIds.forEach(addRoleId -> {
UserRole userRole = new UserRole();
userRole.setUserId(user.getId());
userRole.setRoleId(addRoleId);
userRoleMapper.insert(userRole);
});
addGroupIds.forEach(addGroupId -> {
UserGroup userGroup = new UserGroup();
userGroup.setUserId(user.getId());
userGroup.setGroupId(addGroupId);
userGroupMapper.insert(userGroup);
});
return users;
}
@Override
public User getBasicInfo(int id) {
LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(User::getId, id);
User user = userMapper.selectOne(wrapper);
user.setPasswd("");
return user;
return true;
}
}

View File

@@ -5,6 +5,7 @@ import com.cfive.pinnacle.entity.User;
import com.cfive.pinnacle.entity.permission.LoginUser;
import com.cfive.pinnacle.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
@@ -16,6 +17,7 @@ import java.util.Objects;
public class UserDetailsServiceImpl implements UserDetailsService {
private IUserService userService;
@Lazy
@Autowired
public void setUserService(IUserService userService) {
this.userService = userService;

View File

@@ -14,6 +14,6 @@ mybatis-plus:
db-config:
logic-delete-field: deleted
logic-not-delete-value: 0
logic-delete-value: 1
logic-delete-value: id
id-type: assign_id
type-aliases-package: com.cfive.pinnacle.entity

View File

@@ -2,4 +2,70 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cfive.pinnacle.mapper.UserMapper">
<select id="getAll" resultMap="userMap">
select t_user.id as user_id,
t_user.username as user_username,
t_user.department_id as user_department,
t_user.enable as user_enable,
t_user.deleted as user_deleted,
t_user.version as user_version,
tr.id as role_id,
tr.name as role_name,
tr.deleted as role_deleted,
tr.version as role_version,
tg.id as group_id,
tg.name as group_name,
tg.deleted as group_deleted,
tg.version as group_version
from t_user
left join (select * from t_user_role where deleted = 0) as tur on t_user.id = tur.user_id
left join (select * from t_role where deleted = 0) as tr on tr.id = tur.role_id
left join (select * from t_user_group where deleted = 0) as tug on t_user.id = tug.user_id
left join (select * from t_group where deleted = 0) as tg on tg.id = tug.group_id
where t_user.deleted = 0;
</select>
<select id="getOneById" resultMap="userMap">
select t_user.id as user_id,
t_user.username as user_username,
t_user.department_id as user_department,
t_user.enable as user_enable,
t_user.deleted as user_deleted,
t_user.version as user_version,
tr.id as role_id,
tr.name as role_name,
tr.deleted as role_deleted,
tr.version as role_version,
tg.id as group_id,
tg.name as group_name,
tg.deleted as group_deleted,
tg.version as group_version
from t_user
left join (select * from t_user_role where deleted = 0) as tur on t_user.id = tur.user_id
left join (select * from t_role where deleted = 0) as tr on tr.id = tur.role_id
left join (select * from t_user_group where deleted = 0) as tug on t_user.id = tug.user_id
left join (select * from t_group where deleted = 0) as tg on tg.id = tug.group_id
where t_user.deleted = 0
and t_user.id = #{id};
</select>
<resultMap id="userMap" type="user">
<id property="id" column="user_id"/>
<result property="username" column="user_username"/>
<result property="departmentId" column="user_department"/>
<result property="enable" column="user_enable"/>
<result property="deleted" column="user_deleted"/>
<result property="version" column="user_version"/>
<collection property="roles" ofType="role">
<id property="id" column="role_id"/>
<result property="name" column="role_name"/>
<result property="deleted" column="role_deleted"/>
<result property="version" column="role_version"/>
</collection>
<collection property="groups" ofType="group">
<id property="id" column="group_id"/>
<result property="name" column="group_name"/>
<result property="deleted" column="group_deleted"/>
<result property="version" column="group_version"/>
</collection>
</resultMap>
</mapper>

View File

@@ -97,13 +97,49 @@ VALUES (1656219345971326978, 1, 1655784840189972481),
SET FOREIGN_KEY_CHECKS = 1;
select * from t_role
left join t_power_role tpr on t_role.id = tpr.role_id
left join t_power tp on tp.id = tpr.power_id
left join t_menu tm on tp.id = tm.power_id
left join t_element te on tp.id = te.power_id
left join t_operation t on tp.id = t.power_id;
select *
from t_role
left join t_power_role tpr on t_role.id = tpr.role_id
left join t_power tp on tp.id = tpr.power_id
left join t_menu tm on tp.id = tm.power_id
left join t_element te on tp.id = te.power_id
left join t_operation t on tp.id = t.power_id;
select *
from t_group
left join t_role_group trg on t_group.id = trg.group_id
left join t_role tr on tr.id = trg.role_id;
update t_user
set deleted = id
where id = 1658537970212278274;
select *
from t_user
inner join t_user_role tur on t_user.id = tur.user_id
inner join t_role tr on tr.id = tur.role_id
inner join t_user_group tug on t_user.id = tug.user_id
inner join t_group tg on tg.id = tug.group_id;
select t_user.id as user_id,
t_user.username as user_username,
t_user.department_id as user_department,
t_user.enable as user_enable,
t_user.deleted as user_deleted,
t_user.version as user_version,
tr.id as role_id,
tr.name as role_name,
tr.deleted as role_deleted,
tr.version as role_version,
tg.id as group_id,
tg.name as group_name,
tg.deleted as group_deleted,
tg.version as group_version
from t_user
left join (select * from t_user_role where deleted = 0) as tur on t_user.id = tur.user_id
left join (select * from t_role where deleted = 0) as tr on tr.id = tur.role_id
left join (select * from t_user_group where deleted = 0) as tug on t_user.id = tug.user_id
left join (select * from t_group where deleted = 0) as tg on tg.id = tug.group_id
where t_user.deleted = 0;
select * from t_group
left join t_role_group trg on t_group.id = trg.group_id
left join t_role tr on tr.id = trg.role_id

View File

@@ -84,7 +84,7 @@ create table `t_department`
`name` varchar(50) not null comment '部门名',
`tel` varchar(20) null comment '部门电话',
`address` varchar(20) null comment '部门地址',
`deleted` int not null default 0,
`deleted` bigint not null default 0,
`version` int not null default 0
) comment '部门';
@@ -95,16 +95,17 @@ create table `t_user`
`passwd` char(70) not null comment '密码',
`department_id` bigint null comment '部门',
`enable` int not null comment '启用',
`deleted` int not null default 0,
`deleted` bigint not null default 0,
`version` int not null default 0,
constraint t_user_department_id_fk foreign key (department_id) references t_department (id)
constraint t_user_department_id_fk foreign key (department_id) references t_department (id),
constraint t_user_unique unique (username, deleted)
) comment '用户';
create table `t_group`
(
`id` bigint not null primary key,
`name` varchar(30) not null comment '用户组名',
`deleted` int not null default 0,
`deleted` bigint not null default 0,
`version` int not null default 0
) comment '用户组';
@@ -113,7 +114,7 @@ create table `t_user_group`
`id` bigint not null primary key,
`user_id` bigint not null comment '用户',
`group_id` bigint not null comment '用户组',
`deleted` int not null default 0,
`deleted` bigint not null default 0,
`version` int not null default 0,
constraint t_user_group_user_id_fk foreign key (user_id) references t_user (id),
constraint t_user_group_group_id_fk foreign key (group_id) references t_group (id)
@@ -123,7 +124,7 @@ create table `t_role`
(
`id` bigint not null primary key,
`name` varchar(20) not null comment '角色名',
`deleted` int not null default 0,
`deleted` bigint not null default 0,
`version` int not null default 0
) comment '角色';
@@ -132,7 +133,7 @@ create table `t_role_group`
`id` bigint not null primary key,
`role_id` bigint not null comment '角色',
`group_id` bigint not null comment '群组',
`deleted` int not null default 0,
`deleted` bigint not null default 0,
`version` int not null default 0,
constraint t_role_group_role_id_fk foreign key (role_id) references t_role (id),
constraint t_role_group_group_id_fk foreign key (group_id) references t_group (id)
@@ -143,7 +144,7 @@ create table `t_user_role`
`id` bigint not null primary key,
`user_id` bigint not null comment '用户',
`role_id` bigint not null comment '角色',
`deleted` int not null default 0,
`deleted` bigint not null default 0,
`version` int not null default 0,
constraint t_user_role_user_id_fk foreign key (user_id) references t_user (id),
constraint t_user_role_role_id_fk foreign key (role_id) references t_role (id)
@@ -154,7 +155,7 @@ create table `t_power_role`
`id` bigint not null primary key,
`power_id` bigint not null comment '权限',
`role_id` bigint not null comment '角色',
`deleted` int not null default 0,
`deleted` bigint not null default 0,
`version` int not null default 0,
constraint t_power_role_power_id_fk foreign key (power_id) references t_power (id),
constraint t_power_role_role_id_fk foreign key (role_id) references t_role (id)
@@ -167,7 +168,7 @@ create table `t_operation_log`
`operation_id` bigint not null comment '功能',
`content` varchar(500) not null comment '操作内容',
`operating_time` datetime not null default (utc_timestamp()) comment '操作时间',
`deleted` int not null default 0,
`deleted` bigint not null default 0,
`version` int not null default 0,
constraint t_operation_log_user_id_fk foreign key (user_id) references t_user (id),
constraint t_operation_log_operation_id_fk foreign key (operation_id) references t_operation (id)
@@ -184,7 +185,7 @@ create table `t_staff`
`email` varchar(50) null comment '邮箱',
`tel` varchar(20) null comment '电话',
`address` varchar(50) null comment '地址',
`deleted` int not null default 0,
`deleted` bigint not null default 0,
`version` int not null default 0,
constraint t_staff_user_id_fk foreign key (user_id) references t_user (id)
) comment '员工';
@@ -194,7 +195,7 @@ create table `t_notice_type`
`id` bigint not null primary key,
`name` varchar(20) not null comment '公告类型名',
`enable` int not null default 1 comment '启用',
`deleted` int not null default 0,
`deleted` bigint not null default 0,
`version` int not null default 0
) comment '公告类型';
@@ -213,7 +214,7 @@ create table `t_notice`
`modify_time` datetime not null default (utc_timestamp()) comment '修改时间',
`origin_id` bigint null comment '源ID',
`old` int not null default 0 comment '已修改',
`deleted` int not null default 0,
`deleted` bigint not null default 0,
`version` int not null default 0,
constraint t_notice_type_id_fk foreign key (type_id) references t_notice_type (id),
constraint t_notice_sender_id_fk foreign key (sender_id) references t_user (id)
@@ -225,7 +226,7 @@ create table `t_notice_receive`
`user_id` bigint not null comment '用户',
`notice_id` bigint not null comment '公告',
`already_read` int not null default 0 comment '已读',
`deleted` int not null default 0,
`deleted` bigint not null default 0,
`version` int not null default 0,
constraint t_notice_receive_user_id_fk foreign key (user_id) references t_user (id),
constraint t_notice_receive_notice_if_fk foreign key (notice_id) references t_notice (id)
@@ -241,7 +242,7 @@ create table `t_work`
`modify_time` datetime not null default (utc_timestamp()) comment '修改时间',
`old` int not null default 0 comment '已修改',
`origin_id` bigint null comment '源ID',
`deleted` int not null default 0,
`deleted` bigint not null default 0,
`version` int not null default 0,
constraint t_work_publisher_id_fk foreign key (publisher_id) references t_user (id)
) comment '工作事项';
@@ -252,7 +253,7 @@ create table `t_user_work`
`user_id` bigint not null comment '用户',
`work_id` bigint not null comment '工作事项',
`status` int not null default 0 comment '工作状态',
`deleted` int not null default 0,
`deleted` bigint not null default 0,
`version` int not null default 0,
constraint t_user_work_user_id_fk foreign key (user_id) references t_user (id),
constraint t_user_work_work_id_fk foreign key (work_id) references t_work (id)
@@ -263,7 +264,7 @@ create table `t_affair_type`
`id` bigint not null primary key,
`name` varchar(20) not null comment '事务类型名',
`enable` int not null default 1 comment '启用',
`deleted` int not null default 0,
`deleted` bigint not null default 0,
`version` int not null default 0
) comment '事务类型';
@@ -282,7 +283,7 @@ create table `t_affair`
`modify_time` datetime default (utc_timestamp()) comment '修改时间',
`origin_id` bigint null comment '源ID',
`old` int not null default 0 comment '已修改',
`deleted` int not null default 0,
`deleted` bigint not null default 0,
`version` int not null default 0,
constraint t_affair_type_id_fk foreign key (type_id) references t_affair_type (id),
constraint t_affair_applicant_id_fk foreign key (applicant_id) references t_user (id),
@@ -297,7 +298,7 @@ create table `t_attendance`
`status` int not null default 0 comment '考勤状态',
`modify_id` bigint not null comment '修改人',
`modify_time` datetime not null default (utc_timestamp()) comment '修改时间',
`deleted` int not null default 0,
`deleted` bigint not null default 0,
`version` int not null default 0,
constraint t_attendance_user_id_fk foreign key (user_id) references t_user (id),
constraint t_attendance_modify_id_fk foreign key (modify_id) references t_user (id)

View File

@@ -0,0 +1,324 @@
<template>
<el-button bg style="background-color: white" :loading="tableLoading" @click="loadUserTable">
<template #icon>
<el-icon>
<icon-pinnacle-refresh />
</el-icon>
</template>
</el-button>
<el-button type="primary" @click="handleAddBtn">
<template #icon>
<el-icon>
<icon-pinnacle-plus />
</el-icon>
</template>
<template #default> 添加 </template>
</el-button>
<common-table
:table-date="userTable"
:table-loading="tableLoading"
@onEdit="handleEdit"
@onDelete="handleDelete"
custom-column-label_1="角色"
custom-column-label_2="用户组"
/>
<el-dialog
:title="dialogTitle"
:close-on-click-modal="false"
draggable
v-model="dialogVisible"
@open="handleDialogOpen"
>
<template #default>
<el-form
label-width="100px"
v-loading="dialogLoading"
:rules="rules"
ref="formRef"
:model="userForm"
>
<el-form-item label="用户名" prop="inputUsername">
<el-input
autocomplete="off"
v-model="userForm.inputUsername"
placeholder="请输入用户名"
/>
</el-form-item>
<el-form-item label="密码" prop="inputPassword" :required="isAddNew">
<el-input
show-password
autocomplete="off"
v-model="userForm.inputPassword"
:placeholder="isAddNew ? '请输入密码' : '留空则不修改密码'"
/>
</el-form-item>
<el-form-item label="角色">
<el-select v-model="userForm.selectedRoles" multiple style="width: 100%">
<el-option
v-for="role in roles"
:key="role.id"
:label="role.name"
:value="role.id"
/>
</el-select>
</el-form-item>
<el-form-item label="用户组">
<el-select v-model="userForm.selectedGroups" multiple style="width: 100%">
<el-option
v-for="group in groups"
:key="group.id"
:label="group.name"
:value="group.id"
/>
</el-select>
</el-form-item>
</el-form>
</template>
<template #footer>
<el-button type="primary" @click="handleSubmit" :disabled="dialogLoading"
>提交</el-button
>
<el-button @click="handleCancel">取消</el-button>
</template>
</el-dialog>
</template>
<script lang="ts">
import request from '@/services/index.js'
import {
DATABASE_DELETE_OK,
DATABASE_SAVE_OK,
DATABASE_SELECT_OK,
DATABASE_UPDATE_OK
} from '@/constants/Common.constants.js'
import { ElMessage, ElMessageBox } from 'element-plus'
export default {
name: 'UserManagement',
data() {
const checkPassword = (rule, value, callback) => {
if (this.isAddNew && !value) {
return callback(new Error('密码不能为空'))
} else {
return callback()
}
}
return {
dialogVisible: false,
tableLoading: true,
dialogLoading: true,
userTable: [],
roles: [],
groups: [],
userForm: {
inputUsername: '',
inputPassword: '',
selectedRoles: [],
selectedGroups: []
},
isAddNew: true,
dialogTitle: '',
editUserId: '',
rules: {
inputUsername: [
{
required: true,
message: '用户名不能为空'
}
],
inputPassword: [
{
validator: checkPassword,
message: '密码不能为空'
}
]
}
}
},
methods: {
loadUserTable() {
this.tableLoading = true
request.get('/user').then((res) => {
const response = res.data
if (response.code === DATABASE_SELECT_OK) {
const users = response.data
for (const user of users) {
user.name = user.username
user.customColumn_1 = []
user.customColumn_2 = []
const roles = user.roles
for (const role of roles) {
user.customColumn_1.push(role.name)
}
const groups = user.groups
for (const group of groups) {
user.customColumn_2.push(group.name)
}
}
this.userTable = users
this.tableLoading = false
} else {
ElMessage.error({
dangerouslyUseHTMLString: true,
message: '<strong>查询出错</strong>: ' + response.msg
})
}
})
},
handleAddBtn() {
this.isAddNew = true
this.dialogVisible = true
},
getRoles() {
this.dialogLoading = true
request.get('/role').then((res) => {
const response = res.data
if (response.code === DATABASE_SELECT_OK) {
this.roles = response.data
this.getGroups()
} else {
ElMessage.error({
dangerouslyUseHTMLString: true,
message: '<strong>查询出错</strong>: ' + response.msg
})
}
})
},
getGroups() {
request.get('/group').then((res) => {
const response = res.data
if (response.code === DATABASE_SELECT_OK) {
this.groups = response.data
this.dialogLoading = false
} else {
ElMessage.error({
dangerouslyUseHTMLString: true,
message: '<strong>查询出错</strong>: ' + response.msg
})
}
})
},
handleEdit(index, row) {
this.userForm.inputUsername = row.name
this.userForm.inputPassword = ''
this.editUserId = row.id
this.userForm.selectedRoles = []
this.userForm.selectedGroups = []
for (const role of row.roles) {
this.userForm.selectedRoles.push(role.id)
}
for (const group of row.groups) {
this.userForm.selectedGroups.push(group.id)
}
this.isAddNew = false
this.dialogVisible = true
},
handleDelete(index, row) {
ElMessageBox.confirm('确定删除该用户吗?', '删除').then(() => {
this.tableLoading = true
request.delete('/user/' + row.id).then((res) => {
const response = res.data
if (response.code === DATABASE_DELETE_OK) {
ElMessage.success({
dangerouslyUseHTMLString: true,
message: '<strong>删除成功</strong>'
})
this.loadUserTable()
} else {
ElMessage.error({
dangerouslyUseHTMLString: true,
message: '<strong>删除失败</strong>: ' + response.msg
})
this.tableLoading = false
}
})
})
},
handleDialogOpen() {
this.getRoles()
if (this.isAddNew) {
this.userForm.inputUsername = ''
this.userForm.inputPassword = ''
this.userForm.selectedRoles = []
this.userForm.selectedGroups = []
this.dialogTitle = '添加用户'
} else {
this.dialogTitle = '编辑用户'
}
},
async handleSubmit() {
await this.$refs.formRef.validate((valid) => {
if (valid) {
this.dialogLoading = true
const userObject = {
id: '',
username: this.userForm.inputUsername,
passwd: this.userForm.inputPassword,
roles: [],
groups: []
}
for (const roleId of this.userForm.selectedRoles) {
const role = {
id: roleId
}
userObject.roles.push(role)
}
for (const groupId of this.userForm.selectedGroups) {
const group = {
id: groupId
}
userObject.groups.push(group)
}
if (this.isAddNew) {
request.post('/user', userObject).then((res) => {
const response = res.data
if (response.code === DATABASE_SAVE_OK) {
ElMessage.success({
dangerouslyUseHTMLString: true,
message: '<strong>添加成功</strong>'
})
this.dialogVisible = false
this.loadUserTable()
} else {
ElMessage.error({
dangerouslyUseHTMLString: true,
message: '<strong>添加失败</strong>: ' + response.msg
})
this.dialogLoading = false
}
})
} else {
userObject.id = this.editUserId
request.put('/user', userObject).then((res) => {
const response = res.data
if (response.code === DATABASE_UPDATE_OK) {
ElMessage.success({
dangerouslyUseHTMLString: true,
message: '<strong>修改成功</strong>'
})
this.dialogVisible = false
this.loadUserTable()
} else {
ElMessage.error({
dangerouslyUseHTMLString: true,
message: '<strong>修改失败</strong>: ' + response.msg
})
this.dialogLoading = false
}
})
}
}
})
},
handleCancel() {
this.dialogVisible = false
}
},
mounted() {
this.loadUserTable()
}
}
</script>
<style scoped></style>

View File

@@ -1,6 +1,7 @@
const powerRouter = {
path: '/power',
name: 'systemManagement',
redirect: '/power/role',
children: [
{
path: 'role',
@@ -21,6 +22,16 @@ const powerRouter = {
requiresScrollbar: false,
requiresPadding: true
}
},
{
path: 'user',
name: 'userManagement',
component: async () => await import('@/pages/power/UserManagement.vue'),
meta: {
title: '用户管理',
requiresScrollbar: false,
requiresPadding: true
}
}
],
meta: {