refactor: 用户导入和用户新增修改的方法优化

This commit is contained in:
郝先瑞 2022-04-13 00:01:13 +08:00
parent cf23c1281f
commit cae34fd833
10 changed files with 159 additions and 96 deletions

View File

@ -1,18 +1,18 @@
package com.youlai.admin.controller;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.youlai.admin.dto.AuthUserDTO;
import com.youlai.admin.pojo.entity.SysUser;
import com.youlai.admin.pojo.form.UserForm;
import com.youlai.admin.pojo.form.UserImportForm;
import com.youlai.admin.pojo.query.UserPageQuery;
import com.youlai.admin.pojo.vo.user.LoginUserVO;
import com.youlai.admin.pojo.vo.user.UserDetailVO;
import com.youlai.admin.pojo.vo.user.UserExportVO;
import com.youlai.admin.pojo.vo.user.UserFormVO;
import com.youlai.admin.pojo.vo.user.UserPageVO;
import com.youlai.admin.service.ISysPermissionService;
import com.youlai.admin.service.ISysUserService;
@ -25,7 +25,6 @@ import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
@ -48,9 +47,10 @@ import java.util.stream.Collectors;
@RequestMapping("/api/v1/users")
@RequiredArgsConstructor
public class UserController {
private final ISysUserService iSysUserService;
private final PasswordEncoder passwordEncoder;
private final ISysPermissionService iSysPermissionService;
private final PasswordEncoder passwordEncoder;
@ApiOperation(value = "用户分页列表")
@GetMapping("/page")
@ -61,19 +61,19 @@ public class UserController {
return PageResult.success(result);
}
@ApiOperation(value = "获取用户表单详情")
@GetMapping("/{userId}/form_detail")
public Result<UserFormVO> getUserDetail(
@ApiParam(value = "用户ID", example = "1") @PathVariable Long userId
@ApiOperation(value = "获取用户详情")
@GetMapping("/{userId}")
public Result<UserDetailVO> getUserDetail(
@ApiParam(value = "用户ID") @PathVariable Long userId
) {
UserFormVO userDetail = iSysUserService.getUserFormDetail(userId);
UserDetailVO userDetail = iSysUserService.getUserDetail(userId);
return Result.success(userDetail);
}
@ApiOperation(value = "新增用户")
@PostMapping
public Result addUser(@RequestBody SysUser user) {
boolean result = iSysUserService.saveUser(user);
public Result addUser(@RequestBody UserForm userForm) {
boolean result = iSysUserService.saveUser(userForm);
return Result.judge(result);
}
@ -81,9 +81,9 @@ public class UserController {
@PutMapping(value = "/{userId}")
public Result updateUser(
@ApiParam("用户ID") @PathVariable Long userId,
@RequestBody SysUser user
@RequestBody UserForm userForm
) {
boolean result = iSysUserService.updateUser(user);
boolean result = iSysUserService.updateUser(userId, userForm);
return Result.judge(result);
}
@ -96,7 +96,7 @@ public class UserController {
return Result.judge(status);
}
@ApiOperation(value = "选择性更新用户")
@ApiOperation(value = "选择性修改用户")
@PatchMapping(value = "/{userId}")
public Result updateUserPart(
@ApiParam("用户ID") @PathVariable Long userId,
@ -145,7 +145,7 @@ public class UserController {
public void downloadTemplate(HttpServletResponse response) throws IOException {
String fileName = "用户导入模板.xlsx";
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName,"UTF-8"));
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
String fileClassPath = "excel-templates" + File.separator + fileName;
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileClassPath);
@ -158,15 +158,9 @@ public class UserController {
@ApiOperation("导入用户")
@PostMapping("/_import")
public Result importUsers(@RequestBody UserImportForm userImportForm, MultipartFile file) throws IOException {
InputStream inputStream = file.getInputStream();
String errMsg = iSysUserService.importUsers(inputStream, userImportForm);
if (StrUtil.isNotBlank(errMsg)) {
return Result.failed(errMsg);
}
return Result.success();
public Result importUsers(UserImportForm userImportForm) throws IOException {
String msg = iSysUserService.importUsers(userImportForm);
return Result.success(msg);
}
@ApiOperation("导出用户")
@ -174,7 +168,7 @@ public class UserController {
public void exportUsers(UserPageQuery queryParams, HttpServletResponse response) throws IOException {
String fileName = "用户列表.xlsx";
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName,"UTF-8"));
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
List<UserExportVO> exportUserList = iSysUserService.listExportUsers(queryParams);

View File

@ -6,11 +6,10 @@ import com.youlai.admin.dto.AuthUserDTO;
import com.youlai.admin.pojo.entity.SysUser;
import com.youlai.admin.pojo.query.UserPageQuery;
import com.youlai.admin.pojo.vo.user.UserExportVO;
import com.youlai.admin.pojo.vo.user.UserFormVO;
import com.youlai.admin.pojo.vo.user.UserDetailVO;
import com.youlai.admin.pojo.vo.user.UserPageVO;
import com.youlai.common.mybatis.annotation.DataPermission;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@ -39,7 +38,7 @@ public interface SysUserMapper extends BaseMapper<SysUser> {
* @param userId 用户ID
* @return
*/
UserFormVO getUserFormDetail(Long userId);
UserDetailVO getUserDetail(Long userId);
/**
* 根据用户名获取认证信息

View File

@ -1,10 +1,12 @@
package com.youlai.admin.pojo.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.experimental.Accessors;
@Data
@Accessors(chain = true)
@AllArgsConstructor
public class SysUserRole {
private Long userId;

View File

@ -0,0 +1,42 @@
package com.youlai.admin.pojo.form;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.List;
/**
* 用户表单对象
*
* @author <a href="mailto:xianrui0365@163.com">haoxr</a>
* @date 2022/4/12 11:04
*/
@Data
public class UserForm {
private Long id;
private String username;
private String nickname;
private String mobile;
private Integer gender;
private String avatar;
private String password;
private String email;
private Integer status;
private Long deptId;
private List<Long> roleIds;
}

View File

@ -1,8 +1,10 @@
package com.youlai.admin.pojo.form;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.apache.catalina.User;
import lombok.NoArgsConstructor;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
@ -23,7 +25,10 @@ public class UserImportForm {
/**
* 角色ID
*/
private Long roleId;
private String roleIds;
private MultipartFile file;
/**
* 导入的用户列表
@ -31,7 +36,10 @@ public class UserImportForm {
private List<UserItem> userList;
@Data
public class UserItem {
@NoArgsConstructor
@AllArgsConstructor
public static class UserItem {
@ExcelProperty(value = "用户名")
private String username;
@ -39,7 +47,7 @@ public class UserImportForm {
private String nickname;
@ExcelProperty(value = "性别")
private String genderLabel;
private String gender;
@ExcelProperty(value = "手机号码")
private String mobile;

View File

@ -7,14 +7,14 @@ import lombok.Data;
import java.util.List;
/**
* 用户表单视图对象
* 用户详情视图对象
*
* @author haoxr
* @date 2022/1/14
*/
@ApiModel("用户表单视图对象")
@ApiModel("用户详情视图对象")
@Data
public class UserFormVO {
public class UserDetailVO {
@ApiModelProperty("用户ID")
private Long id;

View File

@ -5,13 +5,14 @@ import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.youlai.admin.dto.AuthUserDTO;
import com.youlai.admin.pojo.entity.SysUser;
import com.youlai.admin.pojo.form.UserForm;
import com.youlai.admin.pojo.form.UserImportForm;
import com.youlai.admin.pojo.query.UserPageQuery;
import com.youlai.admin.pojo.vo.user.UserDetailVO;
import com.youlai.admin.pojo.vo.user.UserExportVO;
import com.youlai.admin.pojo.vo.user.UserFormVO;
import com.youlai.admin.pojo.vo.user.UserPageVO;
import java.io.InputStream;
import java.io.IOException;
import java.util.List;
/**
@ -32,18 +33,19 @@ public interface ISysUserService extends IService<SysUser> {
/**
* 新增用户
*
* @param user
* @param userForm 用户表单对象
* @return
*/
boolean saveUser(SysUser user);
boolean saveUser(UserForm userForm);
/**
* 修改用户
*
* @param user
* @param userId 用户ID
* @param userForm 用户表单对象
* @return
*/
boolean updateUser(SysUser user);
boolean updateUser(Long userId,UserForm userForm);
/**
* 根据用户名获取认证信息
@ -59,15 +61,15 @@ public interface ISysUserService extends IService<SysUser> {
* @param userId
* @return
*/
UserFormVO getUserFormDetail(Long userId);
UserDetailVO getUserDetail(Long userId);
/**
* 导入用户
*
* @param inputStream
* @param userImportForm
* @return
*/
String importUsers(InputStream inputStream, UserImportForm userImportForm);
String importUsers( UserImportForm userImportForm) throws IOException;
/**
* 获取导出用户列表

View File

@ -1,6 +1,8 @@
package com.youlai.admin.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
@ -14,26 +16,29 @@ import com.youlai.admin.common.constant.SystemConstants;
import com.youlai.admin.common.enums.GenderEnum;
import com.youlai.admin.component.listener.excel.UserImportListener;
import com.youlai.admin.dto.AuthUserDTO;
import com.youlai.admin.pojo.entity.SysUser;
import com.youlai.admin.mapper.SysUserMapper;
import com.youlai.admin.pojo.entity.SysUser;
import com.youlai.admin.pojo.entity.SysUserRole;
import com.youlai.admin.pojo.form.UserForm;
import com.youlai.admin.pojo.form.UserImportForm;
import com.youlai.admin.pojo.query.UserPageQuery;
import com.youlai.admin.pojo.vo.user.UserDetailVO;
import com.youlai.admin.pojo.vo.user.UserExportVO;
import com.youlai.admin.pojo.vo.user.UserFormVO;
import com.youlai.admin.pojo.vo.user.UserPageVO;
import com.youlai.admin.service.ISysUserRoleService;
import com.youlai.admin.service.ISysUserService;
import com.youlai.common.base.IBaseEnum;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
@ -67,19 +72,25 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
/**
* 新增用户
*
* @param user
* @param userForm 用户表单对象
* @return
*/
@Override
public boolean saveUser(SysUser user) {
user.setPassword(passwordEncoder.encode(SystemConstants.DEFAULT_USER_PASSWORD));
public boolean saveUser(UserForm userForm) {
SysUser user = new SysUser();
user.setPassword(passwordEncoder.encode(SystemConstants.DEFAULT_USER_PASSWORD)); // 初始化默认密码
BeanUtil.copyProperties(userForm, user);
boolean result = this.save(user);
if (result) {
Long userId = user.getId();
List<Long> roleIds = user.getRoleIds();
if (CollectionUtil.isNotEmpty(roleIds)) {
List<SysUserRole> userRoleList = new ArrayList<>();
roleIds.forEach(roleId -> userRoleList.add(new SysUserRole().setUserId(user.getId()).setRoleId(roleId)));
result = iSysUserRoleService.saveBatch(userRoleList);
List<SysUserRole> sysUserRoles = Optional.ofNullable(roleIds).orElse(new ArrayList<>())
.stream().map(roleId -> new SysUserRole(userId, roleId))
.collect(Collectors.toList());
if (CollectionUtil.isNotEmpty(sysUserRoles)) {
iSysUserRoleService.saveBatch(sysUserRoles);
}
}
return result;
@ -88,41 +99,46 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
/**
* 更新用户
*
* @param user
* @param userId 用户ID
* @param userForm 用户表单对象
* @return
*/
@Override
public boolean updateUser(SysUser user) {
@Transactional
public boolean updateUser(Long userId, UserForm userForm) {
SysUser user = this.getById(userId);
Assert.isTrue(user != null, "用户不存在或已被删除");
// 用户的旧的角色ID集合
// 用户旧角色ID集合
List<Long> oldRoleIds = iSysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>()
.eq(SysUserRole::getUserId, user.getId())).stream()
.eq(SysUserRole::getUserId, userId))
.stream()
.map(item -> item.getRoleId())
.collect(Collectors.toList());
// 用户角色ID集合
List<Long> newRoleIds = user.getRoleIds();
// 用户新角色ID集合
List<Long> newRoleIds = userForm.getRoleIds();
// 需要新增的用户角色ID集合
// 新增的用户角色
List<Long> addRoleIds = newRoleIds.stream().filter(roleId -> !oldRoleIds.contains(roleId)).collect(Collectors.toList());
if (CollectionUtil.isNotEmpty(addRoleIds)) {
List<SysUserRole> addUserRoleList = new ArrayList<>();
addRoleIds.forEach(roleId -> {
addUserRoleList.add(new SysUserRole().setUserId(user.getId()).setRoleId(roleId));
});
iSysUserRoleService.saveBatch(addUserRoleList);
}
List<SysUserRole> addUserRoles = Optional.ofNullable(addRoleIds).orElse(new ArrayList<>())
.stream().map(roleId -> new SysUserRole(userId, roleId))
.collect(Collectors.toList());
iSysUserRoleService.saveBatch(addUserRoles);
// 需要删除的用户角色ID集合
// 删除的用户角色
List<Long> removeRoleIds = oldRoleIds.stream().filter(roleId -> !newRoleIds.contains(roleId)).collect(Collectors.toList());
if (CollectionUtil.isNotEmpty(removeRoleIds)) {
removeRoleIds.forEach(roleId -> {
iSysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, user.getId()).eq(SysUserRole::getRoleId, roleId));
});
iSysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>()
.eq(SysUserRole::getUserId, userId)
.in(SysUserRole::getRoleId, removeRoleIds)
);
}
// 最后更新用户
return this.updateById(user);
BeanUtil.copyProperties(userForm, user);
boolean updateRes = this.updateById(user);
return updateRes;
}
/**
@ -144,8 +160,8 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
* @return
*/
@Override
public UserFormVO getUserFormDetail(Long userId) {
UserFormVO userDetail = this.baseMapper.getUserFormDetail(userId);
public UserDetailVO getUserDetail(Long userId) {
UserDetailVO userDetail = this.baseMapper.getUserDetail(userId);
return userDetail;
}
@ -153,16 +169,16 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
/**
* 导入用户
*
* @param inputStream
* @param userImportForm
* @return
*/
@SneakyThrows
@Override
@Transactional
public String importUsers(InputStream inputStream, UserImportForm userImportForm) {
public String importUsers(UserImportForm userImportForm) throws IOException {
Long deptId = userImportForm.getDeptId();
Long roleId = userImportForm.getRoleId();
List<Long> roleIds = Arrays.stream(userImportForm.getRoleIds().split(",")).map(roleId -> Convert.toLong(roleId)).collect(Collectors.toList());
InputStream inputStream = userImportForm.getFile().getInputStream();
ExcelReaderBuilder excelReaderBuilder = EasyExcel.read(inputStream, UserImportForm.UserItem.class, userImportListener);
ExcelReaderSheetBuilder sheet = excelReaderBuilder.sheet();
@ -211,7 +227,7 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
// 默认密码
user.setPassword(passwordEncoder.encode(SystemConstants.DEFAULT_USER_PASSWORD));
// 性别转换
Integer gender = (Integer) IBaseEnum.getValueByLabel(userItem.getGenderLabel(), GenderEnum.class);
Integer gender = (Integer) IBaseEnum.getValueByLabel(userItem.getGender(), GenderEnum.class);
user.setGender(gender);
saveUserList.add(user);
@ -221,12 +237,18 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
boolean result = this.saveBatch(saveUserList);
Assert.isTrue(result, "导入数据失败,原因:保存用户出错");
List<SysUserRole> userRoleList = saveUserList.stream().map(user -> {
SysUserRole userRole = new SysUserRole();
userRole.setUserId(user.getId());
userRole.setRoleId(roleId);
return userRole;
}).collect(Collectors.toList());
List<SysUserRole> userRoleList = new ArrayList<>();
if (CollectionUtil.isNotEmpty(roleIds)) {
roleIds.forEach(roleId -> {
userRoleList.addAll(
saveUserList.stream()
.map(user -> new SysUserRole(user.getId(), roleId)).
collect(Collectors.toList()));
});
}
iSysUserRoleService.saveBatch(userRoleList);
}

View File

@ -44,7 +44,7 @@
</select>
<!-- 用户表单信息映射 -->
<resultMap id="UserFormMap" type="com.youlai.admin.pojo.vo.user.UserFormVO">
<resultMap id="UserFormMap" type="com.youlai.admin.pojo.vo.user.UserDetailVO">
<id property="id" column="id" jdbcType="BIGINT"/>
<result property="username" column="username" jdbcType="VARCHAR"/>
<result property="nickname" column="nickname" jdbcType="VARCHAR"/>
@ -63,7 +63,7 @@
</resultMap>
<!-- 根据用户ID获取用户详情 -->
<select id="getUserFormDetail" resultMap="UserFormMap">
<select id="getUserDetail" resultMap="UserFormMap">
SELECT id,
username,
nickname,

View File

@ -19,11 +19,5 @@ class SysUserServiceImplTest {
@Test
public void saveUser() {
SysUser user=new SysUser();
user.setUsername("root");
user.setNickname("有来技术");
user.setMobile("17621590365");
user.setEmail("youlaitech@163.com");
iSysUserService.saveUser(user);
}
}