using System.Security.Claims; using JNPF.Common.Const; using JNPF.Common.Enums; using JNPF.Common.Extension; using JNPF.Common.Manager; using JNPF.Common.Models.Authorize; using JNPF.Common.Models.User; using JNPF.Common.Net; using JNPF.Common.Security; using JNPF.DataEncryption; using JNPF.DependencyInjection; using JNPF.Systems.Entitys.Entity.Permission; using JNPF.Systems.Entitys.Permission; using JNPF.Systems.Entitys.System; using Mapster; using Microsoft.AspNetCore.Http; using SqlSugar; namespace JNPF.Common.Core.Manager; /// /// 用户管理 . /// public partial class UserManager : IUserManager, IScoped { /// /// 用户表仓储. /// private readonly ISqlSugarRepository _repository; /// /// 缓存管理. /// private readonly ICacheManager _cacheManager; /// /// 当前Http请求. /// private readonly HttpContext _httpContext; /// /// 用户Claim主体. /// private readonly ClaimsPrincipal _user; /// /// 初始化一个类型的新实例. /// /// 用户仓储. /// 缓存管理. public UserManager( ISqlSugarRepository repository, ICacheManager cacheManager) { _repository = repository; _cacheManager = cacheManager; _httpContext = App.HttpContext; _user = _httpContext?.User; if (!string.IsNullOrEmpty(_httpContext?.Request.Query["token"].ToString())) { var token = _httpContext.Request.Query["token"].ToString(); var claims = JWTEncryption.ReadJwtToken(token.Replace("Bearer ", string.Empty).Replace("bearer ", string.Empty))?.Claims; ClaimsIdentity toKen = new ClaimsIdentity(); foreach (Claim item in claims) { toKen.AddClaim(item); } _user = new ClaimsPrincipal(toKen); } } /// /// 用户信息. /// public UserEntity User { //modify by ly on 20230920 get => _repository.CopyNew().Queryable().Single(u => u.Id == UserId); //_repository.GetSingle(u => u.Id == UserId); } /// /// 用户ID. /// public string UserId { get => _user?.FindFirst(ClaimConst.CLAINMUSERID)?.Value; } /// /// 获取用户角色. /// public List Roles { get { var user = _repository.GetSingle(u => u.Id == UserId); return GetUserRoleIds(user.RoleId, user.OrganizeId); } } /// /// 用户账号. /// public string Account { get => _user.FindFirst(ClaimConst.CLAINMACCOUNT)?.Value; } /// /// 用户昵称. /// public string RealName { get => _user.FindFirst(ClaimConst.CLAINMREALNAME)?.Value; } /// /// 当前用户 token. /// public string ToKen { get => string.IsNullOrEmpty(App.HttpContext?.Request.Headers["Authorization"]) ? App.HttpContext?.Request.Query["token"] : App.HttpContext?.Request.Headers["Authorization"]; } /// /// 数据库连接. /// public ConnectionConfigOptions ConnectionConfig { get => _user?.FindFirst(ClaimConst.CONNECTIONCONFIG)?.Value.ToObject(); } /// /// 租户ID. /// public string TenantId { get => ConnectionConfig?.ConfigId; } /// /// 租户数据库名称. /// public string TenantDbName { get => ConnectionConfig?.ConfigList?.Find(it => it.IsMaster.Equals(true)).ServiceName; } /// /// 是否是管理员. /// public bool IsAdministrator { get => _user.FindFirst(ClaimConst.CLAINMADMINISTRATOR)?.Value == ((int)AccountType.Administrator).ToString(); } /// /// 登录类型,区分Pc、Pda added by ly on 20230619 /// public string LoginType { get => _user.FindFirst(ClaimConst.LOGINTYPE)?.Value; } /// /// 获取用户的数据范围. /// public List DataScope { get { return GetUserDataScope(UserId); } } /// /// 用户当前组织及子组织. /// public List Subsidiary { get { List list = new List(); list.AddRange(GetSubsidiary(User.OrganizeId, IsAdministrator).ToObject>()); return list; } } /// /// 当前用户下属. /// public List Subordinates { get { return this.GetSubordinates(UserId).ToList(); } } /// /// 获取请求端类型 pc 、 app. /// public string UserOrigin { //modifyby zhoukeda 调用发起工作流接口取不到pc还是app 改成默认pc get { try { return _httpContext?.Request.Headers["jnpf-origin"] ?? "pc"; } catch (Exception e) { return "pc"; } } } /// /// 获取用户登录信息. /// /// public async Task GetUserInfo() { UserAgent userAgent = new UserAgent(_httpContext); var data = new UserInfoModel(); var userCache = string.Format("{0}:{1}:{2}", TenantId, CommonConst.CACHEKEYUSER, UserId); var userDataScope = await GetUserDataScopeAsync(UserId); var ipAddress = NetHelper.Ip; //var ipAddressName = await NetHelper.GetLocation(ipAddress); var sysConfigInfo = await _repository.AsSugarClient().Queryable().FirstAsync(s => s.Category.Equals("SysConfig") && s.Key.ToLower().Equals("tokentimeout")); var db = _repository.CopyNew(); data = await db.Queryable().Where(it => it.Id == UserId) .Select(a => new UserInfoModel { userId = a.Id, headIcon = SqlFunc.MergeString("/api/File/Image/userAvatar/", a.HeadIcon), userAccount = a.Account, userName = a.RealName, gender = a.Gender, organizeId = a.OrganizeId, departmentId = a.OrganizeId, departmentName = SqlFunc.Subqueryable().Where(o => o.Id == SqlFunc.ToString(a.OrganizeId) && o.Category.Equals("department")).Select(o => o.FullName), organizeName = SqlFunc.Subqueryable().Where(o => o.Id == SqlFunc.ToString(a.OrganizeId)).Select(o => o.OrganizeIdTree), managerId = a.ManagerId, isAdministrator = SqlFunc.IIF(a.IsAdministrator == 1, true, false), portalId = a.PortalId, positionId = a.PositionId, roleId = a.RoleId, prevLoginTime = a.PrevLogTime, prevLoginIPAddress = a.PrevLogIP, landline = a.Landline, telePhone = a.TelePhone, manager = SqlFunc.Subqueryable().Where(u => u.Id == a.ManagerId).Select(u => SqlFunc.MergeString(u.RealName, "/", u.Account)), mobilePhone = a.MobilePhone, email = a.Email, birthday = a.Birthday, systemId = a.SystemId, signImg = SqlFunc.Subqueryable().Where(a => a.CreatorUserId == UserId && a.IsDefault == 1).Select(a => a.SignImg), changePasswordDate = a.ChangePasswordDate, loginTime = DateTime.Now, }).FirstAsync(); if (data.portalId.IsNullOrWhiteSpace()) data.portalId = string.Empty; if (data != null && data.organizeName.IsNotEmptyOrNull()) { var orgIdTree = data?.organizeName?.Split(','); data.organizeIdList = orgIdTree.ToList(); var organizeName = await _repository.AsSugarClient().Queryable().Where(x => orgIdTree.Contains(x.Id)).OrderBy(x => x.SortCode).OrderBy(x => x.CreatorTime).Select(x => x.FullName).ToListAsync(); data.organizeName = string.Join("/", organizeName); } else { data.organizeName = data.departmentName; } data.prevLogin = (await _repository.AsSugarClient().Queryable().FirstAsync(x => x.Category.Equals("SysConfig") && x.Key.ToLower().Equals("lastlogintimeswitch"))).Value.ParseToInt(); data.loginIPAddress = ipAddress; //data.loginIPAddressName = ipAddressName; //data.prevLoginIPAddressName = await NetHelper.GetLocation(data.prevLoginIPAddress); data.loginPlatForm = userAgent.RawValue; data.subsidiary = await GetSubsidiaryAsync(data.organizeId, data.isAdministrator); data.subordinates = await this.GetSubordinatesAsync(UserId); data.positionIds = data.positionId == null ? null : await GetPosition(data.positionId); data.positionName = data.positionIds == null ? null : string.Join(",", data.positionIds.Select(it => it.name)); var roleList = await GetUserOrgRoleIds(data.roleId, data.organizeId); data.roleName = await GetRoleNameByIds(string.Join(",", roleList)); data.roleIds = roleList.ToArray(); if (!data.isAdministrator && data.roleIds.Any()) { var portalIds = await _repository.AsSugarClient().Queryable().In(a => a.ObjectId, data.roleIds).Where(a => a.ItemType == "portal").GroupBy(it => new { it.ItemId }).Select(it => it.ItemId).ToListAsync(); if (portalIds.Any()) { if (!portalIds.Any(x => x == data.portalId)) data.portalId = portalIds.FirstOrDefault()?.ToString(); } else data.portalId = string.Empty; } data.overdueTime = TimeSpan.FromMinutes(sysConfigInfo.Value.ParseToDouble()); data.dataScope = userDataScope; data.tenantId = TenantId; data.tenantDbName = TenantDbName; // 根据系统配置过期时间自动过期 await SetUserInfo(userCache, data, TimeSpan.FromMinutes(sysConfigInfo.Value.ParseToDouble())); return data; } /// /// 获取用户数据范围. /// /// 用户ID. /// private async Task> GetUserDataScopeAsync(string userId) { List data = new List(); List subData = new List(); List inteList = new List(); var list = await _repository.AsSugarClient().Queryable().Where(it => SqlFunc.ToString(it.UserId) == userId && it.DeleteMark == null).ToListAsync(); // 填充数据 foreach (var item in list) { if (item.SubLayerAdd.ParseToBool() || item.SubLayerEdit.ParseToBool() || item.SubLayerDelete.ParseToBool()) { var subsidiary = (await GetSubsidiaryAsync(item.OrganizeId, false)).ToList(); subsidiary.Remove(item.OrganizeId); subsidiary.ToList().ForEach(it => { subData.Add(new UserDataScopeModel() { organizeId = it, Add = item.SubLayerAdd.ParseToBool(), Edit = item.SubLayerEdit.ParseToBool(), Delete = item.SubLayerDelete.ParseToBool() }); }); } if (item.ThisLayerAdd.ParseToBool() || item.ThisLayerEdit.ParseToBool() || item.ThisLayerDelete.ParseToBool()) { data.Add(new UserDataScopeModel() { organizeId = item.OrganizeId, Add = item.ThisLayerAdd.ParseToBool(), Edit = item.ThisLayerEdit.ParseToBool(), Delete = item.ThisLayerDelete.ParseToBool() }); } } /* 比较数据 所有分级数据权限以本级权限为主 子级为辅 将本级数据与子级数据对比 对比出子级数据内组织ID存在本级数据的组织ID*/ var intersection = data.Select(it => it.organizeId).Intersect(subData.Select(it => it.organizeId)).ToList(); intersection.ForEach(it => { var parent = data.Find(item => item.organizeId == it); var child = subData.Find(item => item.organizeId == it); var add = false; var edit = false; var delete = false; if (parent.Add || child.Add) add = true; if (parent.Edit || child.Edit) edit = true; if (parent.Delete || child.Delete) delete = true; inteList.Add(new UserDataScopeModel() { organizeId = it, Add = add, Edit = edit, Delete = delete }); data.Remove(parent); subData.Remove(child); }); return data.Union(subData).Union(inteList).ToList(); } /// /// 获取用户数据范围. /// /// 用户ID. /// private List GetUserDataScope(string userId) { List data = new List(); List subData = new List(); List inteList = new List(); // 填充数据 foreach (var item in _repository.AsSugarClient().Queryable() .Where(it => SqlFunc.ToString(it.UserId) == userId && it.DeleteMark == null).ToList()) { if (item.SubLayerSelect.ParseToBool() || item.SubLayerAdd.ParseToBool() || item.SubLayerEdit.ParseToBool() || item.SubLayerDelete.ParseToBool()) { var subsidiary = GetSubsidiary(item.OrganizeId, false).ToList(); subsidiary.Remove(item.OrganizeId); subsidiary.ToList().ForEach(it => { subData.Add(new UserDataScopeModel() { organizeId = it, Add = item.SubLayerAdd.ParseToBool(), Edit = item.SubLayerEdit.ParseToBool(), Delete = item.SubLayerDelete.ParseToBool(), Select = item.SubLayerSelect.ParseToBool() }); }); } if (item.ThisLayerSelect.ParseToBool() || item.ThisLayerAdd.ParseToBool() || item.ThisLayerEdit.ParseToBool() || item.ThisLayerDelete.ParseToBool()) { data.Add(new UserDataScopeModel() { organizeId = item.OrganizeId, Add = item.ThisLayerAdd.ParseToBool(), Edit = item.ThisLayerEdit.ParseToBool(), Delete = item.ThisLayerDelete.ParseToBool(), Select = item.ThisLayerSelect.ParseToBool() }); } } /* 比较数据 所有分级数据权限以本级权限为主 子级为辅 将本级数据与子级数据对比 对比出子级数据内组织ID存在本级数据的组织ID*/ var intersection = data.Select(it => it.organizeId).Intersect(subData.Select(it => it.organizeId)).ToList(); intersection.ForEach(it => { var parent = data.Find(item => item.organizeId == it); var child = subData.Find(item => item.organizeId == it); var add = false; var edit = false; var delete = false; var select = false; if (parent.Add || child.Add) add = true; if (parent.Edit || child.Edit) edit = true; if (parent.Delete || child.Delete) delete = true; if (parent.Select || child.Select) select = true; inteList.Add(new UserDataScopeModel() { organizeId = it, Add = add, Edit = edit, Delete = delete, Select = select }); data.Remove(parent); subData.Remove(child); }); return data.Union(subData).Union(inteList).ToList(); } /// /// 获取数据条件. /// /// 实体. /// 模块ID. /// 表主键. /// 是否开启数据权限. /// 联表编号. /// public async Task> GetConditionAsync(string moduleId, string primaryKey = "F_Id", bool isDataPermissions = true, string tableNumber = "") where T : new() { var userInfo = await GetUserInfo(); var conModels = new List(); if (IsAdministrator) return conModels; var items = await _repository.AsSugarClient().Queryable((a, b) => new JoinQueryInfos(JoinType.Left, b.Id == a.ObjectId && b.EnabledMark == 1 && b.DeleteMark == null)) .In((a, b) => b.Id, userInfo.roleIds) .Where(a => a.ItemType == "resource") .GroupBy(a => new { a.ItemId }).Select(a => a.ItemId).ToListAsync(); if (!isDataPermissions) { conModels.Add(new ConditionalCollections() { ConditionalList = new List>() { new KeyValuePair(WhereType.And, new ConditionalModel() { FieldName = string.Format("{0}{1}", tableNumber, primaryKey), ConditionalType = ConditionalType.NoEqual, FieldValue = "0", FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(string)) }) } }); return conModels; } else if (items.Count == 0 && isDataPermissions) { conModels.Add(new ConditionalCollections() { ConditionalList = new List>() { new KeyValuePair(WhereType.And, new ConditionalModel() { FieldName = string.Format("{0}{1}", tableNumber, primaryKey), ConditionalType = ConditionalType.Equal, FieldValue = "0", FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(string)) }) } }); return conModels; } var resourceList = _repository.AsSugarClient().Queryable().In(it => it.Id, items).Where(it => it.ModuleId == moduleId && it.DeleteMark == null).ToList(); if (resourceList.Any(x => x.AllData == 1 || "jnpf_alldata".Equals(x.EnCode))) { conModels.Add(new ConditionalCollections() { ConditionalList = new List>() { new KeyValuePair(WhereType.And, new ConditionalModel() { FieldName = string.Format("{0}{1}", tableNumber, primaryKey), ConditionalType = ConditionalType.NoEqual, FieldValue = "0", FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(string)) }) } }); } else { var allList = new List(); // 构造任何层级的条件 var resultList = new List(); foreach (var item in resourceList) { var groupsList = new List(); foreach (var conditionItem in item.ConditionJson.ToList()) { var conditionalList = new List(); foreach (var fieldItem in conditionItem.Groups) { var itemField = string.Format("{0}{1}", tableNumber, fieldItem.Field); var itemValue = fieldItem.Value; var itemMethod = (QueryType)System.Enum.Parse(typeof(QueryType), fieldItem.Op); var cmodel = GetConditionalModel(itemMethod, itemField, User.OrganizeId); if (itemMethod.Equals(QueryType.Equal)) cmodel.ConditionalType = ConditionalType.Like; if (itemMethod.Equals(QueryType.NotEqual)) cmodel.ConditionalType = ConditionalType.NoLike; switch (itemValue) { case "@userId": // 当前用户 { switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = userInfo.userId, ConditionalType = (int)cmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = userInfo.userId, ConditionalType = (int)cmodel.ConditionalType } }); break; } } break; case "@userAraSubordinates": // 当前用户集下属 { var ids = new List() { userInfo.userId }; ids.AddRange(userInfo.subordinates); for (int i = 0; i < ids.Count; i++) { if (i == 0) { switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; } } else { if (itemMethod.Equals(QueryType.NotEqual) || itemMethod.Equals(QueryType.NotIncluded)) conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); else conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); } } } break; case "@organizeId": // 当前组织 { if (!string.IsNullOrEmpty(userInfo.organizeId)) { switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = userInfo.organizeId, ConditionalType = (int)cmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = userInfo.organizeId, ConditionalType = (int)cmodel.ConditionalType } }); break; } } } break; case "@organizationAndSuborganization": // 当前组织及子组织 { if (!string.IsNullOrEmpty(userInfo.organizeId)) { var ids = new List() { userInfo.organizeId }; ids.AddRange(userInfo.subsidiary); for (int i = 0; i < ids.Count; i++) { if (i == 0) { switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; } } else { if (itemMethod.Equals(QueryType.NotEqual) || itemMethod.Equals(QueryType.NotIncluded)) conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); else conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); } } } } break; case "@branchManageOrganize": // 当前分管组织 { var ids = DataScope.Where(x => x.Select).Select(x => x.organizeId).ToList(); if (ids != null) { for (int i = 0; i < ids.Count; i++) { if (i == 0) { switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; } } else { if (itemMethod.Equals(QueryType.NotEqual) || itemMethod.Equals(QueryType.NotIncluded)) conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); else conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); } } } else { conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = "jnpf", ConditionalType = (int)ConditionalType.Equal } }); } } break; case "@branchManageOrganizeAndSub": // 当前分管组织及子组织 { var ids = new List(); DataScope.Where(x => x.Select).Select(x => x.organizeId).ToList() .ForEach(item => ids.AddRange(_repository.AsSugarClient().Queryable().Where(x => x.OrganizeIdTree.Contains(item)).Select(x => x.Id).ToList())); if (ids.Any()) { for (int i = 0; i < ids.Count; i++) { if (i == 0) { switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; } } else { if (itemMethod.Equals(QueryType.NotEqual) || itemMethod.Equals(QueryType.NotIncluded)) conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); else conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); } } } else { conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = "jnpf", ConditionalType = (int)ConditionalType.Equal } }); } } break; default: { if (!string.IsNullOrEmpty(itemValue)) { var defCmodel = GetConditionalModel(itemMethod, itemField, itemValue, fieldItem.Type); if (defCmodel.ConditionalType.Equals(ConditionalType.In)) defCmodel.ConditionalType = ConditionalType.Like; if (defCmodel.ConditionalType.Equals(ConditionalType.NotIn)) defCmodel.ConditionalType = ConditionalType.NoLike; switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = itemValue, ConditionalType = (int)cmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = itemValue, ConditionalType = (int)cmodel.ConditionalType } }); break; } } } break; } if (itemMethod.Equals(QueryType.NotEqual) || itemMethod.Equals(QueryType.NotIncluded)) conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = string.Empty, ConditionalType = ConditionalType.IsNullOrEmpty } }); } if (conditionalList.Any()) { var firstItem = conditionalList.First().ToObject(); firstItem.Key = 0; conditionalList[0] = firstItem; groupsList.Add(new { Key = (int)WhereType.And, Value = new { ConditionalList = conditionalList } }); } } if (groupsList.Any()) allList.Add(new { Key = (int)WhereType.And, Value = new { ConditionalList = groupsList } }); } if (allList.Any()) resultList.Add(new { ConditionalList = allList }); if (resultList.Any()) conModels.AddRange(_repository.AsSugarClient().Utilities.JsonToConditionalModels(resultList.ToJsonString())); } if (resourceList.Count == 0) { conModels.Add(new ConditionalCollections() { ConditionalList = new List>() { new KeyValuePair(WhereType.And, new ConditionalModel() { FieldName = string.Format("{0}{1}", tableNumber, primaryKey), ConditionalType = ConditionalType.Equal, FieldValue = "0", FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(string)) }) } }); } return conModels; } /// /// 获取数据条件. /// /// 实体. /// 模块ID. /// 表主键. /// 是否开启数据权限. /// public async Task> GetDataConditionAsync(string moduleId, string primaryKey, bool isDataPermissions = true) where T : new() { var userInfo = await GetUserInfo(); var conModels = new List(); if (IsAdministrator) return conModels; var items = await _repository.AsSugarClient().Queryable((a, b) => new JoinQueryInfos(JoinType.Left, b.Id == a.ObjectId && b.EnabledMark == 1 && b.DeleteMark == null)) .In((a, b) => b.Id, userInfo.roleIds) .Where(a => a.ItemType == "resource") .GroupBy(a => new { a.ItemId }).Select(a => a.ItemId).ToListAsync(); if (!isDataPermissions) { conModels.Add(new ConditionalCollections() { ConditionalList = new List>() { new KeyValuePair(WhereType.And, new ConditionalModel() { FieldName = primaryKey, ConditionalType = ConditionalType.NoEqual, FieldValue = "0", FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(string)) }) } }); return conModels; } else if (items.Count == 0 && isDataPermissions) { conModels.Add(new ConditionalCollections() { ConditionalList = new List>() { new KeyValuePair(WhereType.And, new ConditionalModel() { FieldName = primaryKey, ConditionalType = ConditionalType.Equal, FieldValue = "0", FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(string)) }) } }); return conModels; } var resourceList = _repository.AsSugarClient().Queryable().In(it => it.Id, items).Where(it => it.ModuleId == moduleId && it.DeleteMark == null).ToList(); if (resourceList.Any(x => x.AllData == 1 || x.EnCode.Equals("jnpf_alldata"))) { conModels.Add(new ConditionalCollections() { ConditionalList = new List>() { new KeyValuePair(WhereType.And, new ConditionalModel() { FieldName = primaryKey, ConditionalType = ConditionalType.NoEqual, FieldValue = "0", FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(string)) }) } }); } else { var allList = new List(); // 构造任何层级的条件 var resultList = new List(); foreach (var item in resourceList) { var groupsList = new List(); foreach (var conditionItem in item.ConditionJson.ToList()) { var conditionalList = new List(); foreach (var fieldItem in conditionItem.Groups) { var itemField = string.IsNullOrEmpty(fieldItem.BindTable) ? fieldItem.Field : string.Format("{0}.{1}", fieldItem.BindTable, fieldItem.Field); var itemValue = fieldItem.Value; var itemMethod = (QueryType)System.Enum.Parse(typeof(QueryType), fieldItem.Op); var cmodel = GetConditionalModel(itemMethod, itemField, User.OrganizeId); if (itemMethod.Equals(QueryType.Equal)) cmodel.ConditionalType = ConditionalType.Like; if (itemMethod.Equals(QueryType.NotEqual)) cmodel.ConditionalType = ConditionalType.NoLike; switch (itemValue) { case "@userId": // 当前用户 { switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = UserId, ConditionalType = (int)cmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = UserId, ConditionalType = (int)cmodel.ConditionalType } }); break; } } break; case "@userAraSubordinates": // 当前用户集下属 { var ids = new List() { UserId }; ids.AddRange(Subordinates); for (int i = 0; i < ids.Count; i++) { if (i == 0) { switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; } } else { if (itemMethod.Equals(QueryType.NotEqual) || itemMethod.Equals(QueryType.NotIncluded)) conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); else conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); } } } break; case "@organizeId": // 当前组织 { if (!string.IsNullOrEmpty(User.OrganizeId)) { switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = User.OrganizeId, ConditionalType = (int)cmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = User.OrganizeId, ConditionalType = (int)cmodel.ConditionalType } }); break; } } } break; case "@organizationAndSuborganization": // 当前组织及子组织 { if (!string.IsNullOrEmpty(User.OrganizeId)) { var ids = new List() { User.OrganizeId }; ids.AddRange(Subsidiary); for (int i = 0; i < ids.Count; i++) { if (i == 0) { switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; } } else { if (itemMethod.Equals(QueryType.NotEqual) || itemMethod.Equals(QueryType.NotIncluded)) conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); else conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); } } } } break; case "@branchManageOrganize": // 当前分管组织 { var ids = DataScope.Where(x => x.Select).Select(x => x.organizeId).ToList(); if (ids != null) { for (int i = 0; i < ids.Count; i++) { if (i == 0) { switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; } } else { if (itemMethod.Equals(QueryType.NotEqual) || itemMethod.Equals(QueryType.NotIncluded)) conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); else conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); } } } else { conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = "jnpf", ConditionalType = (int)ConditionalType.Equal } }); } } break; case "@branchManageOrganizeAndSub": // 当前分管组织及子组织 { var ids = new List(); DataScope.Where(x => x.Select).Select(x => x.organizeId).ToList() .ForEach(item => ids.AddRange(_repository.AsSugarClient().Queryable().Where(x => x.OrganizeIdTree.Contains(item)).Select(x => x.Id).ToList())); if (ids.Any()) { for (int i = 0; i < ids.Count; i++) { if (i == 0) { switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; } } else { if (itemMethod.Equals(QueryType.NotEqual) || itemMethod.Equals(QueryType.NotIncluded)) conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); else conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); } } } else { conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = "jnpf", ConditionalType = (int)ConditionalType.Equal } }); } } break; default: { if (!string.IsNullOrEmpty(itemValue)) { var defCmodel = GetConditionalModel(itemMethod, itemField, itemValue, fieldItem.Type); if (defCmodel.ConditionalType.Equals(ConditionalType.In)) defCmodel.ConditionalType = ConditionalType.Like; if (defCmodel.ConditionalType.Equals(ConditionalType.NotIn)) defCmodel.ConditionalType = ConditionalType.NoLike; switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = itemValue, ConditionalType = (int)defCmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = itemValue, ConditionalType = (int)defCmodel.ConditionalType } }); break; } } } break; } if (itemMethod.Equals(QueryType.NotEqual) || itemMethod.Equals(QueryType.NotIncluded)) conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = string.Empty, ConditionalType = ConditionalType.IsNullOrEmpty } }); } if (conditionalList.Any()) { var firstItem = conditionalList.First().ToObject(); firstItem.Key = 0; conditionalList[0] = firstItem; groupsList.Add(new { Key = (int)WhereType.And, Value = new { ConditionalList = conditionalList } }); } } if (groupsList.Any()) allList.Add(new { Key = (int)WhereType.And, Value = new { ConditionalList = groupsList } }); } if (allList.Any()) resultList.Add(new { ConditionalList = allList }); if (resultList.Any()) conModels.AddRange(_repository.AsSugarClient().Utilities.JsonToConditionalModels(resultList.ToJsonString())); } if (resourceList.Count == 0) { conModels.Add(new ConditionalCollections() { ConditionalList = new List>() { new KeyValuePair(WhereType.And, new ConditionalModel() { FieldName = primaryKey, ConditionalType = ConditionalType.Equal, FieldValue = "0", FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(string)) }) } }); } return conModels; } /// /// 获取代码生成数据条件. /// /// 实体. /// 模块ID. /// 表主键. /// 是否开启数据权限. /// public async Task> GetCodeGenAuthorizeModuleResource(string moduleId, string primaryKey, bool isDataPermissions = true) where T : new() { var codeGenConditional = new List() { new CodeGenAuthorizeModuleResourceModel { FieldRule = 0, conditionalModel = new List() } }; if (IsAdministrator) return codeGenConditional; // 管理员全部放开 var items = await _repository.AsSugarClient().Queryable((a, b) => new JoinQueryInfos(JoinType.Left, b.Id == a.ObjectId && b.EnabledMark == 1 && b.DeleteMark == null)) .In((a, b) => b.Id, Roles) .Where(a => a.ItemType == "resource") .GroupBy(a => new { a.ItemId }).Select(a => a.ItemId).ToListAsync(); switch (isDataPermissions) { case true: // 开启权限 但是没有权限资源. switch (items.Count) { case 0: codeGenConditional.Find(it => it.FieldRule.Equals(0)).conditionalModel.Add(new ConditionalCollections() { ConditionalList = new List>() { new KeyValuePair(WhereType.And, new ConditionalModel() { FieldName = primaryKey, ConditionalType = ConditionalType.Equal, FieldValue = "0", FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(string)) }) } }); break; } break; default: // 未开启数据权限 codeGenConditional.Find(it => it.FieldRule.Equals(0)).conditionalModel.Add(new ConditionalCollections() { ConditionalList = new List>() { new KeyValuePair(WhereType.And, new ConditionalModel() { FieldName = primaryKey, ConditionalType = ConditionalType.NoEqual, FieldValue = "0", FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(string)) }) } }); break; } var resourceList = await _repository.AsSugarClient().Queryable().In(it => it.Id, items).Where(it => it.ModuleId == moduleId && it.DeleteMark == null).ToListAsync(); // 权限资源是否为全部数据. switch (resourceList?.Any(x => x.AllData == 1 || x.EnCode.Equals("jnpf_alldata"))) { case true: codeGenConditional.Find(it => it.FieldRule.Equals(0)).conditionalModel.Add(new ConditionalCollections() { ConditionalList = new List>() { new KeyValuePair(WhereType.And, new ConditionalModel() { FieldName = primaryKey, ConditionalType = ConditionalType.NoEqual, FieldValue = "0", FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(string)) }) } }); break; case false: switch (resourceList.Count) { case 0: codeGenConditional.Find(it => it.FieldRule.Equals(0)).conditionalModel.Add(new ConditionalCollections() { ConditionalList = new List>() { new KeyValuePair(WhereType.And, new ConditionalModel() { FieldName = primaryKey, ConditionalType = ConditionalType.Equal, FieldValue = "0", FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(string)) }) } }); break; default: codeGenConditional = new List(); var allList = new List(); // 构造任何层级的条件 var resultList = new List(); var codeGenConditionalObject = new List(); foreach (var item in resourceList) { var groupsList = new List(); var fieldRule = 0; var tableName = string.Empty; foreach (var conditionItem in item.ConditionJson.ToList()) { var conditionalList = new List(); foreach (var fieldItem in conditionItem.Groups) { fieldRule = fieldItem.FieldRule; tableName = string.IsNullOrEmpty(fieldItem.BindTable) ? fieldItem.Field.Split('.').First() : fieldItem.BindTable; if (!codeGenConditionalObject.Any(it => it.FieldRule == fieldRule && it.TableName == tableName)) { codeGenConditionalObject.Add(new CodeGenAuthorizeModuleResource() { FieldRule = fieldRule, TableName = tableName, conditionalModel = new List() }); } var itemField = fieldRule == 0 ? fieldItem.Field : (string.IsNullOrEmpty(fieldItem.BindTable) ? fieldItem.Field.Split('.').Last() : fieldItem.Field); var itemValue = fieldItem.Value; var itemMethod = (QueryType)System.Enum.Parse(typeof(QueryType), fieldItem.Op); var cmodel = GetConditionalModel(itemMethod, itemField, User.OrganizeId); if (itemMethod.Equals(QueryType.Equal)) cmodel.ConditionalType = ConditionalType.Like; if (itemMethod.Equals(QueryType.NotEqual)) cmodel.ConditionalType = ConditionalType.NoLike; switch (itemValue) { case "@userId": // 当前用户 { switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = UserId, ConditionalType = (int)cmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = UserId, ConditionalType = (int)cmodel.ConditionalType } }); break; } } break; case "@userAraSubordinates": // 当前用户集下属 { var ids = new List() { UserId }; ids.AddRange(Subordinates); for (int i = 0; i < ids.Count; i++) { if (i == 0) { switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; } } else { if (itemMethod.Equals(QueryType.NotEqual) || itemMethod.Equals(QueryType.NotIncluded)) conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); else conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); } } } break; case "@organizeId": // 当前组织 { if (!string.IsNullOrEmpty(User.OrganizeId)) { switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = User.OrganizeId, ConditionalType = (int)cmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = User.OrganizeId, ConditionalType = (int)cmodel.ConditionalType } }); break; } } } break; case "@organizationAndSuborganization": // 当前组织及子组织 { if (!string.IsNullOrEmpty(User.OrganizeId)) { var ids = new List() { User.OrganizeId }; ids.AddRange(Subsidiary); for (int i = 0; i < ids.Count; i++) { if (i == 0) { switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; } } else { if (itemMethod.Equals(QueryType.NotEqual) || itemMethod.Equals(QueryType.NotIncluded)) conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); else conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); } } } } break; case "@branchManageOrganize": // 当前分管组织 { var ids = DataScope.Where(x => x.Select).Select(x => x.organizeId).ToList(); if (ids != null) { for (int i = 0; i < ids.Count; i++) { if (i == 0) { switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; } } else { if (itemMethod.Equals(QueryType.NotEqual) || itemMethod.Equals(QueryType.NotIncluded)) conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); else conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); } } } else { conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = "jnpf", ConditionalType = (int)ConditionalType.Equal } }); } } break; case "@branchManageOrganizeAndSub": // 当前分管组织及子组织 { var ids = new List(); DataScope.Where(x => x.Select).Select(x => x.organizeId).ToList() .ForEach(item => ids.AddRange(_repository.AsSugarClient().Queryable().Where(x => x.OrganizeIdTree.Contains(item)).Select(x => x.Id).ToList())); if (ids.Any()) { for (int i = 0; i < ids.Count; i++) { if (i == 0) { switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; } } else { if (itemMethod.Equals(QueryType.NotEqual) || itemMethod.Equals(QueryType.NotIncluded)) conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); else conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); } } } else { conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = "jnpf", ConditionalType = (int)ConditionalType.Equal } }); } } break; default: { if (!string.IsNullOrEmpty(itemValue)) { var defCmodel = GetConditionalModel(itemMethod, itemField, itemValue, fieldItem.Type); if (defCmodel.ConditionalType.Equals(ConditionalType.In)) defCmodel.ConditionalType = ConditionalType.Like; if (defCmodel.ConditionalType.Equals(ConditionalType.NotIn)) defCmodel.ConditionalType = ConditionalType.NoLike; switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = itemValue, ConditionalType = (int)defCmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = itemValue, ConditionalType = (int)defCmodel.ConditionalType } }); break; } } } break; } if (itemMethod.Equals(QueryType.NotEqual) || itemMethod.Equals(QueryType.NotIncluded)) conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = string.Empty, ConditionalType = ConditionalType.IsNullOrEmpty } }); codeGenConditionalObject.Find(it => it.FieldRule == fieldRule && it.TableName.Equals(tableName)).conditionalModel.AddRange(conditionalList); } if (codeGenConditionalObject.Any()) { var firstItem = codeGenConditionalObject.Find(it => it.FieldRule.Equals(fieldRule) && it.TableName.Equals(tableName)).conditionalModel.First().ToObject(); firstItem.Key = 0; conditionalList[0] = firstItem; groupsList.Add(new { Key = (int)WhereType.And, Value = new { ConditionalList = codeGenConditionalObject.Find(it => it.FieldRule == fieldRule && it.TableName.Equals(tableName)).conditionalModel } }); codeGenConditionalObject.Find(it => it.FieldRule.Equals(fieldRule) && it.TableName.Equals(tableName)).conditionalModel = groupsList; groupsList = new List(); } } if (codeGenConditionalObject.Any()) { allList.Add(new { Key = (int)WhereType.And, Value = new { ConditionalList = codeGenConditionalObject.Find(it => it.FieldRule.Equals(fieldRule) && it.TableName.Equals(tableName)).conditionalModel } }); codeGenConditionalObject.Find(it => it.FieldRule.Equals(fieldRule) && it.TableName.Equals(tableName)).conditionalModel = allList; allList = new List(); } } if (codeGenConditionalObject.Any()) { foreach (var conditional in codeGenConditionalObject) { resultList.Add(new { ConditionalList = conditional.conditionalModel }); conditional.conditionalModel = resultList; resultList = new List(); } } if (codeGenConditionalObject.Any()) { foreach (var conditional in codeGenConditionalObject) { if (!codeGenConditional.Any(it => it.FieldRule == conditional.FieldRule && it.TableName.Equals(conditional.TableName))) { codeGenConditional.Add(new CodeGenAuthorizeModuleResourceModel { FieldRule = conditional.FieldRule, TableName = conditional.TableName, conditionalModel = new List() }); } codeGenConditional.Find(it => it.FieldRule.Equals(conditional.FieldRule) && it.TableName.Equals(conditional.TableName)).conditionalModel = _repository.AsSugarClient().Utilities.JsonToConditionalModels(conditional.conditionalModel.ToJsonString()); } } break; } break; } return codeGenConditional.FindAll(it => it.conditionalModel.Count > 0); } /// /// 获取数据条件(在线开发专用) . /// /// 实体. /// 表主键. /// 模块ID. /// 是否开启数据权限. /// public async Task> GetCondition(string primaryKey, string moduleId, bool isDataPermissions = true) where T : new() { var conModels = new List(); if (IsAdministrator) return conModels; // 管理员全部放开 var items = _repository.AsSugarClient().Queryable((a, b) => new JoinQueryInfos(JoinType.Left, b.Id == a.ObjectId && b.EnabledMark == 1 && b.DeleteMark == null)) .In((a, b) => b.Id, Roles) .Where(a => a.ItemType == "resource") .GroupBy(a => new { a.ItemId }).Select(a => a.ItemId).ToList(); if (!isDataPermissions) { conModels.Add(new ConditionalCollections() { ConditionalList = new List>() { new KeyValuePair(WhereType.And, new ConditionalModel() { FieldName = primaryKey, ConditionalType = ConditionalType.NoEqual, FieldValue = "0", FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(string)) }) } }); return conModels; } else if (items.Count == 0 && isDataPermissions) { conModels.Add(new ConditionalCollections() { ConditionalList = new List>() { new KeyValuePair(WhereType.And, new ConditionalModel() { FieldName = primaryKey, ConditionalType = ConditionalType.Equal, FieldValue = "0", FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(string)) }) } }); return conModels; } var resourceList = _repository.AsSugarClient().Queryable().In(it => it.Id, items).Where(it => it.ModuleId == moduleId && it.DeleteMark == null).ToList(); if (resourceList.Any(x => x.AllData == 1 || x.EnCode.Equals("jnpf_alldata"))) { conModels.Add(new ConditionalCollections() { ConditionalList = new List>() { new KeyValuePair(WhereType.And, new ConditionalModel() { FieldName = primaryKey, ConditionalType = ConditionalType.NoEqual, FieldValue = "0", FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(string)) }) } }); } else { var allList = new List(); // 构造任何层级的条件 var resultList = new List(); foreach (var item in resourceList) { var groupsList = new List(); foreach (var conditionItem in item.ConditionJson.ToList()) { var conditionalList = new List(); foreach (var fieldItem in conditionItem.Groups) { var itemField = fieldItem.BindTable.IsNullOrWhiteSpace() ? fieldItem.Field : string.Format("{0}.{1}", fieldItem.BindTable, fieldItem.Field); var itemValue = fieldItem.Value; var itemMethod = (QueryType)System.Enum.Parse(typeof(QueryType), fieldItem.Op); var cmodel = GetConditionalModel(itemMethod, itemField, User.OrganizeId); if (itemMethod.Equals(QueryType.Equal)) cmodel.ConditionalType = ConditionalType.Like; if (itemMethod.Equals(QueryType.NotEqual)) cmodel.ConditionalType = ConditionalType.NoLike; switch (itemValue) { case "@userId": // 当前用户 { switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = UserId, ConditionalType = (int)cmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = UserId, ConditionalType = (int)cmodel.ConditionalType } }); break; } } break; case "@userAraSubordinates": // 当前用户集下属 { var ids = new List() { UserId }; ids.AddRange(Subordinates); for (int i = 0; i < ids.Count; i++) { if (i == 0) { switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; } } else { if (itemMethod.Equals(QueryType.NotEqual) || itemMethod.Equals(QueryType.NotIncluded)) conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); else conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); } } } break; case "@organizeId": // 当前组织 { if (!string.IsNullOrEmpty(User.OrganizeId)) { switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = User.OrganizeId, ConditionalType = (int)cmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = User.OrganizeId, ConditionalType = (int)cmodel.ConditionalType } }); break; } } } break; case "@organizationAndSuborganization": // 当前组织及子组织 { if (!string.IsNullOrEmpty(User.OrganizeId)) { var ids = new List() { User.OrganizeId }; ids.AddRange(Subsidiary); for (int i = 0; i < ids.Count; i++) { if (i == 0) { switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; } } else { if (itemMethod.Equals(QueryType.NotEqual) || itemMethod.Equals(QueryType.NotIncluded)) conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); else conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); } } } } break; case "@branchManageOrganize": // 当前分管组织 { var ids = DataScope.Where(x => x.Select).Select(x => x.organizeId).ToList(); if (ids != null) { for (int i = 0; i < ids.Count; i++) { if (i == 0) { switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; } } else { if (itemMethod.Equals(QueryType.NotEqual) || itemMethod.Equals(QueryType.NotIncluded)) conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); else conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); } } } else { conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = "jnpf", ConditionalType = (int)ConditionalType.Equal } }); } } break; case "@branchManageOrganizeAndSub": // 当前分管组织及子组织 { var ids = new List(); DataScope.Where(x => x.Select).Select(x => x.organizeId).ToList() .ForEach(item => ids.AddRange(_repository.AsSugarClient().Queryable().Where(x => x.OrganizeIdTree.Contains(item)).Select(x => x.Id).ToList())); if (ids.Any()) { for (int i = 0; i < ids.Count; i++) { if (i == 0) { switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); break; } } else { if (itemMethod.Equals(QueryType.NotEqual) || itemMethod.Equals(QueryType.NotIncluded)) conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); else conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = ids[i], ConditionalType = (int)cmodel.ConditionalType } }); } } } else { conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = "jnpf", ConditionalType = (int)ConditionalType.Equal } }); } } break; default: { if (!string.IsNullOrEmpty(itemValue)) { var defCmodel = GetConditionalModel(itemMethod, itemField, itemValue, fieldItem.Type); if (defCmodel.ConditionalType.Equals(ConditionalType.In)) defCmodel.ConditionalType = ConditionalType.Like; if (defCmodel.ConditionalType.Equals(ConditionalType.NotIn)) defCmodel.ConditionalType = ConditionalType.NoLike; switch (conditionItem.Logic) { case "and": conditionalList.Add(new { Key = (int)WhereType.And, Value = new { FieldName = itemField, FieldValue = itemValue, ConditionalType = (int)defCmodel.ConditionalType } }); break; case "or": conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = itemValue, ConditionalType = (int)defCmodel.ConditionalType } }); break; } } } break; } if (itemMethod.Equals(QueryType.NotEqual) || itemMethod.Equals(QueryType.NotIncluded)) conditionalList.Add(new { Key = (int)WhereType.Or, Value = new { FieldName = itemField, FieldValue = string.Empty, ConditionalType = ConditionalType.IsNullOrEmpty } }); } if (conditionalList.Any()) { var firstItem = conditionalList.First().ToObject(); firstItem.Key = 0; conditionalList[0] = firstItem; groupsList.Add(new { Key = (int)WhereType.And, Value = new { ConditionalList = conditionalList } }); } } if (groupsList.Any()) allList.Add(new { Key = (int)WhereType.And, Value = new { ConditionalList = groupsList } }); } if (allList.Any()) resultList.Add(new { ConditionalList = allList }); if (resultList.Any()) conModels.AddRange(_repository.AsSugarClient().Utilities.JsonToConditionalModels(resultList.ToJsonString())); } if (resourceList.Count == 0) { conModels.Add(new ConditionalCollections() { ConditionalList = new List>() { new KeyValuePair(WhereType.And, new ConditionalModel() { FieldName = primaryKey, ConditionalType = ConditionalType.Equal, FieldValue = "0", FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(string)) }) } }); } return conModels; } /// /// 下属机构. /// /// 机构ID. /// 是否管理员. /// private async Task GetSubsidiaryAsync(string organizeId, bool isAdmin) { var data = await _repository.AsSugarClient().Queryable().Where(it => it.DeleteMark == null && it.EnabledMark.Equals(1)).ToListAsync(); if (!isAdmin) data = data.TreeChildNode(organizeId, t => t.Id, t => t.ParentId); return data.Select(m => m.Id).ToArray(); } /// /// 下属机构. /// /// 机构ID. /// 是否管理员. /// private string[] GetSubsidiary(string organizeId, bool isAdmin) { var data = _repository.AsSugarClient().Queryable().Where(it => it.DeleteMark == null && it.EnabledMark.Equals(1)).ToList(); if (!isAdmin) data = data.TreeChildNode(organizeId, t => t.Id, t => t.ParentId); return data.Select(m => m.Id).ToArray(); } /// /// 获取下属. /// /// 主管Id. /// private async Task GetSubordinatesAsync(string managerId) { List data = new List(); var userIds = await _repository.AsQueryable().Where(m => m.ManagerId == managerId && m.DeleteMark == null).Select(m => m.Id).ToListAsync(); data.AddRange(userIds); // 关闭无限级我的下属 // data.AddRange(await GetInfiniteSubordinats(userIds.ToArray())); return data.ToArray(); } /// /// 获取下属. /// /// 主管Id. /// private string[] GetSubordinates(string managerId) { List data = new List(); var userIds = _repository.AsQueryable().Where(m => m.ManagerId == managerId && m.DeleteMark == null).Select(m => m.Id).ToList(); data.AddRange(userIds); // 关闭无限级我的下属 // data.AddRange(await GetInfiniteSubordinats(userIds.ToArray())); return data.ToArray(); } /// /// 获取下属无限极. /// /// /// private async Task> GetInfiniteSubordinats(string[] parentIds) { List data = new List(); if (parentIds.ToList().Count > 0) { var userIds = await _repository.AsQueryable().In(it => it.ManagerId, parentIds).Where(it => it.DeleteMark == null).OrderBy(it => it.SortCode).Select(it => it.Id).ToListAsync(); data.AddRange(userIds); data.AddRange(await GetInfiniteSubordinats(userIds.ToArray())); } return data; } /// /// 获取当前用户岗位信息. /// /// /// private async Task> GetPosition(string PositionIds) { return await _repository.AsSugarClient().Queryable().In(it => it.Id, PositionIds.Split(",")).Select(it => new PositionInfoModel { id = it.Id, name = it.FullName }).ToListAsync(); } /// /// 获取条件模型. /// /// private ConditionalModel GetConditionalModel(QueryType expressType, string fieldName, string fieldValue, string dataType = "string") { switch (expressType) { // 模糊 case QueryType.Contains: return new ConditionalModel() { FieldName = fieldName, ConditionalType = ConditionalType.Like, FieldValue = fieldValue }; // 等于 case QueryType.Equal: switch (dataType) { case "Double": return new ConditionalModel() { FieldName = fieldName, ConditionalType = ConditionalType.Equal, FieldValue = fieldValue, FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(double)) }; case "Int32": return new ConditionalModel() { FieldName = fieldName, ConditionalType = ConditionalType.Equal, FieldValue = fieldValue, FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(int)) }; default: return new ConditionalModel() { FieldName = fieldName, ConditionalType = ConditionalType.Equal, FieldValue = fieldValue }; } // 不等于 case QueryType.NotEqual: switch (dataType) { case "Double": return new ConditionalModel() { FieldName = fieldName, ConditionalType = ConditionalType.NoEqual, FieldValue = fieldValue, FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(double)) }; case "Int32": return new ConditionalModel() { FieldName = fieldName, ConditionalType = ConditionalType.NoEqual, FieldValue = fieldValue, FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(int)) }; default: return new ConditionalModel() { FieldName = fieldName, ConditionalType = ConditionalType.NoEqual, FieldValue = fieldValue }; } // 小于 case QueryType.LessThan: switch (dataType) { case "Double": return new ConditionalModel() { FieldName = fieldName, ConditionalType = ConditionalType.LessThan, FieldValue = fieldValue, FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(double)) }; case "Int32": return new ConditionalModel() { FieldName = fieldName, ConditionalType = ConditionalType.LessThan, FieldValue = fieldValue, FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(int)) }; default: return new ConditionalModel() { FieldName = fieldName, ConditionalType = ConditionalType.LessThan, FieldValue = fieldValue }; } // 小于等于 case QueryType.LessThanOrEqual: switch (dataType) { case "Double": return new ConditionalModel() { FieldName = fieldName, ConditionalType = ConditionalType.LessThanOrEqual, FieldValue = fieldValue, FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(double)) }; case "Int32": return new ConditionalModel() { FieldName = fieldName, ConditionalType = ConditionalType.LessThanOrEqual, FieldValue = fieldValue, FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(int)) }; default: return new ConditionalModel() { FieldName = fieldName, ConditionalType = ConditionalType.LessThanOrEqual, FieldValue = fieldValue }; } // 大于 case QueryType.GreaterThan: switch (dataType) { case "Double": return new ConditionalModel() { FieldName = fieldName, ConditionalType = ConditionalType.GreaterThan, FieldValue = fieldValue, FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(double)) }; case "Int32": return new ConditionalModel() { FieldName = fieldName, ConditionalType = ConditionalType.GreaterThan, FieldValue = fieldValue, FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(int)) }; default: return new ConditionalModel() { FieldName = fieldName, ConditionalType = ConditionalType.GreaterThan, FieldValue = fieldValue }; } // 大于等于 case QueryType.GreaterThanOrEqual: switch (dataType) { case "Double": return new ConditionalModel() { FieldName = fieldName, ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = fieldValue, FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(double)) }; case "Int32": return new ConditionalModel() { FieldName = fieldName, ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = fieldValue, FieldValueConvertFunc = it => SqlSugar.UtilMethods.ChangeType2(it, typeof(int)) }; default: return new ConditionalModel() { FieldName = fieldName, ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = fieldValue }; } // 包含 case QueryType.In: return new ConditionalModel() { FieldName = fieldName, ConditionalType = ConditionalType.In, FieldValue = fieldValue }; case QueryType.Included: return new ConditionalModel() { FieldName = fieldName, ConditionalType = ConditionalType.Like, FieldValue = fieldValue }; // 不包含 case QueryType.NotIn: return new ConditionalModel() { FieldName = fieldName, ConditionalType = ConditionalType.In, FieldValue = fieldValue }; case QueryType.NotIncluded: return new ConditionalModel() { FieldName = fieldName, ConditionalType = ConditionalType.NoLike, FieldValue = fieldValue }; } return new ConditionalModel(); } /// /// 获取角色名称 根据 角色Ids. /// /// /// public async Task GetRoleNameByIds(string ids) { if (ids.IsNullOrEmpty()) return string.Empty; var idList = ids.Split(",").ToList(); var nameList = new List(); var roleList = await _repository.AsSugarClient().Queryable().Where(x => x.DeleteMark == null && x.EnabledMark == 1).ToListAsync(); foreach (var item in idList) { var info = roleList.Find(x => x.Id == item); if (info != null && info.FullName.IsNotEmptyOrNull()) { nameList.Add(info.FullName); } } return string.Join(",", nameList); } /// /// 根据角色Ids和组织Id 获取组织下的角色以及全局角色. /// /// 角色Id集合. /// 组织Id. /// public async Task> GetUserOrgRoleIds(string roleIds, string organizeId) { if (roleIds.IsNotEmptyOrNull()) { var userRoleIds = roleIds.Split(","); // 当前组织下的角色Id 集合 var roleList = await _repository.AsSugarClient().Queryable() .Where(x => x.OrganizeId == organizeId && x.ObjectType == "Role" && userRoleIds.Contains(x.ObjectId)).Select(x => x.ObjectId).ToListAsync(); // 全局角色Id 集合 var gRoleList = await _repository.AsSugarClient().Queryable().Where(x => userRoleIds.Contains(x.Id) && x.GlobalMark == 1) .Where(r => r.EnabledMark == 1 && r.DeleteMark == null).Select(x => x.Id).ToListAsync(); roleList.AddRange(gRoleList); // 组织角色 + 全局角色 return roleList; } else { return new List(); } } /// /// 根据角色Ids和组织Id 获取组织下的角色以及全局角色. /// /// 角色Id集合. /// 组织Id. /// public List GetUserRoleIds(string roleIds, string organizeId) { if (roleIds.IsNotEmptyOrNull()) { var userRoleIds = roleIds.Split(","); // 当前组织下的角色Id 集合 var roleList = _repository.AsSugarClient().Queryable() .Where(x => x.OrganizeId == organizeId && x.ObjectType == "Role" && userRoleIds.Contains(x.ObjectId)).Select(x => x.ObjectId).ToList(); // 全局角色Id 集合 var gRoleList = _repository.AsSugarClient().Queryable().Where(x => userRoleIds.Contains(x.Id) && x.GlobalMark == 1) .Where(r => r.EnabledMark == 1 && r.DeleteMark == null).Select(x => x.Id).ToList(); roleList.AddRange(gRoleList); // 组织角色 + 全局角色 return roleList; } else { return new List(); } } /// /// 会否存在用户缓存. /// /// /// private async Task ExistsUserInfo(string cacheKey) { return await _cacheManager.ExistsAsync(cacheKey); } /// /// 保存用户登录信息. /// /// key. /// 用户信息. /// 过期时间. /// private async Task SetUserInfo(string cacheKey, UserInfoModel userInfo, TimeSpan timeSpan) { return await _cacheManager.SetAsync(cacheKey, userInfo, timeSpan); } /// /// 获取用户登录信息. /// /// key. /// private async Task GetUserInfo(string cacheKey) { return (await _cacheManager.GetAsync(cacheKey)).Adapt(); } /// /// 判断是否管理员. /// /// /// public bool IsAdmin(string userId) { if (userId == "admin") return true; return _repository.AsSugarClient().Queryable().Any(x => x.Id == userId && x.Account == "admin" && x.DeleteMark == null); } /// /// 获取管理员用户id. /// public string GetAdminUserId() { var user = _repository.AsSugarClient().Queryable().First(x => x.Account == "admin" && x.DeleteMark == null); if (user.IsNotEmptyOrNull()) return user.Id; return string.Empty; } }