角色指派用户功能

This commit is contained in:
summer853300975 2016-10-28 20:18:12 +08:00
parent 4703ecf4f5
commit 3e32dfc1e5
10 changed files with 251 additions and 2 deletions

View File

@ -226,6 +226,7 @@
<Content Include="Views\Shared\Glyphicons.cshtml" />
<Content Include="Views\Shared\RoleConfig.cshtml" />
<Content Include="Views\Shared\IconView.cshtml" />
<Content Include="Views\Shared\UserConfig.cshtml" />
<None Include="Web.Debug.config">
<DependentUpon>Web.config</DependentUpon>
</None>

View File

@ -254,6 +254,39 @@
processRolesData({ Id: menuId, callback: callback, method: "PUT", data: { type: "menu", roleIds: roleIds } });
};
var processUsersData = function (options) {
var data = $.extend({ data: { type: "" }, method: "POST", Id: "" }, options);
$.ajax({
url: '../api/Users/' + data.Id,
data: data.data,
type: data.method,
success: function (result) {
if ($.isFunction(data.callback)) {
if ($.isArray(result)) {
var html = $.map(result, function (element, index) {
return $.format('<div class="checkbox col-lg-3 col-xs-4"><input type="checkbox" value="{0}" {2}>{1}</div>', element.ID, element.DisplayName, element.Checked);
}).join('');
data.callback(html);
}
else
data.callback(result);
}
else { data.callback(false); }
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if ($.isFunction(data.callback)) data.callback(false);
}
});
}
User = {};
User.getUsersByRoleId = function (roleId, callback) {
processUsersData({ Id: roleId, callback: callback, data: { type: "role" } });
};
User.saveUsersByRoleId = function (roleId, userIds, callback) {
processUsersData({ Id: roleId, callback: callback, method: "PUT", data: { type: "role", userIds: userIds } });
}
Group = {};
Group.getGroupsByUserId = function (userId) {

View File

@ -2,6 +2,8 @@
using Bootstrap.DataAccess;
using System.Web.Http;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
namespace Bootstrap.Admin.Controllers
{
@ -20,6 +22,28 @@ namespace Bootstrap.Admin.Controllers
{
return value.RetrieveData();
}
/// <summary>
///
/// </summary>
/// <param name="roleId"></param>
/// <param name="value"></param>
/// <returns></returns>
[HttpPost]
public IEnumerable<User> Post(int id, [FromBody]JObject value)
{
var ret = new List<User>();
dynamic json = value;
switch ((string)json.type)
{
case "role":
ret = UserHelper.RetrieveUsersByRoleId(id).ToList();
break;
default:
break;
}
return ret;
}
/// <summary>
///
/// </summary>
@ -39,6 +63,24 @@ namespace Bootstrap.Admin.Controllers
{
return UserHelper.SaveUser(value);
}
[HttpPut]
public bool Put(int id, [FromBody]JObject value)
{
var ret = false;
dynamic json = value;
string userIds = json.userIds;
switch ((string)json.type)
{
case "role":
ret = UserHelper.SaveUsersByRoleId(id, userIds);
break;
default:
break;
}
return ret;
}
/// <summary>
///
/// </summary>

View File

@ -7,7 +7,46 @@
RoleName: "roleName",
Description: "roleDesc"
}
})
}),
click: {
assign: [{
id: 'btn_assignUser',
click: function (row) {
User.getUsersByRoleId(row.ID, function (data) {
$("#dialogUser.modal-title").text($.format('{0}-用户授权窗口', row.RoleName));
$('#dialogUser form').html(data);
$('#dialogUser').modal('show');
})
}
}, {
id: 'btn_assignGroup',
click: function (row) {
var roleId = row.ID;
}
}, {
id: 'btnSubmitRoleUser',
click: function (row) {
var roleId = row.ID;
var userIds = $('#dialogUser :checked').map(function (index, element) {
return $(element).val();
}).toArray().join(',');
User.saveUsersByRoleId(roleId, userIds, function (result) {
if (result) {
$('#dialogUser').modal('hide');
swal("成功", "修改用户", "success");
}
else {
swal("失败", "修改用户", "error");
}
});
}
}]
},
success: function (src, data) {
if (src === 'save' && data.ID === $('#roleId').val()) {
//$('.username').text(data.DisplayName);
}
}
});
$('table').smartTable({

View File

@ -19,7 +19,7 @@
<input type="text" class="form-control" id="txt_search_name" />
</div>
<div class="form-group col-lg-5">
<label class="control-label" for="txt_group_desc">角色描述</label>
<label class="control-label" for="txt_role_desc">角色描述</label>
<input type="text" class="form-control" id="txt_role_desc" />
</div>
<div class="form-group col-lg-2">
@ -27,6 +27,14 @@
</div>
</form>
}
@section toolbar{
<button id="btn_assignUser" type="button" class="btn btn-info">
<span class="fa fa-sitemap" aria-hidden="true"></span>指派用户
</button>
<button id="btn_assignGroup" type="button" class="btn btn-info">
<span class="fa fa-home" aria-hidden="true"></span>指派部门
</button>
}
@section modal {
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
@ -45,4 +53,7 @@
</div>
</form>
</div>
}
@section customModal{
@Html.Partial("UserConfig")
}

View File

@ -0,0 +1,17 @@
<div class="modal fade" id="dialogUser" tabindex="-1" role="dialog" data-backdrop="static" aria-labelledby="myUserModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title" id="myUserModalLabel">用户授权窗口</h4>
</div>
<div class="modal-body">
<form class="form-inline" role="form"></form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
<button type="button" class="btn btn-primary" id="btnSubmitRoleUser">保存</button>
</div>
</div>
</div>
</div>

View File

@ -25,6 +25,7 @@
<cacheManager>
<add key="TerminalData-CodeTerminalHelper" interval="600" desc="输入口信息缓存" />
<add key="GroupData-CodeGroupHelper" interval="600" desc="群组信息缓存" />
<add key="UserData-CodeUserHelper-Role-" interval="600" desc="角色用户信息缓存" />
<add key="UserData-CodeUserHelper" interval="600" desc="用户信息缓存" />
<add key="UserData-CodeUserHelper-" interval="600" desc="用户信息缓存" />
<add key="RoleData-CodeRoleHelper" interval="600" desc="角色信息缓存" />

View File

@ -25,5 +25,9 @@
/// 获取/设置 显示名称
/// </summary>
public string DisplayName { get; set; }
/// <summary>
/// 获取/设置 角色用户关联状态 checked 标示已经关联 '' 标示未关联
/// </summary>
public string Checked { get; set; }
}
}

View File

@ -6,6 +6,7 @@ using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
@ -18,6 +19,7 @@ namespace Bootstrap.DataAccess
{
private const string UserDataKey = "UserData-CodeUserHelper";
private const string UserDisplayNameDataKey = "UserData-CodeUserHelper-";
private const string UserRoleIDDataKey = "UserData-CodeUserHelper-Role-";
/// <summary>
/// 查询所有用户
/// </summary>
@ -161,6 +163,93 @@ namespace Bootstrap.DataAccess
{
CacheManager.Clear(key => key == UserDataKey);
CacheManager.Clear(key => key.Contains(UserDisplayNameDataKey));
CacheManager.Clear(key => key.Contains(UserRoleIDDataKey));
}
/// <summary>
/// 通过roleId获取所有用户
/// </summary>
/// <param name="roleId"></param>
/// <returns></returns>
public static IEnumerable<User> RetrieveUsersByRoleId(int roleId)
{
string key = string.Format("{0}{1}", UserRoleIDDataKey, roleId);
return CacheManager.GetOrAdd(key, CacheSection.RetrieveIntervalByKey(UserDisplayNameDataKey), k =>
{
List<User> Users = new List<User>();
string sql = "select u.ID,u.UserName,u.DisplayName,case ur.UserID when u.ID then 'checked' else '' end [status] from Users u left join UserRole ur on u.ID=ur.UserID and RoleID =@RoleID";
DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql);
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@RoleID", roleId, ParameterDirection.Input));
try
{
using (DbDataReader reader = DBAccessManager.SqlDBAccess.ExecuteReader(cmd))
{
while (reader.Read())
{
Users.Add(new User()
{
ID = (int)reader[0],
UserName = (string)reader[1],
DisplayName = (string)reader[2],
Checked = (string)reader[3]
});
}
}
}
catch (Exception ex) { ExceptionManager.Publish(ex); }
return Users;
}, CacheSection.RetrieveDescByKey(UserRoleIDDataKey));
}
/// <summary>
/// 通过角色ID保存当前授权用户插入
/// </summary>
/// <param name="id">角色ID</param>
/// <param name="value">用户ID数组</param>
/// <returns></returns>
public static bool SaveUsersByRoleId(int id, string value)
{
DataTable dt = new DataTable();
dt.Columns.Add("RoleID", typeof(int));
dt.Columns.Add("UserID", typeof(int));
if (!string.IsNullOrEmpty(value))
{
string[] userIds = value.Split(',');
foreach (string userId in userIds)
{
DataRow dr = dt.NewRow();
dr["RoleID"] = id;
dr["UserID"] = userId;
dt.Rows.Add(dr);
}
}
var trans = DBAccessManager.SqlDBAccess.BeginTransaction();
try
{
using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, string.Empty))
{
cmd.CommandText = "delete from UserRole where RoleId=@RoleId";
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@RoleId", id, ParameterDirection.Input));
DBAccessManager.SqlDBAccess.ExecuteNonQuery(cmd, trans);
using (SqlBulkCopy bulk = new SqlBulkCopy((SqlConnection)trans.Transaction.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)trans.Transaction))
{
bulk.BatchSize = 1000;
bulk.DestinationTableName = "UserRole";
bulk.ColumnMappings.Add("RoleID", "RoleID");
bulk.ColumnMappings.Add("UserID", "UserID");
bulk.WriteToServer(dt);
}
trans.CommitTransaction();
ClearCache();
return true;
}
}
catch
{
trans.RollbackTransaction();
return false;
}
}
}
}

View File

@ -1,4 +1,5 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Linq;
namespace Bootstrap.DataAccess.Tests
@ -43,5 +44,16 @@ namespace Bootstrap.DataAccess.Tests
result = UserHelper.SaveUser(users1);
Assert.IsTrue(result == true, "更新用户信息失败请检查数据库连接或者数据库SQL语句");
}
[TestMethod]
public void RetrieveUsersByRoleIdTest(){
IEnumerable<User> result = UserHelper.RetrieveUsersByRoleId(2);
Assert.IsTrue(result.Count() >= 0, "获取该角色的用户信息失败请检查数据库连接或者数据库SQL语句");
}
[TestMethod]
public void SaveUsersByRoleIdTest()
{
bool result = UserHelper.SaveUsersByRoleId(2,"2,3");
Assert.IsTrue(result, "获取该角色的用户信息失败请检查数据库连接或者数据库SQL语句");
}
}
}