All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.javaclub.base.service.impl.AdminUserServiceImpl Maven / Gradle / Ivy

/* Automatic generated by CrudCodeGenerator wirtten by Gerald Chen
 *
 * @(#)AdminUserServiceImpl.java	 2023-09-06
 *
 * Copyright (c) 2023 - 2099. All Rights Reserved.
 *
 */

package com.github.javaclub.base.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.javaclub.Constants.EnableStatus;
import com.github.javaclub.Constants.SepChars;
import com.github.javaclub.base.domain.AdminUser;
import com.github.javaclub.base.domain.SysMenu;
import com.github.javaclub.base.domain.query.AdminUserQuery;
import com.github.javaclub.base.mapper.AdminUserMapper;
import com.github.javaclub.base.mapper.UserRoleMapper;
import com.github.javaclub.base.service.AdminUserService;
import com.github.javaclub.base.service.SysMenuService;
import com.github.javaclub.base.utils.ConfigUtils;
import com.github.javaclub.base.utils.SecurityUtils;
import com.github.javaclub.sword.BizException;
import com.github.javaclub.sword.core.BizObjects;
import com.github.javaclub.sword.core.Collections;
import com.github.javaclub.sword.core.Numbers;
import com.github.javaclub.sword.core.Strings;
import com.github.javaclub.sword.domain.QueryResult;
import com.github.javaclub.sword.domain.ResultDO;
import com.github.javaclub.sword.domain.enumtype.BasicMessage;
import com.google.common.collect.Lists;

import lombok.AllArgsConstructor;

/**
 * AdminUserService 业务逻辑实现
 *
 * @version $Id: AdminUserServiceImpl.java 2023-09-06 19:11:12 Exp $
 */
@Service
@AllArgsConstructor
public class AdminUserServiceImpl extends ServiceImpl implements AdminUserService {
	
	private final AdminUserMapper adminUserMapper;
	private final UserRoleMapper userRoleMapper;
	
	private final SysMenuService sysMenuService;

	/**
	 * 创建时的业务校验
	 * 
	 * @param adminUser 业务实体
	 */
	void doCreateCheck(AdminUser adminUser) {
	    BizObjects.requireNotNull(adminUser, "DB实体不能为空");
		// TODO Auto-generated method stub
		
	}
	
	/**
	 * 更新时的业务校验
	 * 
	 * @param adminUser 业务实体
	 */
	AdminUser doUpdateCheck(AdminUser adminUser) {
		BizObjects.requireNotNull(adminUser, "DB实体不能为空");
		BizObjects.requireNotNullGtZero(adminUser.getId(), "主键ID不能为空");
		// TODO Auto-generated method stub
		
		return null;
	}

	@Override
	public ResultDO saveEntity(AdminUser adminUser) {
		try {
			if (null == adminUser.getId()) {
				Long id = create(adminUser);
				if (Numbers.isPositiveNumber(id)) {
					return ResultDO.success(true);
				}
			}
			AdminUser db = adminUserMapper.selectById(adminUser.getId());
			if (null == db) {
				return ResultDO.failure(BasicMessage.NOT_FOUND);
			}
			boolean suc = update(adminUser);
			if (suc) {
				return ResultDO.success(true);
			}
		} catch (BizException e) {
			return ResultDO.failure(e.getMessage(), e.getCode());
		} catch (Exception e) {
			return ResultDO.failure("数据库执行失败!", BasicMessage.EXCEPTIONED.getCode());
		}
		return ResultDO.failure();
	}

	@Override
	public Long create(AdminUser adminUser) {
		this.doCreateCheck(adminUser);
		int num = adminUserMapper.insert(adminUser);
		if (0 >= num) {
			throw new BizException(BasicMessage.DB_INSERT_FAILED.getCode(), "创建记录失败!");
		}
		return adminUser.getId();
	}
	
	@Override
	public boolean update(AdminUser adminUser) {
		this.doUpdateCheck(adminUser);
		int num = adminUserMapper.updateById(adminUser);
		return num > 0;
	}

	@Override
	public AdminUser selectById(Long id) {
		return adminUserMapper.selectByUserId(id);
	}
	
	@Override
	public AdminUser selectOne(AdminUserQuery query) {
		QueryWrapper qw = query.queryWrapper();
		List list = adminUserMapper.selectList(qw);
		if(null != list && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public int count(AdminUserQuery query) {
		Integer count = adminUserMapper.selectCount(query.queryWrapper());
		return null != count ? count.intValue() : 0;
	}

	@Override
	public List findList(AdminUserQuery query) {
		QueryWrapper qw = query.queryWrapper();
		return adminUserMapper.selectList(qw);
	}

	@Override
	public QueryResult findListWithCount(AdminUserQuery query) {
		QueryResult queryResult = new QueryResult();
		
		QueryWrapper qw = query.queryWrapper();
		Page page = new Page<>(query.getPageNo(), query.getPageSize());
		IPage pageResult = adminUserMapper.selectPage(page, qw);
		
		if (null != pageResult) {
			queryResult.setTotalCount(pageResult.getTotal());
			queryResult.setEntry(pageResult.getRecords());
			queryResult.setSuccess(true);
		}
		return queryResult;
	}
	
	@Override
	public AdminUser selectByEmail(String email) {
		return adminUserMapper.selectByEmail(email);
	}

	@Override
	public AdminUser selectByUsername(String username) {
		return adminUserMapper.selectByUsername(username);
	}

	@Override
	public AdminUser selectByMobile(String mobile) {
		return adminUserMapper.selectByMobile(mobile);
	}
	

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveUserAndUserRole(AdminUser user) {
		AdminUser loginUser = SecurityUtils.getAdminUser();
		Long creatorId = loginUser.getId();
		user.setCreatorId(creatorId);
		adminUserMapper.insert(user);
		if (Collections.isEmpty(user.getRoleIdList())) {
			return ;
		}
		// 保存用户与角色关系
		userRoleMapper.insertUserAndUserRole(user.getId(), creatorId, user.getRoleIdList());
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateUserAndUserRole(AdminUser user) {
		// 更新用户
		adminUserMapper.updateById(user);

		//先删除用户与角色关系
		userRoleMapper.deleteByUserId(user.getId());
		if (Collections.isEmpty(user.getRoleIdList())) {
			return ;
		}
		Long creatorId = 0L; // TODO
		// 保存用户与角色关系
		userRoleMapper.insertUserAndUserRole(user.getId(), creatorId, user.getRoleIdList());
	}

	@Override
	public void updatePasswordByUserId(Long userId, String newPassword) {
		AdminUser user = new AdminUser();
        user.setPassword(newPassword);
        user.setId(userId);
        adminUserMapper.updateById(user);
    }
	

	@Override
	public List queryAllPerms(Long userId) {
		return adminUserMapper.queryAllPerms(userId);
	}

	
	@Override
	public AdminUser checkUserLogin(String account, String password) {
		String encodePwd = ConfigUtils.generatePasswordMD5(password);
		if (Strings.isMobile(account)) {
			AdminUser user = this.selectByMobile(account);
			if (null != user && Strings.equals(encodePwd, user.getPassword())) {
				user.setPassword(null);
				return user;
			}
		} else if (Strings.isEmail(account)) {
			AdminUser user = this.selectByEmail(account);
			if (null != user && Strings.equals(encodePwd, user.getPassword())) {
				user.setPassword(null);
				return user;
			}
		}
		AdminUser user = this.selectByUsername(account);
		BizObjects.requireNotNull(user, "登录失败, 账号或密码不正确!");
		BizObjects.requireTrue(Strings.equals(encodePwd, user.getPassword()), "登录失败, 账号或密码不正确!");
	       
		if (Objects.equals(EnableStatus.DISABLED, user.getStatus())) {
            throw new BizException(BasicMessage.UN_NORMAL_USER.getCode(), "账号已不可用, 请联系系统管理员!");
        }
        if (Objects.equals(2, user.getStatus())) {
            throw new BizException(BasicMessage.IN_ACTIVED_USER.getCode(), "账号尚未激活, 请联系系统管理员!");
        }
        user.setPermissions(getUserPermissions(user.getId()));
        user.setPassword(null);
		return user;
	}

	List getUserPermissions(Long userId) {
        List permsList;
        if (Numbers.isIn(userId, "0,1")) {
            List menuList = sysMenuService.list(Wrappers.emptyWrapper());
            permsList = menuList.stream().map(SysMenu::getPerms).collect(Collectors.toList());
        } else {
            permsList = this.queryAllPerms(userId);
        }
        if (Collections.isEmpty(permsList)) {
        		return Lists.newArrayList();
        }
        
        Set set = permsList.stream().flatMap((perms) -> {
            if (Strings.isBlank(perms)) {
                return null;
            }
            return Arrays.stream(perms.trim().split(SepChars.COMMA));
        }).collect(Collectors.toSet());
        
        List target = Lists.newArrayList(set);
        java.util.Collections.sort(target);
        return target;
    }

	@Override
	public boolean updateUserStatus(AdminUser entity) {
		BizObjects.requireTrue(Numbers.isIn(entity.getStatus(), "0,1"), "用户状态参数错误!");
		AdminUser db = BizObjects.requireNotNull(this.selectById(entity.getId()), "用户不存在!");
		db.setStatus(entity.getStatus());
		return adminUserMapper.updateById(db) > 0;
	}
	
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy