用户指派部门功能

This commit is contained in:
lq_avenue 2016-10-28 21:46:48 +08:00
parent 39490253de
commit 8c79d0955d
9 changed files with 223 additions and 3 deletions

View File

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

View File

@ -297,9 +297,41 @@
processUsersData({ Id: roleId, callback: callback, method: "PUT", data: { type: "role", userIds: userIds } }); processUsersData({ Id: roleId, callback: callback, method: "PUT", data: { type: "role", userIds: userIds } });
} }
Group = {}; var processGroupsData = function (options) {
Group.getGroupsByUserId = function (userId) { var data = $.extend({ data: { type: "" }, method: "POST", Id: "" }, options);
$.ajax({
url: '../api/Groups/' + 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"><label title="{3}"><input type="checkbox" value="{0}" {2}>{1}</label></div>', element.ID, element.GroupName, element.Checked, element.Description);
}).join('');
data.callback(html);
return;
}
}
else if ($.isPlainObject(data.callback) && data.callback.modal !== undefined) {
$("#" + data.callback.modal).modal('hide');
}
if (result) { swal("成功", "授权角色", "success"); }
else { swal("失败", "授权角色", "error"); }
if ($.isFunction(data.callback)) data.callback(result);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if ($.isFunction(data.callback)) data.callback(false);
}
});
}
Group = {};
Group.getGroupsByUserId = function (userId, callback) {
processGroupsData({ Id: userId, callback: callback, data: { type: "user" } });
};
Group.saveGroupsByUserId = function (userId, groupIds, callback) {
processGroupsData({ Id: userId, callback: callback, method: "PUT", data: { type: "user", groupIds: groupIds } });
}; };
Group.getGroupsByRoleId = function (roleId) { Group.getGroupsByRoleId = function (roleId) {

View File

@ -1,5 +1,7 @@
using Bootstrap.Admin.Models; using Bootstrap.Admin.Models;
using Bootstrap.DataAccess; using Bootstrap.DataAccess;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Web.Http; using System.Web.Http;
@ -45,5 +47,48 @@ namespace Bootstrap.Admin.Controllers
{ {
return GroupHelper.DeleteGroup(value); return GroupHelper.DeleteGroup(value);
} }
/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <param name="value"></param>
/// <returns></returns>
[HttpPost]
public IEnumerable<Group> Post(int id, [FromBody]JObject value)
{
var ret = new List<Group>();
dynamic json = value;
switch ((string)json.type)
{
case "user":
ret = GroupHelper.RetrieveGroupsByUserId(id).ToList();
break;
default:
break;
}
return ret;
}
/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <param name="value"></param>
/// <returns></returns>
[HttpPut]
public bool Put(int id, [FromBody]JObject value)
{
var ret = false;
dynamic json = value;
string groupIds = json.groupIds;
switch ((string)json.type)
{
case "user":
ret = GroupHelper.SaveGroupsByUserId(id, groupIds);
break;
default:
break;
}
return ret;
}
} }
} }

View File

@ -22,7 +22,11 @@
}, { }, {
id: 'btn_assignGroup', id: 'btn_assignGroup',
click: function (row) { click: function (row) {
var userId = row.ID; Group.getGroupsByUserId(row.ID, function (data) {
$("#dialogGroup .modal-title").text($.format('{0}-部门授权窗口', row.DisplayName));
$('#dialogGroup form').html(data);
$('#dialogGroup').modal('show');
});
} }
}, { }, {
id: 'btnSubmitUserRole', id: 'btnSubmitUserRole',
@ -33,6 +37,15 @@
}).toArray().join(','); }).toArray().join(',');
Role.saveRolesByUserId(userId, roleIds, { modal: 'dialogRole' }); Role.saveRolesByUserId(userId, roleIds, { modal: 'dialogRole' });
} }
}, {
id: 'btnSubmitUserGroup',
click: function (row) {
var userId = row.ID;
var groupIds = $('#dialogGroup :checked').map(function (index, element) {
return $(element).val();
}).toArray().join(',');
Group.saveGroupsByUserId(userId, groupIds, { modal: 'dialogGroup' });
}
}] }]
}, },
success: function (src, data) { success: function (src, data) {

View File

@ -64,4 +64,5 @@
} }
@section customModal { @section customModal {
@Html.Partial("RoleConfig") @Html.Partial("RoleConfig")
@Html.Partial("GroupConfig")
} }

View File

@ -0,0 +1,17 @@
<div class="modal fade" id="dialogGroup" tabindex="-1" role="dialog" data-backdrop="static" aria-labelledby="myGroupModalLabel" 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="myGroupModalLabel">部门授权窗口</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="btnSubmitUserGroup">保存</button>
</div>
</div>
</div>
</div>

View File

@ -20,5 +20,10 @@
/// 获得/设置 群组描述 /// 获得/设置 群组描述
/// </summary> /// </summary>
public string Description { get; set; } public string Description { get; set; }
/// <summary>
/// 获取/设置 用户群组关联状态 checked 标示已经关联 '' 标示未关联
/// </summary>
public string Checked { get; set; }
} }
} }

View File

@ -1,10 +1,12 @@
using Longbow.Caching; using Longbow.Caching;
using Longbow.Caching.Configuration; using Longbow.Caching.Configuration;
using Longbow.Data;
using Longbow.ExceptionManagement; using Longbow.ExceptionManagement;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data; using System.Data;
using System.Data.Common; using System.Data.Common;
using System.Data.SqlClient;
using System.Globalization; using System.Globalization;
using System.Linq; using System.Linq;
@ -17,6 +19,7 @@ namespace Bootstrap.DataAccess
public static class GroupHelper public static class GroupHelper
{ {
private const string GroupDataKey = "GroupData-CodeGroupHelper"; private const string GroupDataKey = "GroupData-CodeGroupHelper";
private const string GroupUserIDDataKey = "GroupData-CodeGroupHelper-";
/// <summary> /// <summary>
/// 查询所有群组信息 /// 查询所有群组信息
/// </summary> /// </summary>
@ -105,10 +108,101 @@ namespace Bootstrap.DataAccess
} }
return ret; return ret;
} }
/// <summary>
/// 根据用户查询部门信息
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public static IEnumerable<Group> RetrieveGroupsByUserId(int userId)
{
string sql = "select g.ID,g.GroupName,g.[Description],case ug.GroupID when g.ID then 'checked' else '' end [status] from Groups g left join UserGroup ug on g.ID=ug.GroupID and UserID=@UserID";
string k = string.Format("{0}{1}", GroupUserIDDataKey, userId);
var ret = CacheManager.GetOrAdd(k, CacheSection.RetrieveIntervalByKey(GroupUserIDDataKey), key =>
{
List<Group> Groups = new List<Group>();
DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql);
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@UserID", userId, ParameterDirection.Input));
try
{
using (DbDataReader reader = DBAccessManager.SqlDBAccess.ExecuteReader(cmd))
{
while (reader.Read())
{
Groups.Add(new Group()
{
ID = (int)reader[0],
GroupName = (string)reader[1],
Description = (string)reader[2],
Checked = (string)reader[3]
});
}
}
}
catch (Exception ex) { ExceptionManager.Publish(ex); }
return Groups;
}, CacheSection.RetrieveDescByKey(GroupUserIDDataKey));
return ret;
}
/// <summary>
/// 保存用户部门关系
/// </summary>
/// <param name="id"></param>
/// <param name="value"></param>
/// <returns></returns>
public static bool SaveGroupsByUserId(int id, string value)
{
DataTable dt = new DataTable();
dt.Columns.Add("UserID", typeof(int));
dt.Columns.Add("GroupID", typeof(int));
//判断用户是否选定角色
if (!string.IsNullOrEmpty(value))
{
string[] groupIDs = value.Split(',');
foreach (string groupID in groupIDs)
{
DataRow row = dt.NewRow();
row["UserID"] = id;
row["GroupID"] = groupID;
dt.Rows.Add(row);
}
}
string sql = "delete from UserGroup where UserID=@UserID;";
using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql))
{
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@UserID", id, ParameterDirection.Input));
using (TransactionPackage transaction = DBAccessManager.SqlDBAccess.BeginTransaction())
{
using (SqlBulkCopy bulk = new SqlBulkCopy((SqlConnection)transaction.Transaction.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)transaction.Transaction))
{
bulk.BatchSize = 1000;
bulk.DestinationTableName = "UserGroup";
bulk.ColumnMappings.Add("UserID", "UserID");
bulk.ColumnMappings.Add("GroupID", "GroupID");
bool ret = true;
try
{
DBAccessManager.SqlDBAccess.ExecuteNonQuery(cmd, transaction);
bulk.WriteToServer(dt);
transaction.CommitTransaction();
ClearCache();
}
catch (Exception ex)
{
ret = false;
transaction.RollbackTransaction();
}
return ret;
}
}
}
}
// 更新缓存 // 更新缓存
private static void ClearCache() private static void ClearCache()
{ {
CacheManager.Clear(key => key == GroupDataKey); CacheManager.Clear(key => key == GroupDataKey);
CacheManager.Clear(key => key == GroupUserIDDataKey);
} }
} }
} }

View File

@ -48,6 +48,18 @@ namespace Bootstrap.DataAccess.Tests
} }
} }
[TestMethod()]
public void RetrieveGroupsByUserIdTest()
{
var result = GroupHelper.RetrieveGroupsByUserId(1);
Assert.IsTrue(result.Count() > 0, "根据用户查询群组失败");
}
[TestMethod()]
public void SaveGroupsByUserIdTest()
{
var result = GroupHelper.SaveGroupsByUserId(1, "1,2");
Assert.IsTrue(result == true, "保存用户群组关系失败");
}
} }
} }