Sfoglia il codice sorgente

!18 数据权限基础
Merge pull request !18 from yangzhengze/master

yangzhengze 6 anni fa
parent
commit
2401c5552e

+ 11 - 1
sql/ry_20180723.sql

@@ -576,4 +576,14 @@ create table sys_notice (
 -- 初始化-公告信息表数据
 -- ----------------------------
 insert into sys_notice values('1', '温馨提醒:2018-07-01 若依新版本发布啦', '2', '新版本内容', '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '管理员');
-insert into sys_notice values('2', '维护通知:2018-07-01 若依系统凌晨维护', '1', '维护内容',   '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '管理员');
+insert into sys_notice values('2', '维护通知:2018-07-01 若依系统凌晨维护', '1', '维护内容',   '0', 'admin', '2018-03-16 11-33-00', 'ry', '2018-03-16 11-33-00', '管理员');
+
+-- ----------------------------
+-- 18、角色和部门关联表  角色1-N部门(用于数据权限)
+-- ----------------------------
+drop table if exists sys_role_dept;
+create table sys_role_dept (
+  role_id 	int(11) not null comment '角色ID',
+  dept_id 	int(11) not null comment '部门ID',
+  primary key(role_id, dept_id)
+) engine=innodb default charset=utf8 comment = '角色和部门关联表,用于数据权限';

+ 12 - 0
src/main/java/com/ruoyi/project/system/dept/controller/DeptController.java

@@ -2,6 +2,8 @@ package com.ruoyi.project.system.dept.controller;
 
 import java.util.List;
 import java.util.Map;
+
+import com.ruoyi.project.system.role.domain.Role;
 import org.apache.shiro.authz.annotation.RequiresPermissions;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Controller;
@@ -147,4 +149,14 @@ public class DeptController extends BaseController
         List<Map<String, Object>> tree = deptService.selectDeptTree();
         return tree;
     }
+
+    /**
+     * 加载角色部门(数据权限)列表树
+     */
+    @GetMapping("/roleDeptTreeData")
+    @ResponseBody
+    public List<Map<String, Object>> deptTreeData(Role role){
+        List<Map<String, Object>> tree = deptService.roleDeptTreeData(role);
+        return tree;
+    }
 }

+ 8 - 0
src/main/java/com/ruoyi/project/system/dept/mapper/DeptMapper.java

@@ -80,4 +80,12 @@ public interface DeptMapper
      * @return 结果
      */
     public Dept checkDeptNameUnique(String deptName);
+
+    /**
+     * 根据角色ID查询菜单
+     *
+     * @param roleId 角色ID
+     * @return 菜单列表
+     */
+    public List<String> selectRoleDeptTree(Long roleId);
 }

+ 45 - 2
src/main/java/com/ruoyi/project/system/dept/service/DeptServiceImpl.java

@@ -4,6 +4,8 @@ import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+
+import com.ruoyi.project.system.role.domain.Role;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 import com.ruoyi.common.constant.UserConstants;
@@ -55,8 +57,42 @@ public class DeptServiceImpl implements IDeptService
     {
         List<Map<String, Object>> trees = new ArrayList<Map<String, Object>>();
         List<Dept> deptList = deptMapper.selectDeptAll();
+        trees=getTrees(deptList,false,null);
+        return trees;
+    }
+
+
+    /**
+     * 根据角色ID查询部门(数据权限)
+     *
+     * @param role 角色对象
+     * @return 部门列表(数据权限)
+     */
+    @Override
+    public List<Map<String, Object>> roleDeptTreeData(Role role) {
+        Long roleId=role.getRoleId();
+        List<Map<String, Object>> trees = new ArrayList<Map<String, Object>>();
+        List<Dept> deptList=deptMapper.selectDeptAll();
+        if(StringUtils.isNotNull(roleId)){
+            List<String> roleDeptList=deptMapper.selectRoleDeptTree(roleId);
+             trees=getTrees(deptList,true,roleDeptList);
+        }else {
+            trees=getTrees(deptList,false,null);
+        }
+        return trees;
+    }
+    /**
+     * 对象转菜单树
+     *
+     * @param menuList 菜单列表
+     * @param isCheck 是否需要选中
+     * @param roleDeptList 角色已存在菜单列表
+     * @return
+     */
+    public List<Map<String, Object>> getTrees(List<Dept> menuList, boolean isCheck, List<String> roleDeptList){
 
-        for (Dept dept : deptList)
+        List<Map<String, Object>> trees = new ArrayList<Map<String, Object>>();
+        for (Dept dept : menuList)
         {
             if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()))
             {
@@ -65,12 +101,19 @@ public class DeptServiceImpl implements IDeptService
                 deptMap.put("pId", dept.getParentId());
                 deptMap.put("name", dept.getDeptName());
                 deptMap.put("title", dept.getDeptName());
+                if (isCheck)
+                {
+                    deptMap.put("checked", roleDeptList.contains(dept.getDeptId() + dept.getDeptName()));
+                }
+                else
+                {
+                    deptMap.put("checked", false);
+                }
                 trees.add(deptMap);
             }
         }
         return trees;
     }
-
     /**
      * 查询部门人数
      * 

+ 9 - 0
src/main/java/com/ruoyi/project/system/dept/service/IDeptService.java

@@ -4,6 +4,7 @@ import java.util.List;
 import java.util.Map;
 
 import com.ruoyi.project.system.dept.domain.Dept;
+import com.ruoyi.project.system.role.domain.Role;
 
 /**
  * 部门管理 服务层
@@ -34,6 +35,14 @@ public interface IDeptService
      */
     public List<Map<String, Object>> selectDeptTree();
 
+    /**
+     * 根据角色ID查询菜单
+     *
+     * @param role 角色对象
+     * @return 菜单列表
+     */
+    public List<Map<String, Object>> roleDeptTreeData(Role role);
+
     /**
      * 查询部门人数
      * 

+ 1 - 2
src/main/java/com/ruoyi/project/system/menu/service/MenuServiceImpl.java

@@ -118,8 +118,7 @@ public class MenuServiceImpl implements IMenuService
 
     /**
      * 查询所有菜单
-     * 
-     * @param role 角色对象
+     *
      * @return 菜单列表
      */
     @Override

+ 8 - 11
src/main/java/com/ruoyi/project/system/role/controller/RoleController.java

@@ -1,16 +1,5 @@
 package com.ruoyi.project.system.role.controller;
 
-import java.util.List;
-import org.apache.shiro.authz.annotation.RequiresPermissions;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-import org.springframework.transaction.annotation.Transactional;
-import org.springframework.ui.ModelMap;
-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.RequestMapping;
-import org.springframework.web.bind.annotation.ResponseBody;
 import com.ruoyi.common.utils.poi.ExcelUtil;
 import com.ruoyi.framework.aspectj.lang.annotation.Log;
 import com.ruoyi.framework.aspectj.lang.constant.BusinessType;
@@ -19,6 +8,14 @@ import com.ruoyi.framework.web.domain.AjaxResult;
 import com.ruoyi.framework.web.page.TableDataInfo;
 import com.ruoyi.project.system.role.domain.Role;
 import com.ruoyi.project.system.role.service.IRoleService;
+import org.apache.shiro.authz.annotation.RequiresPermissions;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.ui.ModelMap;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.List;
 
 /**
  * 角色信息

+ 13 - 3
src/main/java/com/ruoyi/project/system/role/domain/Role.java

@@ -1,10 +1,10 @@
 package com.ruoyi.project.system.role.domain;
 
-import java.util.Arrays;
-
 import com.ruoyi.framework.aspectj.lang.annotation.Excel;
 import com.ruoyi.framework.web.domain.BaseEntity;
 
+import java.util.Arrays;
+
 /**
  * 角色对象 sys_role
  * 
@@ -38,6 +38,8 @@ public class Role extends BaseEntity
     private boolean flag = false;
     /** 菜单组 */
     private Long[] menuIds;
+    /** 部门组(数据权限) */
+    private Long[] deptIds;
 
     public Long getRoleId()
     {
@@ -109,11 +111,19 @@ public class Role extends BaseEntity
         this.menuIds = menuIds;
     }
 
+    public Long[] getDeptIds() {
+        return deptIds;
+    }
+
+    public void setDeptIds(Long[] deptIds) {
+        this.deptIds = deptIds;
+    }
+
     @Override
     public String toString()
     {
         return "Role [roleId=" + roleId + ", roleName=" + roleName + ", roleKey=" + roleKey + ", roleSort=" + roleSort
-                + ", status=" + status + ", flag=" + flag + ", menuIds=" + Arrays.toString(menuIds) + "]";
+                + ", status=" + status + ", flag=" + flag + ", menuIds=" + Arrays.toString(menuIds) + ", deptIds=" + Arrays.toString(deptIds)+ "]";
     }
 
 }

+ 32 - 0
src/main/java/com/ruoyi/project/system/role/domain/RoleDept.java

@@ -0,0 +1,32 @@
+package com.ruoyi.project.system.role.domain;
+
+/**
+ * 角色和部门关联 sys_role_dept
+ */
+public class RoleDept {
+    /** 角色ID */
+    private Long roleId;
+    /** 部门ID */
+    private Long deptId;
+
+    public Long getRoleId() {
+        return roleId;
+    }
+
+    public void setRoleId(Long roleId) {
+        this.roleId = roleId;
+    }
+
+    public Long getDeptId() {
+        return deptId;
+    }
+
+    public void setDeptId(Long deptId) {
+        this.deptId = deptId;
+    }
+    @Override
+    public String toString()
+    {
+        return "RoleDept [roleId=" + roleId + ", deptId=" + deptId + "]";
+    }
+}

+ 43 - 0
src/main/java/com/ruoyi/project/system/role/mapper/RoleDeptMapper.java

@@ -0,0 +1,43 @@
+package com.ruoyi.project.system.role.mapper;
+
+import com.ruoyi.project.system.role.domain.RoleDept;
+
+import java.util.List;
+
+/**
+ * 角色与部门关联表(用于数据权限) 数据层
+ */
+public interface RoleDeptMapper {
+    /**
+     * 通过角色ID删除角色和部门关联
+     *
+     * @param roleId 角色ID
+     * @return 结果
+     */
+    public int deleteRoleDeptByRoleId(Long roleId);
+
+    /**
+     * 批量删除角色部门关联信息
+     *
+     * @param ids 需要删除的数据ID
+     * @return 结果
+     */
+    public int deleteRoleDept(Long[] ids);
+
+    /**
+     * 查询部门使用数量
+     *
+     * @param detpId 部门ID
+     * @return 结果
+     */
+    public int selectCountRoleDeptByDetpId(Long detpId);
+
+    /**
+     * 批量新增角色部门信息(数据权限)
+     *
+     * @param roleDeptList 角色菜单列表
+     * @return 结果
+     */
+    public int batchRoleDept(List<RoleDept> roleDeptList);
+
+}

+ 2 - 1
src/main/java/com/ruoyi/project/system/role/service/IRoleService.java

@@ -1,8 +1,9 @@
 package com.ruoyi.project.system.role.service;
 
+import com.ruoyi.project.system.role.domain.Role;
+
 import java.util.List;
 import java.util.Set;
-import com.ruoyi.project.system.role.domain.Role;
 
 /**
  * 角色业务层

+ 271 - 240
src/main/java/com/ruoyi/project/system/role/service/RoleServiceImpl.java

@@ -1,240 +1,271 @@
-package com.ruoyi.project.system.role.service;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-import com.ruoyi.common.constant.UserConstants;
-import com.ruoyi.common.support.Convert;
-import com.ruoyi.common.utils.StringUtils;
-import com.ruoyi.common.utils.security.ShiroUtils;
-import com.ruoyi.project.system.role.domain.Role;
-import com.ruoyi.project.system.role.domain.RoleMenu;
-import com.ruoyi.project.system.role.mapper.RoleMapper;
-import com.ruoyi.project.system.role.mapper.RoleMenuMapper;
-import com.ruoyi.project.system.user.mapper.UserRoleMapper;
-
-/**
- * 角色 业务层处理
- * 
- * @author ruoyi
- */
-@Service
-public class RoleServiceImpl implements IRoleService
-{
-
-    @Autowired
-    private RoleMapper roleMapper;
-
-    @Autowired
-    private RoleMenuMapper roleMenuMapper;
-
-    @Autowired
-    private UserRoleMapper userRoleMapper;
-
-    /**
-     * 根据条件分页查询角色数据
-     * 
-     * @param role 角色信息
-     * @return 角色数据集合信息
-     */
-    @Override
-    public List<Role> selectRoleList(Role role)
-    {
-        return roleMapper.selectRoleList(role);
-    }
-
-    /**
-     * 根据用户ID查询权限
-     * 
-     * @param userId 用户ID
-     * @return 权限列表
-     */
-    @Override
-    public Set<String> selectRoleKeys(Long userId)
-    {
-        List<Role> perms = roleMapper.selectRolesByUserId(userId);
-        Set<String> permsSet = new HashSet<>();
-        for (Role perm : perms)
-        {
-            if (StringUtils.isNotNull(perms))
-            {
-                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
-            }
-        }
-        return permsSet;
-    }
-
-    /**
-     * 根据用户ID查询角色
-     * 
-     * @param userId 用户ID
-     * @return 角色列表
-     */
-    @Override
-    public List<Role> selectRolesByUserId(Long userId)
-    {
-        List<Role> userRoles = roleMapper.selectRolesByUserId(userId);
-        List<Role> roles = roleMapper.selectRolesAll();
-        for (Role role : roles)
-        {
-            for (Role userRole : userRoles)
-            {
-                if (role.getRoleId() == userRole.getRoleId())
-                {
-                    role.setFlag(true);
-                    break;
-                }
-            }
-        }
-        return roles;
-    }
-
-    /**
-     * 查询所有角色
-     * 
-     * @return 角色列表
-     */
-    @Override
-    public List<Role> selectRoleAll()
-    {
-        return roleMapper.selectRolesAll();
-    }
-
-    /**
-     * 通过角色ID查询角色
-     * 
-     * @param roleId 角色ID
-     * @return 角色对象信息
-     */
-    @Override
-    public Role selectRoleById(Long roleId)
-    {
-        return roleMapper.selectRoleById(roleId);
-    }
-
-    /**
-     * 通过角色ID删除角色
-     * 
-     * @param roleId 角色ID
-     * @return 结果
-     */
-    @Override
-    public boolean deleteRoleById(Long roleId)
-    {
-        return roleMapper.deleteRoleById(roleId) > 0 ? true : false;
-    }
-
-    /**
-     * 批量删除角色信息
-     * 
-     * @param ids 需要删除的数据ID
-     * @throws Exception
-     */
-    @Override
-    public int deleteRoleByIds(String ids) throws Exception
-    {
-        Long[] roleIds = Convert.toLongArray(ids);
-        for (Long roleId : roleIds)
-        {
-            Role role = selectRoleById(roleId);
-            if (countUserRoleByRoleId(roleId) > 0)
-            {
-                throw new Exception(String.format("%1$s已分配,不能删除", role.getRoleName()));
-            }
-        }
-        return roleMapper.deleteRoleByIds(roleIds);
-    }
-
-    /**
-     * 新增保存角色信息
-     * 
-     * @param role 角色信息
-     * @return 结果
-     */
-    @Override
-    public int insertRole(Role role)
-    {
-        role.setCreateBy(ShiroUtils.getLoginName());
-        // 新增角色信息
-        roleMapper.insertRole(role);
-        ShiroUtils.clearCachedAuthorizationInfo();
-        return insertRoleMenu(role);
-    }
-
-    /**
-     * 修改保存角色信息
-     * 
-     * @param role 角色信息
-     * @return 结果
-     */
-    @Override
-    public int updateRole(Role role)
-    {
-        role.setUpdateBy(ShiroUtils.getLoginName());
-        // 修改角色信息
-        roleMapper.updateRole(role);
-        // 删除角色与菜单关联
-        roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId());
-        ShiroUtils.clearCachedAuthorizationInfo();
-        return insertRoleMenu(role);
-    }
-
-    /**
-     * 新增角色菜单信息
-     * 
-     * @param user 角色对象
-     */
-    public int insertRoleMenu(Role role)
-    {
-        int rows = 1;
-        // 新增用户与角色管理
-        List<RoleMenu> list = new ArrayList<RoleMenu>();
-        for (Long menuId : role.getMenuIds())
-        {
-            RoleMenu rm = new RoleMenu();
-            rm.setRoleId(role.getRoleId());
-            rm.setMenuId(menuId);
-            list.add(rm);
-        }
-        if (list.size() > 0)
-        {
-            rows = roleMenuMapper.batchRoleMenu(list);
-        }
-        return rows;
-    }
-
-    /**
-     * 校验角色名称是否唯一
-     * 
-     * @param role 角色信息
-     * @return 结果
-     */
-    @Override
-    public String checkRoleNameUnique(Role role)
-    {
-        Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
-        Role info = roleMapper.checkRoleNameUnique(role.getRoleName());
-        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue())
-        {
-            return UserConstants.ROLE_NAME_NOT_UNIQUE;
-        }
-        return UserConstants.ROLE_NAME_UNIQUE;
-    }
-
-    /**
-     * 通过角色ID查询角色使用数量
-     * 
-     * @param roleId 角色ID
-     * @return 结果
-     */
-    @Override
-    public int countUserRoleByRoleId(Long roleId)
-    {
-        return userRoleMapper.countUserRoleByRoleId(roleId);
-    }
-
-}
+package com.ruoyi.project.system.role.service;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import com.ruoyi.project.system.role.domain.RoleDept;
+import com.ruoyi.project.system.role.mapper.RoleDeptMapper;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import com.ruoyi.common.constant.UserConstants;
+import com.ruoyi.common.support.Convert;
+import com.ruoyi.common.utils.StringUtils;
+import com.ruoyi.common.utils.security.ShiroUtils;
+import com.ruoyi.project.system.role.domain.Role;
+import com.ruoyi.project.system.role.domain.RoleMenu;
+import com.ruoyi.project.system.role.mapper.RoleMapper;
+import com.ruoyi.project.system.role.mapper.RoleMenuMapper;
+import com.ruoyi.project.system.user.mapper.UserRoleMapper;
+
+/**
+ * 角色 业务层处理
+ * 
+ * @author ruoyi
+ */
+@Service
+public class RoleServiceImpl implements IRoleService
+{
+
+    @Autowired
+    private RoleMapper roleMapper;
+
+    @Autowired
+    private RoleMenuMapper roleMenuMapper;
+
+    @Autowired
+    private UserRoleMapper userRoleMapper;
+
+    @Autowired
+    private RoleDeptMapper roleDeptMapper;
+
+    /**
+     * 根据条件分页查询角色数据
+     * 
+     * @param role 角色信息
+     * @return 角色数据集合信息
+     */
+    @Override
+    public List<Role> selectRoleList(Role role)
+    {
+        return roleMapper.selectRoleList(role);
+    }
+
+    /**
+     * 根据用户ID查询权限
+     * 
+     * @param userId 用户ID
+     * @return 权限列表
+     */
+    @Override
+    public Set<String> selectRoleKeys(Long userId)
+    {
+        List<Role> perms = roleMapper.selectRolesByUserId(userId);
+        Set<String> permsSet = new HashSet<>();
+        for (Role perm : perms)
+        {
+            if (StringUtils.isNotNull(perms))
+            {
+                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
+            }
+        }
+        return permsSet;
+    }
+
+    /**
+     * 根据用户ID查询角色
+     * 
+     * @param userId 用户ID
+     * @return 角色列表
+     */
+    @Override
+    public List<Role> selectRolesByUserId(Long userId)
+    {
+        List<Role> userRoles = roleMapper.selectRolesByUserId(userId);
+        List<Role> roles = roleMapper.selectRolesAll();
+        for (Role role : roles)
+        {
+            for (Role userRole : userRoles)
+            {
+                if (role.getRoleId() == userRole.getRoleId())
+                {
+                    role.setFlag(true);
+                    break;
+                }
+            }
+        }
+        return roles;
+    }
+
+    /**
+     * 查询所有角色
+     * 
+     * @return 角色列表
+     */
+    @Override
+    public List<Role> selectRoleAll()
+    {
+        return roleMapper.selectRolesAll();
+    }
+
+    /**
+     * 通过角色ID查询角色
+     * 
+     * @param roleId 角色ID
+     * @return 角色对象信息
+     */
+    @Override
+    public Role selectRoleById(Long roleId)
+    {
+        return roleMapper.selectRoleById(roleId);
+    }
+
+    /**
+     * 通过角色ID删除角色
+     * 
+     * @param roleId 角色ID
+     * @return 结果
+     */
+    @Override
+    public boolean deleteRoleById(Long roleId)
+    {
+        return roleMapper.deleteRoleById(roleId) > 0 ? true : false;
+    }
+
+    /**
+     * 批量删除角色信息
+     * 
+     * @param ids 需要删除的数据ID
+     * @throws Exception
+     */
+    @Override
+    public int deleteRoleByIds(String ids) throws Exception
+    {
+        Long[] roleIds = Convert.toLongArray(ids);
+        for (Long roleId : roleIds)
+        {
+            Role role = selectRoleById(roleId);
+            if (countUserRoleByRoleId(roleId) > 0)
+            {
+                throw new Exception(String.format("%1$s已分配,不能删除", role.getRoleName()));
+            }
+        }
+        return roleMapper.deleteRoleByIds(roleIds);
+    }
+
+    /**
+     * 新增保存角色信息
+     * 
+     * @param role 角色信息
+     * @return 结果
+     */
+    @Override
+    public int insertRole(Role role)
+    {
+        role.setCreateBy(ShiroUtils.getLoginName());
+        // 新增角色信息
+        roleMapper.insertRole(role);
+        ShiroUtils.clearCachedAuthorizationInfo();
+        //新增角色和部门信息(数据权限)
+        insertRoleDept(role);
+        return insertRoleMenu(role);
+    }
+
+    /**
+     * 修改保存角色信息
+     *
+     * @param role 角色信息
+     * @return 结果
+     */
+    @Override
+    public int updateRole(Role role)
+    {
+        role.setUpdateBy(ShiroUtils.getLoginName());
+        // 修改角色信息
+        roleMapper.updateRole(role);
+        // 删除角色与菜单关联
+        roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId());
+        ShiroUtils.clearCachedAuthorizationInfo();
+        //新增角色和部门信息(数据权限)
+        insertRoleDept(role);
+        return insertRoleMenu(role);
+    }
+
+    /**
+     * 新增角色菜单信息
+     * 
+     * @param role 角色对象
+     */
+    public int insertRoleMenu(Role role)
+    {
+        int rows = 1;
+        // 新增用户与角色管理
+        List<RoleMenu> list = new ArrayList<RoleMenu>();
+        for (Long menuId : role.getMenuIds())
+        {
+            RoleMenu rm = new RoleMenu();
+            rm.setRoleId(role.getRoleId());
+            rm.setMenuId(menuId);
+            list.add(rm);
+        }
+        if (list.size() > 0)
+        {
+            rows = roleMenuMapper.batchRoleMenu(list);
+        }
+        return rows;
+    }
+
+    /**
+     * 新增角色部门信息(数据权限)
+     *
+     * @param role 角色对象
+     */
+    public void  insertRoleDept(Role role)
+    {
+        // 新增角色与部门(数据权限)管理
+        List<RoleDept> list = new ArrayList<RoleDept>();
+        for (Long deptId : role.getDeptIds())
+        {
+            RoleDept rd = new RoleDept();
+            rd.setRoleId(role.getRoleId());
+            rd.setDeptId(deptId);
+            list.add(rd);
+        }
+        if (list.size() > 0)
+        {
+            roleDeptMapper.batchRoleDept(list);
+        }
+    }
+    /**
+     * 校验角色名称是否唯一
+     * 
+     * @param role 角色信息
+     * @return 结果
+     */
+    @Override
+    public String checkRoleNameUnique(Role role)
+    {
+        Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
+        Role info = roleMapper.checkRoleNameUnique(role.getRoleName());
+        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue())
+        {
+            return UserConstants.ROLE_NAME_NOT_UNIQUE;
+        }
+        return UserConstants.ROLE_NAME_UNIQUE;
+    }
+
+    /**
+     * 通过角色ID查询角色使用数量
+     * 
+     * @param roleId 角色ID
+     * @return 结果
+     */
+    @Override
+    public int countUserRoleByRoleId(Long roleId)
+    {
+        return userRoleMapper.countUserRoleByRoleId(roleId);
+    }
+
+}

+ 8 - 0
src/main/resources/mybatis/system/DeptMapper.xml

@@ -24,6 +24,14 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
         select t.dept_id, t.parent_id, t.dept_name, t.order_num, t.leader, t.phone, t.email, t.status, t.create_by, t.create_time from sys_dept t
     </sql>
 
+	<select id="selectRoleDeptTree" parameterType="Long" resultType="String">
+		select concat(d.dept_id, d.dept_name) as dept_name
+		from sys_dept d
+			left join sys_role_dept rd on d.dept_id = rd.dept_id
+		where rd.role_id = #{roleId}
+		order by d.parent_id, d.order_num
+	</select>
+
 	<select id="selectDeptAll" resultMap="DeptResult">
 		<include refid="selectDeptVo"/>
 	</select>

+ 34 - 0
src/main/resources/mybatis/system/RoleDeptMapper.xml

@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<!DOCTYPE mapper
+PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
+"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
+<mapper namespace="com.ruoyi.project.system.role.mapper.RoleDeptMapper">
+
+	<resultMap type="RoleDept" id="RoleDeptResult">
+		<result property="roleId"     column="role_id"      />
+		<result property="deptId"     column="dept_id"      />
+	</resultMap>
+
+	<delete id="deleteRoleDeptByRoleId" parameterType="Long">
+		delete from sys_role_dept where role_id=#{roleId}
+	</delete>
+	
+	<select id="selectCountRoleDeptByDetpId" resultType="Integer">
+	    select count(*) from sys_role_dept where dept_id=#{detpId}
+	</select>
+	
+	<delete id="deleteRoleDept" parameterType="Long">
+ 		delete from sys_role_dept where role_id in
+ 		<foreach collection="array" item="roleId" open="(" separator="," close=")">
+ 			#{roleId}
+        </foreach> 
+ 	</delete>
+	
+	<insert id="batchRoleDept">
+		insert into sys_role_dept(role_id, dept_id) values
+		<foreach item="item" index="index" collection="list" separator=",">
+			(#{item.roleId},#{item.deptId})
+		</foreach>
+	</insert>
+	
+</mapper> 

+ 50 - 12
src/main/resources/templates/system/role/add.html

@@ -48,6 +48,12 @@
 					<div id="menuTrees" class="ztree"></div>
 				</div>
 			</div>
+			<div class="form-group">
+				<label class="col-sm-3 control-label">数据权限</label>
+				<div class="col-sm-8">
+					<div id="deptTrees" class="ztree"></div>
+				</div>
+			</div>
 			<div class="form-group">
 				<div class="form-control-static col-sm-offset-9">
 					<button type="submit" class="btn btn-primary">提交</button>
@@ -76,6 +82,24 @@
 				menuTrees = $.fn.zTree.init($("#menuTrees"), setting, data); //.expandAll(true);
 			}, null, null, "正在加载,请稍后...");
 		};loadTree();
+
+        // 权限树结构初始化加载
+        var deptsetting = {
+            check:{enable:true,nocheckInherit:true,chkboxType:{"Y":"ps","N":"ps"}},
+            view:{selectedMulti:false,nameIsHTML: true},
+            data:{simpleData:{enable:true},key:{title:"title"}},
+            callback:{
+                beforeClick: function (treeId, treeNode, clickFlag) {
+                    var deptTrees = $.fn.zTree.getZTreeObj(treeId);
+                    deptTrees.checkNode(treeNode, !treeNode.checked, true, true);
+                    return false;
+                }
+            }
+        }, deptTrees, loadTree = function(){
+            $.get(ctx + "system/dept/treeData", function(data) {
+                deptTrees = $.fn.zTree.init($("#deptTrees"), deptsetting, data); //.expandAll(true);
+            }, null, null, "正在加载,请稍后...");
+        };loadTree();
 	
 		$("#form-role-add").validate({
 			rules:{
@@ -115,17 +139,29 @@
 		});
 	
 		function selectCheckeds() {
-		    var menuIds = "";
-		    var treeNodes = menuTrees.getCheckedNodes(true);
-		    for (var i = 0; i < treeNodes.length; i++) {
-		        if (0 == i) {
-		        	menuIds = treeNodes[i].id;
-		        } else {
-		        	menuIds += ("," + treeNodes[i].id);
-		        }
-		    }
-		    return menuIds;
-		}
+            var menuIds = "";
+            var treeNodes = menuTrees.getCheckedNodes(true);
+            for (var i = 0; i < treeNodes.length; i++) {
+                if (0 == i) {
+                    menuIds = treeNodes[i].id;
+                } else {
+                    menuIds += ("," + treeNodes[i].id);
+                }
+            }
+            return menuIds;
+        }
+        function selectDeptCheckeds() {
+            var deptIds = "";
+            var treeNodes = deptTrees.getCheckedNodes(true);
+            for (var i = 0; i < treeNodes.length; i++) {
+                if (0 == i) {
+                    deptIds = treeNodes[i].id;
+                } else {
+                    deptIds += ("," + treeNodes[i].id);
+                }
+            }
+            return deptIds;
+        }
 	
 		function add() {
 			var roleName = $("input[name='roleName']").val();
@@ -134,6 +170,7 @@
 			var status = $("input[name='status']").is(':checked') == true ? 0 : 1;
 			var remark = $("input[name='remark']").val();
 			var menuIds = selectCheckeds();
+			var deptIds = selectDeptCheckeds();
 			$.ajax({
 				cache : true,
 				type : "POST",
@@ -144,7 +181,8 @@
 					"roleSort": roleSort,
 					"status": status,
 					"remark": remark,
-					"menuIds": menuIds
+					"menuIds": menuIds,
+					"deptIds":deptIds
 				},
 				async : false,
 				error : function(request) {

+ 42 - 3
src/main/resources/templates/system/role/edit.html

@@ -49,6 +49,12 @@
 					<div id="menuTrees" class="ztree"></div>
 				</div>
 			</div>
+			<div class="form-group">
+				<label class="col-sm-3 control-label">数据权限</label>
+				<div class="col-sm-8">
+					<div id="deptTrees" class="ztree"></div>
+				</div>
+			</div>
 			<div class="form-group">
 				<div class="form-control-static col-sm-offset-9">
 					<button type="submit" class="btn btn-primary">提交</button>
@@ -77,7 +83,25 @@
 				menuTrees = $.fn.zTree.init($("#menuTrees"), setting, data); //.expandAll(true);
 			}, null, null, "正在加载,请稍后...");
 		};loadTree();
-	
+
+        // 部门(数据权限)树结构初始化加载
+        var deptsetting = {
+            check:{enable:true,nocheckInherit:true,chkboxType:{"Y":"ps","N":"ps"}},
+            view:{selectedMulti:false,nameIsHTML: true},
+            data:{simpleData:{enable:true},key:{title:"title"}},
+            callback:{
+                beforeClick: function (treeId, treeNode, clickFlag) {
+                    var deptTrees = $.fn.zTree.getZTreeObj(treeId);
+                    deptTrees.checkNode(treeNode, !treeNode.checked, true, true);
+                    return false;
+                }
+            }
+        }, deptTrees, loadTree = function(){
+            $.get(ctx + "system/dept/roleDeptTreeData?roleId=" + $("#roleId").val(), function(data) {
+                deptTrees = $.fn.zTree.init($("#deptTrees"), deptsetting, data); //.expandAll(true);
+            }, null, null, "正在加载,请稍后...");
+        };loadTree();
+
 		$("#form-role-edit").validate({
 			rules:{
 				roleName:{
@@ -130,7 +154,20 @@
 		    }
 		    return menuIds;
 		}
-	
+
+        function selectDeptCheckeds() {
+            var deptIds = "";
+            var treeNodes = deptTrees.getCheckedNodes(true);
+            for (var i = 0; i < treeNodes.length; i++) {
+                if (0 == i) {
+                    deptIds = treeNodes[i].id;
+                } else {
+                    deptIds += ("," + treeNodes[i].id);
+                }
+            }
+            return deptIds;
+        }
+
 		function edit() {
 			var roleId = $("input[name='roleId']").val();
 			var roleName = $("input[name='roleName']").val();
@@ -139,6 +176,7 @@
 			var status = $("input[name='status']").is(':checked') == true ? 0 : 1;
 			var remark = $("input[name='remark']").val();
 			var menuIds = selectCheckeds();
+            var deptIds = selectDeptCheckeds();
 			$.ajax({
 				cache : true,
 				type : "POST",
@@ -150,7 +188,8 @@
 					"roleSort": roleSort,
 					"status": status,
 					"remark": remark,
-					"menuIds": menuIds
+					"menuIds": menuIds,
+			        "deptIds": deptIds
 				},
 				async : false,
 				error : function(request) {