基于JavaEE的通用超市结算系统的设计与实现

作者主页:编程千纸鹤

作者简介:Java、前端、Python开发多年,做过高程,项目经理,架构师

主要内容:Java项目开发、Python项目开发、大学数据和AI项目开发、单片机项目设计、面试技术整理、最新技术分享

收藏点赞不迷路  关注作者有好处

文末获得源码

 项目编号:BS-XX-160

一,环境介绍

语言环境:Java:  jdk1.8

数据库:Mysql: mysql5.7

应用服务器:Tomcat:  tomcat8.5.31

开发工具:IDEA或eclipse

开发技术:Springboot+Vue

二,项目简介

【项目简介】

在这个互联网发展迅速的时代,生活中我们离不开的除了手机就是超市了,不只是大型连锁超市这种适合全家出动的商超,更是说小区转角马路对面,总会出现的小型超市,经济不断发展的同时,我们的消费能力也在不断地提升,越来越多的超市出现在了我们的日常生活中,给我们提供了更多的可选性,然而对于超市本身来说,他们需要对商品、数据等进行管理来提升自身在行业中的竞争力,但是对于经营成本的提升甚至是流量红利的消退以及现在很多门店市场定位的雷同,如何对现状进行一些缓解呢,能看的出来大部分的小超市都非常需要一套能够满足商品管理对数据进行维护的收银系统。21 世纪我国的超市产业飞速发展,其经营模式更为复杂,旧的管理体制已经无法适应超市的发展,这就迫切的需要引进新的管理技术。此系统的实现节省了大量的人力、物力,改善了员工的并且能够快速反映出商品的进、销、存等状況和各种反馈信息分析,使管理人员快速对市场的变化做出相应的决策,加快超市经营管理效率。

【技术架构】

基于JavaEE的通用超市结算系统使用IntelliJ IDEA 2019.2.3作为后端开发工具及Visual Studio Code为前端开发工具;以Vue作为开发技术,vue是单页面应用,使页面局部刷新,不用每次跳转页面都要请求所有数据和DOM,这样大大加快了访问速度和提升用户体验。MySQL数据库作为系统数据库,其使用的SQL语言是用于访问数据库的最常用的标准化语言,支持多种操作系统,提供用于管理、检查、优化数据库操作的管理工具;系统采用Java作为开发语言,服务端架构采用Springboot技术,Springboot能够快速构建项目,并且可独立运行,无须外部依赖Servlet容器,极大的提高了开发、部署效率。通过这些技术构建系统,可以很好得对系统的功能进行完善及系统后期的维护。

【功能模块】

1.系统登录模块:在软件首页可以选择以管理员或收银员两种身份登录,在选定对应身份后即可输入账号密码进入系统。

管理员身份登录:

2.商品管理模块:可查询进货情况,添加进货需求,对超市库存,商品种类及商品数量等进行增删改查,并可对商品进行价格更改。

3.会员管理模块:可对超市会员名单进行查询,并增删超市会员名单,会员可对会员卡进行充值,会员可享受超市消费的折扣福利。

4.员工管理模块:可对超市收银员进行信息修改,增删员工名单。并记录员工登录退出系统的准确时间,避免员工迟到早退。

5.营业额查询模块:可对近期超市营业情况进行查询,随时掌握超市商品销售情况,并以此判断进货方向。查询统计的基础上添加图形报表进行商品销售统计展示。

收银员身份登录:

6.收银模块:当顾客选择手机支付时,扫描二维码付款(支付宝沙箱),当顾客使用会员卡支付时,可刷卡或于收银台内输入会员卡卡号及会员留存手机号,收银员直接对会员卡内余额进行扣款。

三,系统展示

用户管理

部门管理

文件管理

角色权限管理

商品管理

供应商管理

四,核心代码展示

package cn.zwz.data.controller;

import cn.zwz.basics.baseVo.Result;
import cn.zwz.basics.parameter.SettingConstant;
import cn.zwz.basics.utils.ResultUtil;
import cn.zwz.data.entity.Setting;
import cn.zwz.data.service.ISettingService;
import cn.zwz.data.vo.*;
import cn.hutool.core.util.StrUtil;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 设置
 * @author znz
 */
@RestController
@Api(tags = "设置接口")
@RequestMapping("/zwz/setting")
public class SettingController {

    @Autowired
    private ISettingService iSettingService;

    @RequestMapping(value = "/seeSecret/{settingName}", method = RequestMethod.GET)
    @ApiOperation(value = "查看私密配置")
    public Result<Object> seeSecret(@PathVariable String settingName) {
        String result = "";
        Setting setting = iSettingService.getById(settingName);
        if(setting==null||StrUtil.isBlank(setting.getValue())){
            return ResultUtil.error("配置不存在");
        }
        if(settingName.equals(SettingConstant.ALI_SMS)){
            result = new Gson().fromJson(setting.getValue(), SmsSetting.class).getSecretKey();
        } else if(settingName.equals(SettingConstant.VAPTCHA_SETTING)){
            result = new Gson().fromJson(setting.getValue(), VaptchaSetting.class).getSecretKey();
        }
        return ResultUtil.data(result);
    }

    @RequestMapping(value = "/oss/check", method = RequestMethod.GET)
    @ApiOperation(value = "检查OSS配置")
    public Result<Object> osscheck() {
        Setting setting = iSettingService.getById(SettingConstant.OSS_USED);
        if(setting==null||StrUtil.isBlank(setting.getValue())){
            return ResultUtil.error(501, "您还未配置第三方OSS服务");
        }
        return ResultUtil.data(setting.getValue());
    }

    @RequestMapping(value = "/oss/{serviceName}", method = RequestMethod.GET)
    @ApiOperation(value = "查看OSS配置")
    public Result<OssSetting> oss(@PathVariable String serviceName) {
        Setting setting = new Setting();
        if(serviceName.equals(SettingConstant.QINIU_OSS)||serviceName.equals(SettingConstant.ALI_OSS)
                ||serviceName.equals(SettingConstant.TENCENT_OSS)||serviceName.equals(SettingConstant.MINIO_OSS)
                ||serviceName.equals(SettingConstant.LOCAL_OSS)){
            setting = iSettingService.getById(serviceName);
        }
        if(setting==null||StrUtil.isBlank(setting.getValue())){
            return new ResultUtil<OssSetting>().setData(null);
        }
        OssSetting ossSetting = new Gson().fromJson(setting.getValue(), OssSetting.class);
        return new ResultUtil<OssSetting>().setData(ossSetting);
    }

    @RequestMapping(value = "/sms/{serviceName}", method = RequestMethod.GET)
    @ApiOperation(value = "查看短信配置")
    public Result<SmsSetting> sms(@PathVariable String serviceName) {
        Setting setting = new Setting();
        if(serviceName.equals(SettingConstant.ALI_SMS)){
            setting = iSettingService.getById(SettingConstant.ALI_SMS);
        }
        if(setting==null||StrUtil.isBlank(setting.getValue())){
            return new ResultUtil<SmsSetting>().setData(null);
        }
        SmsSetting smsSetting = new Gson().fromJson(setting.getValue(), SmsSetting.class);
        smsSetting.setSecretKey("**********");
        if(smsSetting.getType()!=null){
            Setting code = new Setting();
            smsSetting.setTemplateCode(code.getValue());
        }
        return new ResultUtil<SmsSetting>().setData(smsSetting);
    }

    @RequestMapping(value = "/sms/templateCode/{type}", method = RequestMethod.GET)
    @ApiOperation(value = "查看短信模板配置")
    public Result<String> smsTemplateCode(@PathVariable Integer type) {
        String templateCode = "";
        if(type!=null){
            String template = "CommonUtil.getSmsTemplate(type)";
            Setting setting = iSettingService.getById(template);
            if(StrUtil.isNotBlank(setting.getValue())){
                templateCode = setting.getValue();
            }
        }
        return new ResultUtil<String>().setData(templateCode);
    }

    @RequestMapping(value = "/vaptcha", method = RequestMethod.GET)
    @ApiOperation(value = "查看vaptcha配置")
    public Result<VaptchaSetting> vaptcha() {
        Setting setting = iSettingService.getById(SettingConstant.VAPTCHA_SETTING);
        if(setting==null||StrUtil.isBlank(setting.getValue())){
            return new ResultUtil<VaptchaSetting>().setData(null);
        }
        VaptchaSetting vaptchaSetting = new Gson().fromJson(setting.getValue(), VaptchaSetting.class);
        vaptchaSetting.setSecretKey("**********");
        return new ResultUtil<VaptchaSetting>().setData(vaptchaSetting);
    }

    @RequestMapping(value = "/other", method = RequestMethod.GET)
    @ApiOperation(value = "查看其他配置")
    public Result<HttpIpSsoSetting> other() {
        Setting setting = iSettingService.getById(SettingConstant.OTHER_SETTING);
        if(setting==null||StrUtil.isBlank(setting.getValue())){
            return new ResultUtil<HttpIpSsoSetting>().setData(null);
        }
        HttpIpSsoSetting otherSetting = new Gson().fromJson(setting.getValue(), HttpIpSsoSetting.class);
        return new ResultUtil<HttpIpSsoSetting>().setData(otherSetting);
    }

    @RequestMapping(value = "/notice", method = RequestMethod.GET)
    @ApiOperation(value = "查看公告配置")
    public Result<NoticeSetting> notice() {
        Setting setting = iSettingService.getById(SettingConstant.NOTICE_SETTING);
        if(setting==null||StrUtil.isBlank(setting.getValue())){
            return new ResultUtil<NoticeSetting>().setData(null);
        }
        NoticeSetting noticeSetting = new Gson().fromJson(setting.getValue(), NoticeSetting.class);
        return new ResultUtil<NoticeSetting>().setData(noticeSetting);
    }

    @RequestMapping(value = "/oss/set", method = RequestMethod.POST)
    @ApiOperation(value = "OSS配置")
    public Result<Object> ossSet(OssSetting ossSetting) {
        String name = ossSetting.getServiceName();
        Setting setting = iSettingService.getById(name);
        setting.setValue(new Gson().toJson(ossSetting));
        iSettingService.saveOrUpdate(setting);
        Setting used = iSettingService.getById(SettingConstant.OSS_USED);
        used.setValue(name);
        iSettingService.saveOrUpdate(used);
        return ResultUtil.data(null);
    }

    @RequestMapping(value = "/sms/set", method = RequestMethod.POST)
    @ApiOperation(value = "短信配置")
    public Result<Object> smsSet(SmsSetting smsSetting) {
        if(smsSetting.getServiceName().equals(SettingConstant.ALI_SMS)){
            // 阿里
            Setting setting = iSettingService.getById(SettingConstant.ALI_SMS);
            if(StrUtil.isNotBlank(setting.getValue())&&!smsSetting.getChanged()){
                String secrectKey = new Gson().fromJson(setting.getValue(), SmsSetting.class).getSecretKey();
                smsSetting.setSecretKey(secrectKey);
            }
            if(smsSetting.getType()!=null){
                Setting codeSetting = new Setting();
                codeSetting.setValue(smsSetting.getTemplateCode());
                iSettingService.saveOrUpdate(codeSetting);
            }
            smsSetting.setType(null);
            smsSetting.setTemplateCode(null);
            setting.setValue(new Gson().toJson(smsSetting));
            iSettingService.saveOrUpdate(setting);

            Setting used = iSettingService.getById(SettingConstant.SMS_USED);
            used.setValue(SettingConstant.ALI_SMS);
            iSettingService.saveOrUpdate(used);
        }
        return ResultUtil.data();
    }

    @RequestMapping(value = "/vaptcha/set", method = RequestMethod.POST)
    @ApiOperation(value = "vaptcha配置")
    public Result<Object> vaptchaSet(VaptchaSetting vaptchaSetting) {
        Setting setting = iSettingService.getById(SettingConstant.VAPTCHA_SETTING);
        if(StrUtil.isNotBlank(setting.getValue())&&!vaptchaSetting.getChanged()){
            String key = new Gson().fromJson(setting.getValue(), VaptchaSetting.class).getSecretKey();
            vaptchaSetting.setSecretKey(key);
        }
        setting.setValue(new Gson().toJson(vaptchaSetting));
        iSettingService.saveOrUpdate(setting);
        return ResultUtil.data();
    }

    @RequestMapping(value = "/other/set", method = RequestMethod.POST)
    @ApiOperation(value = "其他配置")
    public Result<Object> otherSet(HttpIpSsoSetting otherSetting) {
        Setting setting = iSettingService.getById(SettingConstant.OTHER_SETTING);
        setting.setValue(new Gson().toJson(otherSetting));
        iSettingService.saveOrUpdate(setting);
        return ResultUtil.data();
    }

    @RequestMapping(value = "/notice/set", method = RequestMethod.POST)
    @ApiOperation(value = "其他配置")
    public Result<Object> noticeSet(NoticeSetting noticeSetting) {
        Setting setting = iSettingService.getById(SettingConstant.NOTICE_SETTING);
        setting.setValue(new Gson().toJson(noticeSetting));
        iSettingService.saveOrUpdate(setting);
        return ResultUtil.data();
    }
}
package cn.zwz.data.controller;

import cn.zwz.basics.log.SystemLog;
import cn.zwz.basics.redis.RedisTemplateHelper;
import cn.zwz.basics.utils.*;
import cn.zwz.basics.security.SecurityUserDetails;
import cn.zwz.basics.parameter.CommonConstant;
import cn.zwz.basics.log.LogType;
import cn.zwz.basics.exception.ZwzException;
import cn.zwz.basics.baseVo.PageVo;
import cn.zwz.basics.baseVo.Result;
import cn.zwz.data.entity.*;
import cn.zwz.data.service.*;
import cn.zwz.data.utils.ZwzNullUtils;
import cn.zwz.data.vo.PermissionDTO;
import cn.zwz.data.vo.RoleDTO;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户
 * @author znz
 */
@RestController
@Api(tags = "用户接口")
@RequestMapping("/zwz/user")
@CacheConfig(cacheNames = "user")
@Transactional
public class UserController {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IDepartmentService iDepartmentService;

    @Autowired
    private IRoleService iRoleService;

    @Autowired
    private IUserRoleService iUserRoleService;

    @Autowired
    private IDepartmentHeaderService iDepartmentHeaderService;

    @Autowired
    private IRolePermissionService iRolePermissionService;

    @Autowired
    private RedisTemplateHelper redisTemplateHelper;

    @Autowired
    private IPermissionService iPermissionService;

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private SecurityUtil securityUtil;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ApiOperation(value = "获取当前登录用户接口")
    public Result<User> getUserInfo(){
        User u = securityUtil.getCurrUser();
        entityManager.clear();
        u.setPassword(null);
        return new ResultUtil<User>().setData(u);
    }

    @RequestMapping(value = "/resetByMobile", method = RequestMethod.POST)
    @ApiOperation(value = "短信重置密码")
    public Result<Object> resetByMobile(@RequestParam String mobile, @RequestParam String password, @RequestParam String passStrength){
        QueryWrapper<User> userQw = new QueryWrapper<>();
        userQw.eq("mobile",mobile);
        User user = iUserService.getOne(userQw);
        String encryptPass = new BCryptPasswordEncoder().encode(password);
        user.setPassword(encryptPass).setPassStrength(passStrength);
        iUserService.saveOrUpdate(user);
        redisTemplate.delete("user::"+user.getUsername());
        return ResultUtil.success();
    }

    @RequestMapping(value = "/regist", method = RequestMethod.POST)
    @ApiOperation(value = "注册用户")
    public Result<Object> regist(@Valid User u){
        u.setEmail(u.getMobile() + "@qq.com");
        checkUserInfo(u.getUsername(), u.getMobile(), u.getEmail());
        String encryptPass = new BCryptPasswordEncoder().encode(u.getPassword());
        u.setPassword(encryptPass).setType(0);
        iUserService.saveOrUpdate(u);
        QueryWrapper<Role> roleQw = new QueryWrapper<>();
        roleQw.eq("default_role",true);
        List<Role> roleList = iRoleService.list(roleQw);
        if(roleList.size() > 0){
            for(Role role : roleList) {
                iUserRoleService.saveOrUpdate(new UserRole().setUserId(u.getId()).setRoleId(role.getId()));
            }
        }
        return ResultUtil.data(u);
    }

    @RequestMapping(value = "/smsLogin", method = RequestMethod.POST)
    @SystemLog(about = "短信登录", type = LogType.USER_LOGIN)
    @ApiOperation(value = "短信登录接口")
    public Result<Object> smsLogin(@RequestParam String mobile, @RequestParam(required = false) Boolean saveLogin){
        QueryWrapper<User> userQw = new QueryWrapper<>();
        userQw.eq("mobile",mobile);
        User user = iUserService.getOne(userQw);
        if(user==null){
            throw new ZwzException("手机号不存在");
        }
        String accessToken = securityUtil.getToken(user.getUsername(), saveLogin);
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(new SecurityUserDetails(user), null, null);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        return ResultUtil.data(accessToken);
    }

    @RequestMapping(value = "/changeMobile", method = RequestMethod.POST)
    @ApiOperation(value = "修改绑定手机")
    public Result<Object> changeMobile(@RequestParam String mobile){
        User u = securityUtil.getCurrUser();
        u.setMobile(mobile);
        iUserService.saveOrUpdate(u);
        redisTemplate.delete("user::"+u.getUsername());
        return ResultUtil.success();
    }

    @RequestMapping(value = "/unlock", method = RequestMethod.POST)
    @ApiOperation(value = "解锁验证密码")
    public Result<Object> unLock(@RequestParam String password){
        User u = securityUtil.getCurrUser();
        if(!new BCryptPasswordEncoder().matches(password, u.getPassword())){
            return ResultUtil.error("密码不正确");
        }
        return ResultUtil.data(null);
    }

    @RequestMapping(value = "/resetPass", method = RequestMethod.POST)
    @ApiOperation(value = "重置密码")
    public Result<Object> resetPass(@RequestParam String[] ids){
        for(String id:ids){
            User u = iUserService.getById(id);
            u.setPassword(new BCryptPasswordEncoder().encode("123456"));
            iUserService.saveOrUpdate(u);
            redisTemplate.delete("user::"+u.getUsername());
        }
        return ResultUtil.success();
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ApiOperation(value = "修改用户自己资料",notes = "用户名密码不会修改 需要username更新缓存")
    @CacheEvict(key = "#u.username")
    public Result<Object> editOwn(User u){
        User old = securityUtil.getCurrUser();
        u.setUsername(old.getUsername());
        u.setPassword(old.getPassword());
        iUserService.saveOrUpdate(u);
        return ResultUtil.success("修改成功");
    }

    @RequestMapping(value = "/modifyPass", method = RequestMethod.POST)
    @ApiOperation(value = "修改密码")
    public Result<Object> modifyPass(@RequestParam String password,@RequestParam String newPass,@RequestParam String passStrength){
        User user = securityUtil.getCurrUser();
        if(!new BCryptPasswordEncoder().matches(password, user.getPassword())){
            return ResultUtil.error("原密码不正确");
        }
        String newEncryptPass= new BCryptPasswordEncoder().encode(newPass);
        user.setPassword(newEncryptPass);
        user.setPassStrength(passStrength);
        iUserService.saveOrUpdate(user);
        redisTemplate.delete("user::"+user.getUsername());
        return ResultUtil.success();
    }

    @RequestMapping(value = "/getByCondition", method = RequestMethod.GET)
    @ApiOperation(value = "查询用户")
    public Result<IPage<User>> getByCondition(@ModelAttribute User user, @ModelAttribute PageVo page) {
        QueryWrapper<User> userQw = new QueryWrapper<>();
        if(!ZwzNullUtils.isNull(user.getUsername())) {
            userQw.like("username",user.getUsername());
        }
        if(!ZwzNullUtils.isNull(user.getNickname())) {
            userQw.like("nickname",user.getNickname());
        }
        if(!ZwzNullUtils.isNull(user.getMobile())) {
            userQw.like("mobile",user.getMobile());
        }
        if(!ZwzNullUtils.isNull(user.getDepartmentId())) {
            userQw.eq("department_id",user.getDepartmentId());
        }
        if(user.getType() != null) {
            userQw.eq("type",user.getType());
        }
        if(user.getStatus() != null) {
            userQw.eq("status",user.getStatus());
        }
        if(!ZwzNullUtils.isNull(user.getSex())) {
            userQw.eq("sex",user.getSex());
        }
        IPage<User> userData = iUserService.page(PageUtil.initMpPage(page),userQw);
        for(User u: userData.getRecords()) {
            List<Role> list = iUserRoleService.findByUserId(u.getId());
            List<RoleDTO> roleDTOList = list.stream().map(e->{
                return new RoleDTO().setId(e.getId()).setName(e.getName()).setDescription(e.getDescription());
            }).collect(Collectors.toList());
            u.setRoles(roleDTOList);
            entityManager.detach(u);
            u.setPassword(null);
        }
        return new ResultUtil<IPage<User>>().setData(userData);
    }

    @RequestMapping(value = "/getByDepartmentId/{departmentId}", method = RequestMethod.GET)
    @ApiOperation(value = "根据部门查询用户")
    public Result<List<User>> getByCondition(@PathVariable String departmentId){
        QueryWrapper<User> userQw = new QueryWrapper<>();
        userQw.eq("department_id", departmentId);
        List<User> list = iUserService.list(userQw);
        entityManager.clear();
        list.forEach(u -> {
            u.setPassword(null);
        });
        return new ResultUtil<List<User>>().setData(list);
    }

    @RequestMapping(value = "/searchByName/{username}", method = RequestMethod.GET)
    @ApiOperation(value = "模拟搜索用户姓名")
    public Result<List<User>> searchByName(@PathVariable String username) throws UnsupportedEncodingException {
        QueryWrapper<User> userQw = new QueryWrapper<>();
        userQw.eq("username", URLDecoder.decode(username, "utf-8"));
        userQw.eq("status", 0);
        List<User> list = iUserService.list(userQw);
        entityManager.clear();
        list.forEach(u -> {
            u.setPassword(null);
        });
        return new ResultUtil<List<User>>().setData(list);
    }

    @RequestMapping(value = "/getAll", method = RequestMethod.GET)
    @ApiOperation(value = "获取全部用户数据")
    public Result<List<User>> getByCondition(){
        List<User> userList = iUserService.list();
        for(User user: userList){
            entityManager.clear();
            user.setPassword(null);
        }
        return new ResultUtil<List<User>>().setData(userList);
    }

    @RequestMapping(value = "/admin/edit", method = RequestMethod.POST)
    @ApiOperation(value = "管理员修改资料")
    @CacheEvict(key = "#u.username")
    public Result<Object> edit(User u,@RequestParam(required = false) String[] roleIds){
        User old = iUserService.getById(u.getId());
        u.setUsername(old.getUsername());
        if(!old.getMobile().equals(u.getMobile()) && findByMobile(u.getMobile())!=null){
            return ResultUtil.error("手机号重复");
        }
        if(!old.getEmail().equals(u.getEmail()) && findByEmail(u.getEmail())!=null){
            return ResultUtil.error("邮箱重复");
        }
        if(StrUtil.isNotBlank(u.getDepartmentId())){
            Department d = iDepartmentService.getById(u.getDepartmentId());
            if(d != null) {
                u.setDepartmentTitle(d.getTitle());
            }
        }else{
            u.setDepartmentId(null);
            u.setDepartmentTitle("");
        }
        u.setPassword(old.getPassword());
        iUserService.saveOrUpdate(u);
        QueryWrapper<UserRole> urQw = new QueryWrapper<>();
        urQw.eq("user_id",u.getId());
        iUserRoleService.remove(urQw);
        if(roleIds != null){
            List<UserRole> userRoles = Arrays.asList(roleIds).stream().map(e -> {
                return new UserRole().setRoleId(e).setUserId(u.getId());
            }).collect(Collectors.toList());
            iUserRoleService.saveOrUpdateBatch(userRoles);
        }
        redisTemplate.delete("userRole::"+u.getId());
        redisTemplate.delete("userRole::depIds:"+u.getId());
        redisTemplate.delete("permission::userMenuList:"+u.getId());
        return ResultUtil.success();
    }

    @RequestMapping(value = "/admin/add", method = RequestMethod.POST)
    @ApiOperation(value = "添加用户")
    public Result<Object> add(@Valid User u,@RequestParam(required = false) String[] roleIds) {
        checkUserInfo(u.getUsername(), u.getMobile(), u.getEmail());
        String encryptPass = new BCryptPasswordEncoder().encode(u.getPassword());
        u.setPassword(encryptPass);
        if(StrUtil.isNotBlank(u.getDepartmentId())){
            Department d = iDepartmentService.getById(u.getDepartmentId());
            if(d!=null){
                u.setDepartmentTitle(d.getTitle());
            }
        }else{
            u.setDepartmentId(null);
            u.setDepartmentTitle("");
        }
        iUserService.saveOrUpdate(u);
        if(roleIds != null) {
            List<UserRole> userRoles = Arrays.asList(roleIds).stream().map(e -> {
                return new UserRole().setUserId(u.getId()).setRoleId(e);
            }).collect(Collectors.toList());
            iUserRoleService.saveOrUpdateBatch(userRoles);
        }
        return ResultUtil.success();
    }

    @ApiOperation(value = "根据账号查询用户")
    private User findByUsername(String username) {
        QueryWrapper<User> userQw = new QueryWrapper<>();
        userQw.eq("username",username);
        return userToDTO(iUserService.getOne(userQw));
    }

    @ApiOperation(value = "根据手机号查询用户")
    private User findByMobile(String mobile) {
        QueryWrapper<User> userQw = new QueryWrapper<>();
        userQw.eq("mobile",mobile);
        return userToDTO(iUserService.getOne(userQw));
    }

    @ApiOperation(value = "根据邮箱查询用户")
    private User findByEmail(String email) {
        QueryWrapper<User> userQw = new QueryWrapper<>();
        userQw.eq("email",email);
        return userToDTO(iUserService.getOne(userQw));
    }

    @RequestMapping(value = "/admin/disable/{userId}", method = RequestMethod.POST)
    @ApiOperation(value = "禁用用户")
    public Result<Object> disable( @PathVariable String userId){
        User user = iUserService.getById(userId);
        if(user == null){
            return ResultUtil.error("用户已被删除");
        }
        user.setStatus(CommonConstant.USER_STATUS_LOCK);
        iUserService.saveOrUpdate(user);
        redisTemplate.delete("user::"+user.getUsername());
        return ResultUtil.success();
    }

    @RequestMapping(value = "/admin/enable/{userId}", method = RequestMethod.POST)
    @ApiOperation(value = "启用用户")
    public Result<Object> enable(@PathVariable String userId){
        User user = iUserService.getById(userId);
        if(user==null){
            return ResultUtil.error("用户已被删除");
        }
        user.setStatus(CommonConstant.USER_STATUS_NORMAL);
        iUserService.saveOrUpdate(user);
        redisTemplate.delete("user::"+user.getUsername());
        return ResultUtil.success();
    }

    @RequestMapping(value = "/delByIds", method = RequestMethod.POST)
    @ApiOperation(value = "删除用户")
    public Result<Object> delByIds(@RequestParam String[] ids) {
        for(String id:ids){
            User u = iUserService.getById(id);
            redisTemplate.delete("user::" + u.getUsername());
            redisTemplate.delete("userRole::" + u.getId());
            redisTemplate.delete("userRole::depIds:" + u.getId());
            redisTemplate.delete("permission::userMenuList:" + u.getId());
            Set<String> keys = redisTemplateHelper.keys("department::*");
            redisTemplate.delete(keys);
            iUserService.removeById(id);
            QueryWrapper<UserRole> urQw = new QueryWrapper<>();
            urQw.eq("user_id",id);
            iUserRoleService.remove(urQw);
            QueryWrapper<DepartmentHeader> dhQw = new QueryWrapper<>();
            dhQw.eq("user_id",id);
            iDepartmentHeaderService.remove(dhQw);
        }
        return ResultUtil.success();
    }

    @RequestMapping(value = "/importData", method = RequestMethod.POST)
    @ApiOperation(value = "导入用户")
    public Result<Object> importData(@RequestBody List<User> users){
        List<Integer> errors = new ArrayList<>();
        List<String> reasons = new ArrayList<>();
        int count = 0;
        for(User u: users){
            count++;
            if(StrUtil.isBlank(u.getUsername())||StrUtil.isBlank(u.getPassword())){
                errors.add(count);
                reasons.add("账号密码为空");
                continue;
            }
            if(findByUsername(u.getUsername())!=null){
                errors.add(count);
                reasons.add("用户名已存在");
                continue;
            }
            u.setPassword(new BCryptPasswordEncoder().encode(u.getPassword()));
            if(StrUtil.isNotBlank(u.getDepartmentId())){
                Department department = iDepartmentService.getById(u.getDepartmentId());
                if(department == null) {
                    errors.add(count);
                    reasons.add("部门不存在");
                    continue;
                }
            }
            if(u.getStatus()==null){
                u.setStatus(CommonConstant.USER_STATUS_NORMAL);
            }
            iUserService.saveOrUpdate(u);
            if(u.getDefaultRole() != null && u.getDefaultRole()==1) {
                QueryWrapper<Role> roleQw = new QueryWrapper<>();
                roleQw.eq("default_role",true);
                List<Role> roleList = iRoleService.list(roleQw);
                if(roleList!=null&&roleList.size()>0){
                    for(Role role : roleList){
                        UserRole ur = new UserRole().setUserId(u.getId()).setRoleId(role.getId());
                        iUserRoleService.saveOrUpdate(ur);
                    }
                }
            }
        }
        int successCount = users.size() - errors.size();
        String successMessage = "成功导入 " + successCount + " 位用户";
        String failMessage = "成功导入 " + successCount + " 位用户,失败 " + errors.size() + " 位用户。<br>" +"第 " + errors.toString() + " 行数据导入出错,错误原因是为 <br>" + reasons.toString();
        String message = null;
        if(errors.size() == 0){
            message = successMessage;
        }else{
            message = failMessage;
        }
        return ResultUtil.success(message);
    }

    @ApiOperation(value = "校验")
    public void checkUserInfo(String username, String mobile, String email){
        CommonUtil.stopwords(username);
        if(StrUtil.isNotBlank(username) && findByUsername(username)!=null){
            throw new ZwzException("账户重复");
        }
        if(StrUtil.isNotBlank(email) && findByEmail(email)!=null){
            throw new ZwzException("邮箱重复");
        }
        if(StrUtil.isNotBlank(mobile) && findByMobile(mobile)!=null){
            throw new ZwzException("手机号重复");
        }
    }

    @ApiOperation(value = "添加用户的角色和菜单信息")
    public User userToDTO(User user) {
        if(user == null) {
            return null;
        }
        // 角色
        QueryWrapper<UserRole> urQw = new QueryWrapper<>();
        urQw.eq("user_id", user.getId());
        List<UserRole> roleList = iUserRoleService.list(urQw);
        List<RoleDTO> roleDTOList = new ArrayList<>();
        for (UserRole userRole : roleList) {
            Role role = iRoleService.getById(userRole.getRoleId());
            if(role != null) {
                roleDTOList.add(new RoleDTO().setId(role.getId()).setName(role.getName()));
            }
        }
        user.setRoles(roleDTOList);
        // 菜单
        List<String> permissionIdList = new ArrayList<>();
        for (RoleDTO dto : roleDTOList) {
            QueryWrapper<RolePermission> rpQw = new QueryWrapper<>();
            rpQw.eq("role_id",dto.getId());
            List<RolePermission> list = iRolePermissionService.list(rpQw);
            for (RolePermission rp : list) {
                boolean flag = true;
                for (String id : permissionIdList) {
                    if(Objects.equals(id,rp.getPermissionId())) {
                        flag = false;
                        break;
                    }
                }
                if(flag) {
                    permissionIdList.add(rp.getPermissionId());
                }
            }
        }
        List<PermissionDTO> permissionDTOList = new ArrayList<>();
        for (String id : permissionIdList) {
            Permission permission = iPermissionService.getById(id);
            if(permission != null) {
                if(Objects.equals(permission.getType(),CommonConstant.PERMISSION_OPERATION)) {
                    continue;
                }
                permissionDTOList.add(new PermissionDTO().setTitle(permission.getTitle()).setPath(permission.getPath()));
            }
        }
        user.setPermissions(permissionDTOList);
        return user;
    }
}

五,相关作品展示

基于Java开发、Python开发、PHP开发、C#开发等相关语言开发的实战项目

基于Nodejs、Vue等前端技术开发的前端实战项目

基于微信小程序和安卓APP应用开发的相关作品

基于51单片机等嵌入式物联网开发应用

基于各类算法实现的AI智能应用

基于大数据实现的各类数据管理和推荐系统

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程千纸鹤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值