using DS.Module.Core;
using DS.Module.Core.Extensions;
using DS.Module.Core.Helpers;
using DS.Module.UserModule;
using DS.WMS.Core.Sys.Dtos;
using DS.WMS.Core.Sys.Entity;
using DS.WMS.Core.Sys.Interface;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System.Diagnostics;
using System.Runtime.InteropServices;
using DS.Module.Core.Log;
using DS.Module.SqlSugar;
using DS.WMS.Core.Code.Dtos;
using DS.WMS.Core.Code.Entity;
using Mapster;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System.Data;
using DS.WMS.Core.Info.Dtos;
using NPOI.SS.Formula.Functions;
using DS.WMS.Core.Flow.Dtos;
using Microsoft.Extensions.Logging;
using DS.Module.Core.Constants;
using DS.WMS.Core.Op.Entity;
using DS.Module.Core.Data;
using DS.WMS.Core.TaskPlat.Entity;
using DS.WMS.Core.Invoice.Dtos;
using DS.WMS.Core.Op.Method;
namespace DS.WMS.Core.Sys.Method;
///
/// 公共服务
///
public class CommonService : ICommonService
{
private readonly IServiceProvider _serviceProvider;
private readonly ISqlSugarClient db;
private readonly IUser user;
private readonly ISaasDbService saasService;
private readonly IHttpContextAccessor IhttpContext;
private readonly IWebHostEnvironment _environment;
private readonly ILogger _logger;
///
/// 任务台基础表自定义列对应的Code
///
private const string TASK_PLAT_BASIC_CODE = "BASIC";
///
///
///
///
public CommonService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
db = _serviceProvider.GetRequiredService();
user = _serviceProvider.GetRequiredService();
saasService = _serviceProvider.GetRequiredService();
IhttpContext = _serviceProvider.GetRequiredService();
_environment = _serviceProvider.GetRequiredService();
_logger = _serviceProvider.GetRequiredService>();
}
#region 后台登录
///
/// 用户登录
///
///
///
public DataResult UserLogin(UserLoginModel model)
{
if (model.UserName != "admin")
{
return DataResult.Failed("非管理端账号!");
}
var userInfo = db.Queryable().Filter(null, true)
.First(x => x.UserCode == model.UserName);
if (userInfo == null)
{
return DataResult.Failed("账号不存在,请检查!");
}
if (userInfo.MD5Password != model.Password)
{
return DataResult.Failed("密码错误!");
}
var tokenModel = new JwtHelper.JwtTokenModel
{
Uid = userInfo.Id.ToString(),
Name = userInfo.UserName,
// OrgId = userInfo.OrgId,
// GID = userInfo.GID,
TenantId = userInfo.TenantId.ToString(),
TenantName = userInfo.TenantName,
};
var token = JwtHelper.Encrypt(tokenModel);
return DataResult.Success(token);
}
///
/// 获取用户信息
///
///
public DataResult GetUserInfo()
{
var userId = long.Parse(user.UserId);
var tenantId = long.Parse(user.TenantId);
var tokenModel = new JwtHelper.JwtTokenModel
{
Uid = user.UserId,
Name = db.Queryable().Filter(null, true).First(x => x.Id == userId).UserName,
// OrgId = userInfo.OrgId,
// GID = userInfo.GID,
TenantName = user.TenantName,
TenantId = tenantId.ToString(),
};
var refreshToken = JwtHelper.Encrypt(tokenModel, true, false);
var data = db.Queryable().Filter(null, true).Where(x => x.Id == userId)
.Select(a => new CurrentUserViewModel
{
UserId = a.Id,
UserCode = a.UserCode,
UserName = a.UserName,
TenantId = tenantId,
UserType = a.UserType,
CompanyId = a.CompanyId,
// ClientId = a.ClientId,
IsUseSystem = a.IsUseSystem,
RefreshToken = refreshToken,
// OrgId = a.OrgId.ToString(), CompanyName = a.CustomerName
})
.Mapper(it =>
{
//只能写在Select后面
it.HomePath = "/analysis";
})
.First();
// var context = IhttpContext.HttpContext;
// var log = new SysLogVisit()
// {
// Ip = HttpUtil.GetClientIP(context),
// Location = HttpUtil.GetRequestUrlAddress(request),
// Browser = clientInfo?.UA.Family + clientInfo?.UA.Major,
// Os = clientInfo?.OS.Family + clientInfo?.OS.Major,
// OpTime = DateTime.Now,
// };
return DataResult.Success(data);
}
///
/// 查询用户拥有的菜单权限
///
///
public DataResult> GetUserPermissionByToken()
{
List list = new List();
var userId = long.Parse(user.UserId);
var userInfo = db.Queryable().Filter(null, true).Where(x => x.Id == userId).First();
//超级管理员
if (userInfo.UserType == 0)
{
list = db.Queryable().Filter(null, true).Where(x =>
x.MenuType == 1 && x.IsHidden == false && (x.PermissionType == -1 || x.PermissionType == 0))
.OrderBy(x => x.SortCode)
.Select(a => new RouteItem
{
Id = a.Id,
Path = a.Url,
Name = a.PermissionName,
Component = a.Component,
Redirect = a.Redirect,
Meta = new RouteMeta()
{
Title = a.Title,
Icon = a.Icon,
}
})
.ToList();
foreach (var item in list)
{
var childs = db.Queryable().Filter(null, true)
.Where(x => x.MenuType == 2 && x.ParentId == item.Id && x.IsHidden == false &&
(x.PermissionType == -1 || x.PermissionType == 0))
.OrderBy(x => x.SortCode)
.Select(a => new RouteItem
{
Id = a.Id,
ParentId = a.ParentId,
Path = a.Url,
Name = a.PermissionName,
Component = a.Component,
Meta = new RouteMeta()
{
Title = a.Title,
Icon = a.Icon,
}
}).ToList();
item.Children = childs;
}
}
else
{
var roleIds = db.Queryable().Where(x => x.UserId == userId).Select(x => x.RoleId).ToList();
var permissions = db.Queryable().Where(x => roleIds.Contains(x.RoleId))
.Select(x => x.PermissionId).Distinct().ToList();
var perlist = db.Queryable()
.Where(x => x.MenuType == 1 && x.IsHidden == false && permissions.Contains(x.Id) &&
(x.PermissionType == -1 || x.PermissionType == 0))
.OrderBy(x => x.SortCode)
.Select(a => new RouteItem
{
Id = a.Id,
Path = a.Url,
Name = a.PermissionName,
Component = a.Component,
Redirect = a.Redirect,
SortCode = a.SortCode,
Meta = new RouteMeta()
{
Title = a.Title,
Icon = a.Icon,
}
})
.ToList();
list.AddRange(perlist);
//去重
list.Distinct();
//排序
list = list.OrderBy(x => x.SortCode).ToList();
foreach (var item in list)
{
var childs = db.Queryable().Where(x =>
x.MenuType == 2 && x.ParentId == item.Id && x.IsHidden == false && permissions.Contains(x.Id) &&
(x.PermissionType == -1 || x.PermissionType == 0))
.OrderBy(x => x.SortCode)
.Select(a => new RouteItem
{
Id = a.Id,
ParentId = a.ParentId,
Path = a.Url,
Name = a.PermissionName,
Component = a.Component,
Meta = new RouteMeta()
{
Title = a.Title,
Icon = a.Icon,
}
}).ToList();
//去重
childs.Distinct();
//排序
childs = childs.OrderBy(x => x.SortCode).ToList();
item.Children = childs;
}
}
// list = list.OrderBy(x => x.Id).ToList();
return DataResult>.Success("获取数据成功!", list);
}
#region 刷新Token
///
/// 后台端刷新Token
///
///
public DataResult UserRefreshToken()
{
var refreshToken = IhttpContext.HttpContext!.Request.Headers["RefreshToken"].First();
if (string.IsNullOrWhiteSpace(refreshToken))
{
return DataResult.Failed("RefreshToken值为空");
}
try
{
var result = JwtHelper.DecodeJwt(refreshToken);
if (result.Count <= 0 && !string.IsNullOrWhiteSpace(result["TenantId"]))
{
return DataResult.Failed("Token解密失败!");
}
var userId = long.Parse(user.UserId);
var tenantId = long.Parse(user.TenantId);
var tokenModel = new JwtHelper.JwtTokenModel
{
Uid = user.UserId,
Name = db.Queryable().Filter(null, true).First(x => x.Id == userId).UserName,
TenantId = tenantId.ToString(),
TenantName = user.TenantName,
};
var data = new RefreshTokenRes
{
AccessToken = JwtHelper.Encrypt(tokenModel),
RefreshToken = JwtHelper.Encrypt(tokenModel, true)
};
return DataResult.Success(data);
}
catch (SecurityTokenExpiredException e)
{
IhttpContext.HttpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
return DataResult.Failed("Token过期!");
}
}
///
/// 客户端刷新Token
///
///
public DataResult ClientUserRefreshToken()
{
var refreshToken = IhttpContext.HttpContext!.Request.Headers["RefreshToken"].First();
if (string.IsNullOrWhiteSpace(refreshToken))
{
return DataResult.Failed("RefreshToken值为空");
}
try
{
var result = JwtHelper.DecodeJwt(refreshToken);
if (result.Count <= 0 && !string.IsNullOrWhiteSpace(result["TenantId"]))
{
return DataResult.Failed("Token解密失败!");
}
var userId = long.Parse(result["jti"]);
var userInfo = db.Queryable().Filter(null, true).First(x => x.Id == userId);
var tenantId = result["TenantId"];
var orgId = result["OrgId"];
var tokenModel = new JwtHelper.JwtTokenModel
{
Uid = userId.ToString(),
Name = userInfo.UserName,
OrgId = orgId.ToString(),
TenantId = tenantId.ToString(),
TenantName = userInfo.TenantName,
};
var data = new RefreshTokenRes
{
AccessToken = JwtHelper.Encrypt(tokenModel, false, true),
RefreshToken = JwtHelper.Encrypt(tokenModel, true, true)
};
return DataResult.Success(data);
}
catch (SecurityTokenExpiredException e)
{
IhttpContext.HttpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
return DataResult.Failed("Token过期!");
}
}
#endregion
#endregion
#region 客户端登录
///
/// 用户登录 账号密码
///
///
///
public async Task> ClientUserLogin(UserLoginModel model)
{
if (model.UserName.ToLower().Trim() == "admin")
{
return await Task.FromResult(DataResult.Failed("非租户端用户!"));
}
var userInfo = await db.Queryable().Filter(null, true)
.FirstAsync(x => x.UserCode == model.UserName && x.IsUseSystem == true);
if (userInfo == null)
{
return await Task.FromResult(DataResult.Failed("账号不存在或账号禁用,请检查!"));
}
if (userInfo.MD5Password != model.Password)
{
return await Task.FromResult(DataResult.Failed("密码错误!"));
}
var tenant = await db.Queryable().Filter(null, true)
.FirstAsync(x => x.Id == userInfo.TenantId);
var tokenModel = new JwtHelper.JwtTokenModel
{
Uid = userInfo.Id.ToString(),
Name = userInfo.UserName,
OrgId = userInfo.DefaultOrgId.ToString(),
TenantId = userInfo.TenantId.ToString(),
TenantName = tenant.Name,
};
var token = JwtHelper.Encrypt(tokenModel, false, true);
var visLog = new SysLogVisit()
{
LoginType = 0,
UserName = userInfo.UserName,
UserCode = userInfo.UserCode,
TenantId = userInfo.TenantId,
OpTime = DateTime.Now,
Message = "登录成功"
};
await saasService.GetLogDb().Insertable(visLog).ExecuteCommandAsync();
return await Task.FromResult(DataResult.Success(token));
}
///
/// 用户登录 邮箱
///
///
///
public async Task> ClientUserEmailLogin(UserEmailLoginModel model)
{
var userInfo = await db.Queryable().Filter(null, true)
.FirstAsync(x => x.Email == model.Email && x.IsUseSystem == true);
if (userInfo == null)
{
return await Task.FromResult(DataResult.Failed("用户邮箱不存在或邮箱账号禁用,请检查!"));
}
if (userInfo.MD5Password != model.Password)
{
return await Task.FromResult(DataResult.Failed("密码错误!"));
}
var tenant = await db.Queryable().Filter(null, true)
.FirstAsync(x => x.Id == userInfo.TenantId);
var tokenModel = new JwtHelper.JwtTokenModel
{
Uid = userInfo.Id.ToString(),
Name = userInfo.UserName,
OrgId = userInfo.DefaultOrgId.ToString(),
TenantId = userInfo.TenantId.ToString(),
TenantName = tenant.Name,
};
var token = JwtHelper.Encrypt(tokenModel, false, true);
var visLog = new SysLogVisit()
{
LoginType = 0,
UserName = userInfo.UserName,
UserCode = userInfo.UserCode,
TenantId = userInfo.TenantId,
OpTime = DateTime.Now,
Message = "登录成功"
};
await saasService.GetLogDb().Insertable(visLog).ExecuteCommandAsync();
return await Task.FromResult(DataResult.Success(token));
}
///
/// 用户登录 手机号
///
///
///
public async Task> ClientUserPhoneLogin(UserPhoneLoginModel model)
{
var userInfo = await db.Queryable().Filter(null, true)
.FirstAsync(x => x.Phone == model.Phone && x.IsUseSystem == true);
if (userInfo == null)
{
return await Task.FromResult(DataResult.Failed("用户手机号不存在或手机号账号禁用,请检查!"));
}
if (userInfo.MD5Password != model.Password)
{
return await Task.FromResult(DataResult.Failed("密码错误!"));
}
var tenant = await db.Queryable().Filter(null, true)
.FirstAsync(x => x.Id == userInfo.TenantId);
var tokenModel = new JwtHelper.JwtTokenModel
{
Uid = userInfo.Id.ToString(),
Name = userInfo.UserName,
OrgId = userInfo.DefaultOrgId.ToString(),
TenantId = userInfo.TenantId.ToString(),
TenantName = tenant.Name,
};
var token = JwtHelper.Encrypt(tokenModel, false, true);
var visLog = new SysLogVisit()
{
LoginType = 0,
UserName = userInfo.UserName,
UserCode = userInfo.UserCode,
TenantId = userInfo.TenantId,
OpTime = DateTime.Now,
Message = "登录成功"
};
await saasService.GetLogDb().Insertable(visLog).ExecuteCommandAsync();
return await Task.FromResult(DataResult.Success(token));
}
///
///
///
///
public async Task> GetClientUserInfo()
{
var userId = long.Parse(user.UserId);
var tenantId = long.Parse(user.TenantId);
//取第一个机构
var orgRelations = await db.Queryable().Filter(null, true)
.LeftJoin((a, b) => a.OrgId == b.Id)
.Where(a => a.UserId == userId)
.Select((a, b) => new UserOrgListRes
{
OrgId = a.OrgId,
OrgName = b.OrgName
})
.ToListAsync();
var userInfo = await db.Queryable().Filter(null, true).FirstAsync(x => x.Id == userId);
var tenant = await db.Queryable().Filter(null, true)
.FirstAsync(x => x.Id == userInfo.TenantId);
var tokenModel = new JwtHelper.JwtTokenModel
{
Uid = user.UserId,
Name = userInfo.UserName,
OrgId = user.OrgId.ToString(),
TenantId = tenantId.ToString(),
TenantName = tenant.Name
};
var refreshToken = JwtHelper.Encrypt(tokenModel, true, true);
var data = await db.Queryable().Filter(null, true).Where(x => x.Id == userId)
.Select(a => new CurrentUserViewModel
{
UserId = a.Id,
UserCode = a.UserCode,
UserName = a.UserName,
TenantId = tenantId,
UserType = a.UserType,
CompanyId = a.CompanyId,
// ClientId = a.ClientId,
IsUseSystem = a.IsUseSystem,
RefreshToken = refreshToken,
OrgId = user.OrgId.ToString(),
Tel = a.Tel,
Email = a.Email,
Phone = a.Phone,
OfficePhone = a.OfficePhone,
HomePath = string.IsNullOrEmpty(a.HomePath) ? "/taskmanage" : a.HomePath
// UserOrgs = orgRelations,
//OrgId = a.OrgId.ToString(), CompanyName = a.CustomerName
})
//.Mapper(it =>
//{
// //只能写在Select后面
// //it.HomePath = "/analysis";
// it.HomePath = string.IsNullOrEmpty(it.HomePath) ? "/taskmanage": it.HomePath;
//})
.FirstAsync();
data.UserOrgs = orgRelations;
return await Task.FromResult(DataResult.Success(data));
}
#region 更换机构
///
/// 更换机构
///
///
///
public DataResult ChangeOrg(string id)
{
var userId = user.UserId;
var tenantId = long.Parse(user.TenantId);
var sysUser = db.Queryable().First(x => x.Id == long.Parse(userId));
if (sysUser.IsNull())
{
return DataResult.Failed("非法用户!");
}
var relation = db.Queryable()
.First(x => x.UserId == long.Parse(userId) && x.OrgId == long.Parse(id));
if (relation.IsNull())
{
return DataResult.Failed("非法机构!");
}
var tokenModel = new JwtHelper.JwtTokenModel
{
Uid = userId,
OrgId = id,
Name = sysUser.UserName,
TenantId = tenantId.ToString(),
TenantName = sysUser.TenantName,
};
var token = new RefreshTokenRes
{
AccessToken = JwtHelper.Encrypt(tokenModel, false, true),
RefreshToken = JwtHelper.Encrypt(tokenModel, true, true)
};
return DataResult.Success(token);
}
#endregion
///
/// 查询客户 用户拥有的菜单权限
///
///
public async Task>> GetClientUserPermissionByToken()
{
List list = new List();
_logger.LogInformation("GetClientUserPermissionByToken临时日志:user.UserId={userId},user.TenantId={TenantId}", user.UserId, user.TenantId);
var userId = long.Parse(user.UserId);
var userInfo = await db.Queryable().Where(x => x.Id == userId).FirstAsync();
var sql = db.Queryable().Where(x => x.Id == userId).ToSqlString();
_logger.LogInformation("GetClientUserPermissionByToken临时日志:sql={sql}", sql);
//超级管理员
if (userInfo.UserType == UserTypeEnum.SupperAdmin.ToEnumInt())
{
list = await db.Queryable().Where(x =>
x.MenuType == 1 && x.IsHidden == false && (x.PermissionType == 1 || x.PermissionType == 0))
.OrderBy(x => x.SortCode)
.Select(a => new RouteItem
{
Id = a.Id,
Path = a.Url,
Name = a.PermissionName,
Component = a.Component,
Redirect = a.Redirect,
Meta = new RouteMeta()
{
Title = a.Title,
Icon = a.Icon,
}
})
.ToListAsync();
foreach (var item in list)
{
var childs = await db.Queryable().Filter(null, true)
.Where(x => (x.MenuType == 1 || x.MenuType == 2) && x.ParentId == item.Id && x.IsHidden == false &&
(x.PermissionType == 1 || x.PermissionType == 0))
.OrderBy(x => x.SortCode)
.Select(a => new RouteItem
{
Id = a.Id,
ParentId = a.ParentId,
Path = a.Url,
Name = a.PermissionName,
Component = a.Component,
IsCache = a.IsCache,
Meta = new RouteMeta()
{
Title = a.Title,
Icon = a.Icon,
}
}).ToListAsync();
item.Children = childs;
}
}
else if (userInfo.UserType == UserTypeEnum.ApplyUser.ToEnumInt()) //租户申请用户
{
var roleIds = await db.Queryable().Where(x => x.UserId == userId).Select(x => x.RoleId).ToListAsync();
var permissions = await db.Queryable().Where(x => roleIds.Contains(x.RoleId))
.Select(x => x.PermissionId).Distinct().ToListAsync();
var perlist = await db.Queryable()
.Where(x => x.MenuType == 1 && x.IsHidden == false && permissions.Contains(x.Id) &&
(x.PermissionType == 1 || x.PermissionType == 0))
.OrderBy(x => x.SortCode)
.Select(a => new RouteItem
{
Id = a.Id,
Path = a.Url,
Name = a.PermissionName,
Component = a.Component,
Redirect = a.Redirect,
SortCode = a.SortCode,
Meta = new RouteMeta()
{
Title = a.Title,
Icon = a.Icon,
}
})
.ToListAsync();
list.AddRange(perlist);
//去重
list.Distinct();
//排序
list = list.OrderBy(x => x.SortCode).ToList();
foreach (var item in list)
{
var childs = await db.Queryable().Where(x =>
x.MenuType == 2 && x.ParentId == item.Id && x.IsHidden == false && permissions.Contains(x.Id) &&
(x.PermissionType == 1 || x.PermissionType == 0))
.OrderBy(x => x.SortCode)
.Select(a => new RouteItem
{
Id = a.Id,
ParentId = a.ParentId,
Path = a.Url,
Name = a.PermissionName,
Component = a.Component,
Meta = new RouteMeta()
{
Title = a.Title,
Icon = a.Icon,
}
}).ToListAsync();
//去重
childs.Distinct();
//排序
childs = childs.OrderBy(x => x.SortCode).ToList();
item.Children = childs;
}
}
else
{
var roleIds = await db.Queryable().Where(x => x.UserId == userId).Select(x => x.RoleId).ToListAsync();
var permissions = await db.Queryable().Where(x => roleIds.Contains(x.RoleId))
.Select(x => x.PermissionId).Distinct().ToListAsync();
var perlist = await db.Queryable()
.Where(x => x.MenuType == 1 && x.IsHidden == false && permissions.Contains(x.PermissionId) &&
(x.PermissionType == 1 || x.PermissionType == 0))
.OrderBy(x => x.SortCode)
.Select(a => new RouteItem
{
Id = a.Id,
ParentId = a.PermissionId,
Path = a.Url,
Name = a.PermissionName,
EnName = a.PermissionEnName,
Component = a.Component,
Redirect = a.Redirect,
SortCode = a.SortCode,
Meta = new RouteMeta()
{
Title = a.Title,
Icon = a.Icon,
}
})
.ToListAsync();
list.AddRange(perlist);
//去重
list.Distinct();
//排序
list = list.OrderBy(x => x.SortCode).ToList();
foreach (var item in list)
{
var childs = await db.Queryable().Where(x =>
(x.MenuType == 1 || x.MenuType == 2) && x.ParentId == item.ParentId && x.IsHidden == false &&
permissions.Contains(x.PermissionId) &&
(x.PermissionType == 1 || x.PermissionType == 0) &&
x.PermissionId != 1744968217220222976) //排除企业用户维护
.OrderBy(x => x.SortCode)
.Select(a => new RouteItem
{
Id = a.Id,
ParentId = a.PermissionId,
Path = a.Url,
Name = a.PermissionName,
EnName = a.PermissionEnName,
Component = a.Component,
IsCache = a.IsCache,
Meta = new RouteMeta()
{
Title = a.Title,
Icon = a.Icon,
}
}).ToListAsync();
//去重
childs.Distinct();
//排序
childs = childs.OrderBy(x => x.SortCode).ToList();
foreach (var child in childs)
{
var grandsons = await db.Queryable().Where(x =>
x.MenuType == 2 && x.ParentId == child.ParentId && x.IsHidden == false &&
permissions.Contains(x.PermissionId)) //获取第三层路由
.OrderBy(x => x.SortCode)
.Select(a => new RouteItem
{
Id = a.Id,
ParentId = a.PermissionId,
Path = a.Url,
Name = a.PermissionName,
EnName = a.PermissionEnName,
Component = a.Component,
IsCache = a.IsCache,
Meta = new RouteMeta()
{
Title = a.Title,
Icon = a.Icon,
}
}).ToListAsync();
if (grandsons.Count > 0)
{
//去重
grandsons.Distinct();
//排序
grandsons = grandsons.OrderBy(x => x.SortCode).ToList();
child.Children = grandsons;
}
}
item.Children = childs;
}
}
// list = list.OrderBy(x => x.Id).ToList();
return await Task.FromResult(DataResult>.Success("获取数据成功!", list));
}
///
/// 获取客户端按钮权限
///
///
public async Task> GetClientUserPermissionCode()
{
var userId = long.Parse(user.UserId);
var roleList = await db.Queryable()
.Where(x => x.UserId == userId).Select(n => n.RoleId).ToListAsync();
roleList.Distinct();
var list = await db.Queryable().Where(a => roleList.Contains(a.RoleId) && a.IsPermission == 1)
.InnerJoin((a, b) => a.PermissionId == b.Id)
.Where((a, b) => b.MenuType == 3)
.Select((a, b) => b.PermissionCode
).ToArrayAsync();
return await Task.FromResult(DataResult.Success("获取数据成功!", list));
}
#endregion
#region 客户端通用
///
/// 获取权限树列表-客户端
///
///
public DataResult> GetClientPermissionTreeList()
{
var list = db.Queryable()
.Where(x => x.MenuType == 1 && x.IsHidden == false && (x.PermissionType == 1 || x.PermissionType == 0))
.OrderBy(x => x.SortCode)
.Select(a => new PermissionTreeList
{
Title = a.PermissionName,
EnTitle = a.PermissionEnName,
Key = a.Id,
Icon = a.Icon
})
.ToList();
foreach (var item in list)
{
var childs = db.Queryable().Where(x =>
(x.MenuType == 1 || x.MenuType == 2) && x.IsHidden == false && x.ParentId == item.Key &&
(x.PermissionType == 1 || x.PermissionType == 0))
.OrderBy(x => x.SortCode)
.Select(a => new PermissionTreeList
{
Title = a.PermissionName,
EnTitle = a.PermissionEnName,
Key = a.Id,
Icon = a.Icon
}).ToList();
foreach (var child in childs)
{
var grandsons = db.Queryable().Where(x => x.MenuType == 2 && x.ParentId == child.Key)
.OrderBy(x => x.SortCode)
.Select(a => new PermissionTreeList
{
Title = a.PermissionName,
EnTitle = a.PermissionEnName,
Key = a.Id,
Icon = a.Icon
}).ToList();
child.Children = grandsons;
}
item.Children = childs;
}
return DataResult>.Success("获取数据成功!", list);
}
#endregion
#region 获取角色下拉列表
///
/// 获取角色下拉列表
///
///
public DataResult> GetRoleList()
{
var list = db.Queryable()
.Select(a => new ApiSelectViewModel
{
Label = a.RoleName,
Value = a.Id,
})
.ToList();
return DataResult>.Success("获取数据成功!", list);
}
#endregion 获取角色下拉列表
#region 获取用户下拉列表
///
/// 获取指定用户下拉列表
///
///
public DataResult> GetUserList(string queryKey = "")
{
var list = db.Queryable().Where(a => a.UserType != UserTypeEnum.ApplyUser.ToEnumInt())
.WhereIF(!string.IsNullOrEmpty(queryKey), a => a.PinYinCode.Contains(queryKey) || a.UserCode.Contains(queryKey) || a.UserName.Contains(queryKey))
.Select(a => new ApiSelectViewModel
{
Label = a.UserName,
Value = a.Id,
})
.Take(20)
.WithCache($"{SqlSugarCacheConst.User}{user.TenantId}", SqlSugarCacheConst.CacheDurationInSeconds).ToList();
return DataResult>.Success("获取数据成功!", list);
}
#endregion 获取用户下拉列表
#region 获取机构下拉列表
///
/// 获取机构下拉列表
///
///
public DataResult> GetOrgList(string queryKey = "")
{
var list = db.Queryable().Where(a => a.Status == StatusEnum.Enable && a.IsDepartment == false)
.WhereIF(!string.IsNullOrEmpty(queryKey), a => (a.OrgName.Contains(queryKey) || a.OrgFullName.Contains(queryKey) || a.OrgEnName.Contains(queryKey)))
.Select(a => new OrgApiSelectViewModel
{
Label = a.OrgName,
Id = a.Id,
})
.Take(20)
.WithCache($"{SqlSugarCacheConst.Org}{user.TenantId}", SqlSugarCacheConst.CacheDurationInSeconds)
.ToList();
return DataResult>.Success("获取数据成功!", list);
}
#endregion 获取机构下拉列表
#region 商品类型分类
///
/// 获取商品类型下拉列表
///
///
public DataResult> GetGoodsTypeList()
{
var list = db.Queryable()
.Select(a => new ApiSelectViewModel
{
Label = a.GoodsTypeName,
Value = a.Id,
})
.ToList();
return DataResult>.Success("获取数据成功!", list);
}
///
/// 获取商品类型下拉列表-客户端
///
///
public DataResult> GetClientGoodsTypeList()
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var list = tenantDb.Queryable()
.Select(a => new ApiSelectViewModel
{
Label = a.GoodsTypeName,
Value = a.Id,
})
.ToList();
return DataResult>.Success("获取数据成功!", list);
}
#endregion
#region 国家信息下拉
///
/// 获取国家信息下拉列表
///
///
public DataResult> GetCountrySelectList()
{
var list = db.Queryable()
.Where(x => x.Status == StatusEnum.Enable)
.Select()
.ToList();
return DataResult>.Success("获取数据成功!", list);
}
///
/// 获取国家信息下拉列表-客户端
///
///
public DataResult> GetClientCountrySelectList()
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var list = tenantDb.Queryable()
.Where(x => x.Status == StatusEnum.Enable)
.Select()
.ToList();
return DataResult>.Success("获取数据成功!", list);
}
#endregion
#region 航线信息下拉
///
/// 获取航线信息下拉列表
///
///
public DataResult> GetLanesSelectList()
{
var list = db.Queryable()
.Where(x => x.Status == StatusEnum.Enable)
.Select()
.ToList();
return DataResult>.Success("获取数据成功!", list);
}
///
/// 获取航线信息下拉列表-客户端
///
///
public DataResult> GetClientLanesSelectList()
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var list = tenantDb.Queryable()
.Where(x => x.Status == StatusEnum.Enable)
.Select()
.ToList();
return DataResult>.Success("获取数据成功!", list);
}
///
/// 获取港口信息下拉列表
///
///
public DataResult> GetPortSelectList()
{
var list = db.Queryable()
.Where(x => x.Status == StatusEnum.Enable)
.Select()
.ToList();
return DataResult>.Success("获取数据成功!", list);
}
///
/// 获取港口信息下拉列表-客户端
///
///
public async Task>> GetClientPortSelectList(string queryKey = "")
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var list = await tenantDb.Queryable()
.Where(x => x.Status == StatusEnum.Enable)
.WhereIF(!string.IsNullOrEmpty(queryKey), x => x.PortName.Contains(queryKey) || x.CnName.Contains(queryKey) || x.EdiCode.Contains(queryKey))
.Select(x => new CodePortSelectRes()
{
PinYinCode = !String.IsNullOrEmpty(x.EdiCode) ? x.EdiCode + "/" + x.PortName : x.PortName,
}, true)
.Take(20)
.WithCache(SqlSugarCacheConst.Port + user.TenantId, SqlSugarCacheConst.CacheDurationInSeconds)
.ToListAsync();
return await Task.FromResult(DataResult>.Success("获取数据成功!", list));
}
#endregion
#region 获取客户数据权限列表
///
/// 获取客户数据权限列表
///
///
public DataResult> GetClientPermissionList()
{
var list = db.Queryable().Where(x => x.MenuType == 2 && x.IsHidden == false &&
(x.PermissionType == 1 || x.PermissionType == 0) &&
x.Id != 1744968217220222976 &&
(x.PermissionEntity != "" || x.PermissionEntity != null))
.Select()
.ToList();
return DataResult>.Success("获取数据成功!", list);
}
#endregion
#region 修改密码
///
/// 修改密码
///
///
///
public DataResult ChangePassword(ChangePasswordReq model)
{
var userId = long.Parse(user.UserId);
var userInfo = db.Queryable().First(x => x.Id == userId);
if (model.OldPassword == model.NewPassword)
{
return DataResult.Failed("旧密码与新密码一致!");
}
if (model.NewPassword != model.ConfirmPassword)
{
return DataResult.Failed("新密码与确认密码不一致!");
}
if (userInfo.Password == model.NewPassword)
{
return DataResult.Failed("新密码与用户密码一致!");
}
userInfo.Password = model.ConfirmPassword;
userInfo.MD5Password = MD5Helper.MD5Encrypt(model.ConfirmPassword);
db.Updateable(userInfo).ExecuteCommand();
return DataResult.Successed("密码修改成功!");
}
#endregion 修改密码
#region 租户注册
///
/// 租户注册
///
///
///
public DataResult TenantRegister(TenantRegisterReq req)
{
if (!req.Policy)
{
return DataResult.Failed("请阅读并勾选合同规定!");
}
var existApply = db.Queryable().Where(x =>
x.TaxNo == req.TaxNo && x.AuditStatus == AuditStatusEnum.Approve).Select(x => x.TaxNo).First();
if (!existApply.IsNullOrEmpty())
{
return DataResult.Failed("该企业信息已经注册!");
}
var auditApply = db.Queryable().Where(x =>
x.TaxNo == req.TaxNo &&
(x.AuditStatus == AuditStatusEnum.NoAudit || x.AuditStatus == AuditStatusEnum.Auditing))
.Select(x => x.TaxNo).First();
if (!auditApply.IsNullOrEmpty())
{
return DataResult.Failed("该企业信息待提交或待审批,请勿重复注册!");
}
var checkAdminUser = db.Queryable().Where(x =>
x.AdminUserCode == req.AdminUserCode.Trim()).Select(x => x.AdminUserCode).First();
if (!checkAdminUser.IsNullOrEmpty())
{
return DataResult.Failed(checkAdminUser + " 管理员登录账号已经注册!");
}
if (req.AdminUserPassword != req.AgainPassword)
return DataResult.Failed("密码不一致!");
try
{
//开启事务
db.Ado.BeginTran();
var apply = req.Adapt();
// var apply = new SysTenantApply
// {
// Name = req.Name,
// TaxNo = req.TaxNo,
// Phone = req.Phone,
// AdminUserCode = req.AdminUserCode,
// AdminUserPassword = req.AdminUserPassword,
// AuditStatus = AuditStatusEnum.NoAudit,
// PinYinCode = PinYinUtil.GetFristLetter(req.Name),
// };
apply.AuditStatus = AuditStatusEnum.NoAudit;
apply.PinYinCode = PinYinUtil.GetFristLetter(req.Name);
db.Insertable(apply).ExecuteCommand();
//写入注册用户
var userEntity = new SysUser
{
UserCode = req.AdminUserCode,
UserName = req.Name,
Password = req.AdminUserPassword,
PinYinCode = PinYinUtil.GetFristLetter(req.Name),
MD5Password = MD5Helper.MD5Encrypt(req.AdminUserPassword),
Email = "",
Phone = req.Phone,
UserType = UserTypeEnum.ApplyUser.ToEnumInt(), //管理员
Status = 0, //正常
IsUseSystem = true,
TenantId = 1288018625843826688,
};
var adminUser = db.Insertable(userEntity).ExecuteReturnEntity();
//写入用户角色 指定角色
var roleUser = new SysRoleUser
{
RoleId = 1744922920100171776,
UserId = adminUser.Id
};
db.Insertable(roleUser).ExecuteCommand();
db.Ado.CommitTran();
return DataResult.Successed("企业注册成功!请登录后完善相关资料并提交审核!");
}
catch (Exception ex)
{
db.Ado.RollbackTran();
ex.LogAsync(db).GetAwaiter().GetResult();
return DataResult.Failed("企业注册失败!");
}
}
#endregion
public DataResult> GetDataRuleEntityFields(string permissionId)
{
// var query = GetDataRuleFilter();
// SysUser us = new SysUser();
// var temp = us.GetEntityFieldProperty();
var role = new EntityFieldProperty()
{
FieldName = ComonConst.DataRule_LoginRole,
FieldComment = "当前登录用户的角色",
FieldType = "String"
};
var permission = db.Queryable().First(x => x.Id == long.Parse(permissionId));
if (permission.IsNull())
{
return DataResult>.Failed("权限模块不存在!");
}
var list = permission.PermissionEntity.GetEntityFieldByName();
// var entity = db.EntityMaintenance.GetEntityInfo(permission.PermissionEntity.GetEntity());
// var list = entity.GetEntityFieldByName();
if (list.Count == 0)
{
return DataResult>.Failed("请配置实体属性!");
}
list.Add(role);
return DataResult>.Success(list);
}
///
/// 获取当前登录用户的数据访问权限
///
/// linq表达式参数的名称,如u=>u.name中的"u"
///
public ISugarQueryable GetDataRuleFilter()
{
var userInfo = db.Queryable().First(x => x.Id == long.Parse(user.UserId));
if (userInfo.UserType == 0)
{
return db.Queryable(); //超级管理员特权
}
var moduleName = typeof(T).Name.ToLower();
var rule = db.Queryable()
.First(u => u.PermissionEntity.ToLower() == moduleName && u.Status == StatusEnum.Enable);
if (rule == null) return db.Queryable(); //没有设置数据规则,那么视为该资源允许被任何主体查看
#region 数据权限
var rules = db.Queryable()
.Where(u => u.PermissionEntity.ToLower() == moduleName && u.Status == StatusEnum.Enable && u.RuleType == "user").ToList();
if (rules.Count > 0)//检索制定用户的数据权限
{
var ruleIds = rules.Select(x => x.Id);
var ruleUser = db.Queryable()
.First(u => ruleIds.Contains((long)u.RuleId) && u.UserId == long.Parse(user.UserId));
if (ruleUser.IsNull())
{
// 检索公共数据权限
rule = db.Queryable()
.First(u => u.PermissionEntity.ToLower() == moduleName && u.Status == StatusEnum.Enable && u.RuleType == "public");
if (rule == null) return db.Queryable();
}
else
{
rule = rules.Find(x => x.Id == ruleUser.RuleId);
}
}
else
{
// 检索公共数据权限
rule = db.Queryable()
.First(u => u.PermissionEntity.ToLower() == moduleName && u.Status == StatusEnum.Enable && u.RuleType == "public");
if (rule == null) return db.Queryable();
}
#endregion
//if (db.Queryable()
// .Where(u => u.PermissionEntity.ToLower() == moduleName && u.Status == StatusEnum.Enable && u.RuleType == "user").Any())
//{
// //此处取第一个
// var ruleUser = db.Queryable()
// .First(u => u.PermissionEntity.ToLower() == moduleName && u.Status == StatusEnum.Enable);
//}
if (rule.DataRules.Contains(DataRuleConst.LoginUser))
{
//即把{loginUser} =='xxxxxxx'换为 user.UserId =='xxxxxxx',从而把当前登录的用户名与当时设计规则时选定的用户id对比
rule.DataRules = rule.DataRules.Replace(DataRuleConst.LoginUser, user.UserId);
}
if (rule.DataRules.Contains(DataRuleConst.LoginRole))
{
var roles = db.Queryable().Where(x => x.UserId == long.Parse(user.UserId))
.Select(n => n.RoleId)
.ToList();
roles.Sort();
rule.DataRules = rule.DataRules.Replace(DataRuleConst.LoginRole, string.Join(',', roles));
}
if (rule.DataRules.Contains(DataRuleConst.LoginOrg))
{
var orgs = db.Queryable().Where(x => x.UserId == long.Parse(user.UserId)).Select(n => n.OrgId)
.ToList();
orgs.Sort();
rule.DataRules = rule.DataRules.Replace(DataRuleConst.LoginOrg, string.Join(',', orgs));
}
var conditions = rule.DataRules.ConvertSqlSugarExpression();
var conditionalModels =
db.ConfigQuery.Context.Utilities.JsonToConditionalModels(
JsonConvert.SerializeObject(conditions));
return db.Queryable().Where(conditionalModels);
}
///
/// 获取操作规则条件组
///
///
///
public List GetOperationRuleConditional()
{
var userInfo = db.Queryable().First(x => x.Id == long.Parse(user.UserId));
if (userInfo.UserType == 0)
{
return new List(); //超级管理员特权
}
var moduleName = typeof(T).Name.ToLower();
var rule = db.Queryable()
.First(u => u.PermissionEntity.ToLower() == moduleName && u.Status == StatusEnum.Enable);
if (rule == null) return new List(); //没有设置数据规则,那么视为该资源允许被任何主体查看
if (rule.DataRules.Contains(DataRuleConst.LoginUser))
{
//即把{loginUser} =='xxxxxxx'换为 user.UserId =='xxxxxxx',从而把当前登录的用户名与当时设计规则时选定的用户id对比
rule.DataRules = rule.DataRules.Replace(DataRuleConst.LoginUser, user.UserId);
}
if (rule.DataRules.Contains(DataRuleConst.LoginRole))
{
var roles = db.Queryable().Where(x => x.UserId == long.Parse(user.UserId))
.Select(n => n.RoleId)
.ToList();
roles.Sort();
rule.DataRules = rule.DataRules.Replace(DataRuleConst.LoginRole, string.Join(',', roles));
}
if (rule.DataRules.Contains(DataRuleConst.LoginOrg))
{
var orgs = db.Queryable().Where(x => x.UserId == long.Parse(user.UserId)).Select(n => n.OrgId)
.ToList();
orgs.Sort();
rule.DataRules = rule.DataRules.Replace(DataRuleConst.LoginOrg, string.Join(',', orgs));
}
var conditions = rule.DataRules.ConvertSqlSugarExpression();
var conditionalModels =
db.ConfigQuery.Context.Utilities.JsonToConditionalModels(
JsonConvert.SerializeObject(conditions));
return conditionalModels;
}
#region 可视权限
///
/// 获取当前用户的可视权限范围
///
///
///
///
public async Task<(ISugarQueryable queryable, string? ruleScope)> GetVisibleDataRuleFilter(SqlSugarScopeProvider tenantDb)
{
var queryable = tenantDb.Queryable();
// 因为TaskBaseAllocation不能继承IOrgId,所以在这里根据条件,在需要的时候手动添加IOrgId查询筛选器
bool isTask = typeof(T) == typeof(TaskBaseAllocation);
var userInfo = db.Queryable().First(x => x.Id == long.Parse(user.UserId));
if (userInfo.UserType == 0)
{
if (isTask) queryable.Filter(typeof(IOrgId));
return (queryable, "all"); //超级管理员特权
}
var moduleName = typeof(T).Name.ToLower();
var rule = tenantDb.Queryable()
.First(u => u.UserId == long.Parse(user.UserId) && u.PermissionEntity.ToLower() == moduleName && u.Status == StatusEnum.Enable);
if (rule.IsNull())
{
return (queryable, null); //默认查询
}
else
{
var contidions = new List();
#region 可视权限
if ((long)rule.VisibleTemplateId == 0)
{
contidions.Add(new ConditionalModel { FieldName = "CreateBy", ConditionalType = ConditionalType.Equal, FieldValue = user.UserId });
return (queryable.Where(contidions), "self"); //查询自身
}
var ruleInfo = tenantDb.Queryable().First(x => x.Id == (long)rule.VisibleTemplateId);
if (ruleInfo.RuleScope == "all")
{
return (queryable.ClearFilter(), ruleInfo.RuleScope); //查询全部
}
else if (ruleInfo.RuleScope == "none")
{
if (isTask)
{ return (queryable, ruleInfo.RuleScope); }
else
{
SqlSugar.Check.ExceptionEasy("NO Operation", "没有数据查看权限!");//返回提示
}
}
else if (ruleInfo.RuleScope == "self_org")
{
if (isTask) queryable.Filter(typeof(IOrgId));
var conditionalModels = ConvertConditionalModel(ruleInfo.DataRules);
if (conditionalModels.Count > 0)
{
return (queryable.Where(conditionalModels), ruleInfo.RuleScope);//自定义查询
}
else
{
return (queryable, ruleInfo.RuleScope);//默认查询
}
}
else if (ruleInfo.RuleScope == "self_org_with_child") // 当前机构及下属机构
{
List orgList = await db.Queryable().ToChildListAsync(s => s.ParentId, user.OrgId);
IEnumerable orgIdList = orgList.Select(x => x.Id);
contidions.Add(new ConditionalModel { FieldName = "OrgId", ConditionalType = ConditionalType.In, FieldValue = string.Join(",", orgIdList) });
return (queryable.Where(contidions), ruleInfo.RuleScope);
}
else if (ruleInfo.RuleScope == "self")
{
var conditionalModels = ConvertConditionalModel(ruleInfo.DataRules);
if (conditionalModels.Count > 0)
{
return (queryable.Where(conditionalModels), ruleInfo.RuleScope);//自定义查询
}
else
{
contidions.Add(new ConditionalModel { FieldName = "CreateBy", ConditionalType = ConditionalType.Equal, FieldValue = user.UserId });
return (queryable.Where(contidions), ruleInfo.RuleScope); //查询创建人自身信息
}
}
else if (ruleInfo.RuleScope == "self_dept")
{
if (String.IsNullOrEmpty(userInfo.DeptName))
{
if (!isTask)
{
SqlSugar.Check.ExceptionEasy("NO Operation", "当前员工没有默认归属部门!");
}
}
var conditionalModels = ConvertConditionalModel(ruleInfo.DataRules);
if (conditionalModels.Count > 0)
{
return (queryable.Where(conditionalModels), ruleInfo.RuleScope);//自定义查询
}
else
{
var deptUsers = db.Queryable().Where(x => x.DeptId == userInfo.DeptId).Select(x => x.Id).ToList();
contidions.Add(new ConditionalModel { FieldName = "CreateBy", ConditionalType = ConditionalType.In, FieldValue = string.Join(",", deptUsers) });
return (queryable.Where(contidions), ruleInfo.RuleScope); //查询本部门
}
}
else if (ruleInfo.RuleScope == "select_org")
{
var conditionalModels = ConvertConditionalModel(ruleInfo.DataRules);
//var conditions = ruleInfo.DataRules.ConvertSqlSugarExpression();
//var conditionalModels =
// db.ConfigQuery.Context.Utilities.JsonToConditionalModels(
// JsonConvert.SerializeObject(conditions));
return (queryable.ClearFilter().Where(conditionalModels), ruleInfo.RuleScope); //查询指定机构
}
else if (ruleInfo.RuleScope == "select_user")
{
//var conditionalModels = ConvertConditionalModel(ruleInfo.DataRules);
var conditionalModels = ConvertConditionalModel(ruleInfo.DataRules);
return (queryable.ClearFilter().Where(conditionalModels), ruleInfo.RuleScope);//查询指定人员
}
else if (ruleInfo.RuleScope == "customize")
{
//var conditionalModels = ConvertConditionalModel(ruleInfo.DataRules);
var conditionalModels = ConvertConditionalModel(ruleInfo.DataRules);
return (queryable.Where(conditionalModels), ruleInfo.RuleScope);//自定义查询
}
else if (ruleInfo.DataRules.IsNull())
{
contidions.Add(new ConditionalModel { FieldName = "CreateBy", ConditionalType = ConditionalType.Equal, FieldValue = user.UserId });
return (queryable.Where(contidions), ruleInfo.RuleScope); //没有设置数据规则,那么视为该资源允许被创建人查看
}
return (queryable, ruleInfo.RuleScope);
#endregion
}
}
///
/// 获取当前用户的可视权限范围
///
///
///
///
public async Task<(ISugarQueryable queryable, string? ruleScope, List? contidions)> GetSpecialVisibleDataRuleFilter(ISugarQueryable queryable,SqlSugarScopeProvider tenantDb)
{
// 因为TaskBaseAllocation不能继承IOrgId,所以在这里根据条件,在需要的时候手动添加IOrgId查询筛选器
bool isTask = typeof(T) == typeof(TaskBaseAllocation);
var contidions = new List();
var otherContidions = new List();
var userInfo = db.Queryable().First(x => x.Id == long.Parse(user.UserId));
if (userInfo.UserType == 0)
{
if (isTask) queryable.Filter(typeof(IOrgId));
return (queryable, "all", otherContidions); //超级管理员特权
}
var moduleName = typeof(T).Name.ToLower();
var rule = tenantDb.Queryable()
.First(u => u.UserId == long.Parse(user.UserId) && u.PermissionEntity.ToLower() == moduleName && u.Status == StatusEnum.Enable);
if (rule.IsNull())
{
return (queryable, null, otherContidions); //默认查询
}
else
{
#region 可视权限
if ((long)rule.VisibleTemplateId == 0)
{
contidions.Add(new ConditionalModel { FieldName = "CreateBy", ConditionalType = ConditionalType.Equal, FieldValue = user.UserId });
return (queryable.Where(contidions), "self", otherContidions); //查询自身
}
var ruleInfo = tenantDb.Queryable().First(x => x.Id == (long)rule.VisibleTemplateId);
if (ruleInfo.RuleScope == "all")
{
return (queryable.ClearFilter().ClearFilter(), ruleInfo.RuleScope, otherContidions); //查询全部
}
else if (ruleInfo.RuleScope == "none")
{
if (isTask)
{ return (queryable, ruleInfo.RuleScope, otherContidions); }
else
{
SqlSugar.Check.ExceptionEasy("NO Operation", "没有数据查看权限!");//返回提示
}
}
else if (ruleInfo.RuleScope == "self_org")
{
if (isTask) queryable.Filter(typeof(IOrgId));
var conditionalModels = ConvertConditionalModel(ruleInfo.DataRules);
var additions = ConvertConditionalModel(ruleInfo.AdditionDataRules);
if (conditionalModels.Count > 0)
{
return (queryable.Where(conditionalModels), ruleInfo.RuleScope, additions);//自定义查询
}
else
{
return (queryable.Where(contidions), ruleInfo.RuleScope, otherContidions);//默认查询
}
}
else if (ruleInfo.RuleScope == "self_org_with_child") // 当前机构及下属机构
{
List orgList = await db.Queryable().ToChildListAsync(s => s.ParentId, user.OrgId);
IEnumerable orgIdList = orgList.Select(x => x.Id);
contidions.Add(new ConditionalModel { FieldName = "OrgId", ConditionalType = ConditionalType.In, FieldValue = string.Join(",", orgIdList) });
return (queryable.Where(contidions), ruleInfo.RuleScope, otherContidions);
}
else if (ruleInfo.RuleScope == "self")
{
var conditionalModels = ConvertConditionalModel(ruleInfo.DataRules);
var additions = ConvertConditionalModel(ruleInfo.AdditionDataRules);
if (conditionalModels.Count > 0)
{
return (queryable.Where(conditionalModels), ruleInfo.RuleScope, additions);//自定义查询
}
else
{
contidions.Add(new ConditionalModel { FieldName = "CreateBy", ConditionalType = ConditionalType.Equal, FieldValue = user.UserId });
return (queryable.Where(contidions), ruleInfo.RuleScope, otherContidions); //查询创建人自身信息
}
}
else if (ruleInfo.RuleScope == "self_dept")
{
if (String.IsNullOrEmpty(userInfo.DeptName))
{
if (!isTask)
{
SqlSugar.Check.ExceptionEasy("NO Operation", "当前员工没有默认归属部门!");
}
}
var conditionalModels = ConvertConditionalModel(ruleInfo.DataRules);
var additions = ConvertConditionalModel(ruleInfo.AdditionDataRules);
if (conditionalModels.Count > 0)
{
return (queryable.Where(conditionalModels), ruleInfo.RuleScope, additions);//自定义查询
}
else
{
var deptUsers = db.Queryable().Where(x => x.DeptId == userInfo.DeptId).Select(x => x.Id).ToList();
contidions.Add(new ConditionalModel { FieldName = "CreateBy", ConditionalType = ConditionalType.In, FieldValue = string.Join(",", deptUsers) });
return (queryable.Where(contidions), ruleInfo.RuleScope, additions); //查询本部门
}
}
else if (ruleInfo.RuleScope == "select_org")
{
var conditionalModels = ConvertConditionalModel(ruleInfo.DataRules);
//var conditions = ruleInfo.DataRules.ConvertSqlSugarExpression();
//var conditionalModels =
// db.ConfigQuery.Context.Utilities.JsonToConditionalModels(
// JsonConvert.SerializeObject(conditions));
var additions = ConvertConditionalModel(ruleInfo.AdditionDataRules);
return (queryable.ClearFilter().ClearFilter().Where(conditionalModels), ruleInfo.RuleScope, additions); //查询指定机构
}
else if (ruleInfo.RuleScope == "select_user")
{
//var conditionalModels = ConvertConditionalModel(ruleInfo.DataRules);
var conditionalModels = ConvertConditionalModel(ruleInfo.DataRules);
var additions = ConvertConditionalModel(ruleInfo.AdditionDataRules);
return (queryable.ClearFilter().ClearFilter().Where(conditionalModels), ruleInfo.RuleScope, additions);//查询指定人员
}
else if (ruleInfo.RuleScope == "customize")
{
//var conditionalModels = ConvertConditionalModel(ruleInfo.DataRules);
var conditionalModels = ConvertConditionalModel(ruleInfo.DataRules);
var additions = ConvertConditionalModel(ruleInfo.AdditionDataRules);
return (queryable.Where(conditionalModels), ruleInfo.RuleScope, additions);//自定义查询
}
else if (ruleInfo.DataRules.IsNull())
{
contidions.Add(new ConditionalModel { FieldName = "CreateBy", ConditionalType = ConditionalType.Equal, FieldValue = user.UserId });
return (queryable.Where(contidions), ruleInfo.RuleScope, otherContidions); //没有设置数据规则,那么视为该资源允许被创建人查看
}
return (queryable, ruleInfo.RuleScope, otherContidions);
#endregion
}
}
private List ConvertConditionalModel(string rules)
{
if (!string.IsNullOrEmpty(rules))
{
if (rules.Contains(DataRuleConst.LoginUser))
{
//即把{loginUser} =='xxxxxxx'换为 user.UserId =='xxxxxxx',从而把当前登录的用户名与当时设计规则时选定的用户id对比
rules = rules.Replace(DataRuleConst.LoginUser, user.UserId);
}
if (rules.Contains(DataRuleConst.LoginOrg))
{
rules = rules.Replace(DataRuleConst.LoginOrg, user.OrgId.ToString());
}
if (rules.Contains(DataRuleConst.LoginDept))
{
var userInfo = db.Queryable().First(x => x.Id == long.Parse(user.UserId));
var deptUsers = db.Queryable().Where(x => x.DeptId == userInfo.DeptId).Select(n=>n.Id).ToArray();
//rules = rules.Replace(DataRuleConst.LoginDept, deptUsers.ToString());
//rules = rules.Replace(DataRuleConst.LoginDept, "(" + string.Join(",", deptUsers) + ")");
//rules = rules.Replace(DataRuleConst.LoginDept, userInfo.DeptId.ToString());
rules = rules.Replace(DataRuleConst.LoginDept, string.Join(",", deptUsers));
}
var conditions = rules.ConvertSqlSugarExpression();
var conditionalModels =
db.ConfigQuery.Context.Utilities.JsonToConditionalModels(
JsonConvert.SerializeObject(conditions));
return conditionalModels;
}
else
{
return new List();
}
}
#endregion
#region 获取数据库表及字段属性
///
/// 获取数据库表
///
///
public DataResult> GetTables()
{
var data = db.DbMaintenance.GetTableInfoList();
return DataResult>.Success("获取数据成功", data);
}
///
/// 获取数据库表字段
///
///
///
public DataResult> GetColumns(string tableViewName)
{
var data = db.DbMaintenance.GetColumnInfosByTableName(tableViewName);
return DataResult>.Success("获取数据成功", data);
}
///
/// 获取数据库表-按客户
///
///
public DataResult> GetTablesByClient()
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var data = tenantDb.DbMaintenance.GetTableInfoList();
return DataResult>.Success("获取数据成功", data);
}
///
/// 获取数据库表字段-按客户
///
///
///
public DataResult> GetColumnsByClient(string tableViewName)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var data = tenantDb.DbMaintenance.GetColumnInfosByTableName(tableViewName);
return DataResult>.Success("获取数据成功", data);
}
#endregion
#region 用户字段设置
///
/// 获取用户字段设置
///
///
/// 标识序号
///
public DataResult GetUserFieldSet(string permissionId, int tagNo = 0)
{
var info = db.Queryable()
.Where(x => x.UserId == long.Parse(user.UserId) && x.PermissionId == long.Parse(permissionId) && x.TagNo == tagNo).First();
return DataResult.Success(info);
}
///
/// 批量获取任务台用户字段设置
///
///
public async Task>> GetUserTaskPlatFieldSet(SysFieldSetTaskPlatQueryDto query)
{
if (query.TaskTypeCodeArray == null || query.TaskTypeCodeArray.Length == 0)
{
return DataResult>.Success(null);
}
long userId = long.Parse(user.UserId);
Dictionary tagNoDic = new(query.TaskTypeCodeArray.Length);
foreach (var item in query.TaskTypeCodeArray)
{
if (item.ToUpper() == TASK_PLAT_BASIC_CODE)
{
var typeInt = -1;
if (!tagNoDic.ContainsKey(typeInt))
{
tagNoDic.Add(typeInt, TASK_PLAT_BASIC_CODE);
}
}
else
{
if (Enum.TryParse(typeof(TaskBaseTypeEnum), item, out object? typeEnum))
{
var typeInt = (int)typeEnum;
if (!tagNoDic.ContainsKey(typeInt))
{
tagNoDic.Add(typeInt, item);
}
}
}
}
var tenantId = long.Parse(user.TenantId);
var tagNoList = tagNoDic.Select(x => x.Key);
var infoList = await db.Queryable()
.Where(x => x.PermissionId == long.Parse(query.PermissionId) && x.TenantId == tenantId && tagNoList.Contains(x.TagNo))
.WhereIF(query.IsGetDefault, x => x.UserId == 0)
.WhereIF(!query.IsGetDefault, x => (x.UserId == userId || x.UserId == 0))
.Select(x => new SysFieldSetTaskPlatResultDto(), true)
.ToListAsync();
var result = new List();
foreach (var item in tagNoDic)
{
var temp = infoList.FirstOrDefault(x => x.TagNo == item.Key && x.UserId == userId);
if (temp != null)
{
temp.IsDefault = false;
temp.TaskTypeCode = item.Value;
result.Add(temp);
}
else
{
temp = infoList.FirstOrDefault(x => x.TagNo == item.Key);
if (temp != null)
{
temp.IsDefault = true;
temp.TaskTypeCode = item.Value;
result.Add(temp);
}
}
}
return DataResult>.Success(result);
}
///
/// 更新用户字段设置
///
///
///
public DataResult UpdateUserFieldSet(UserFieldSetUpdateReq req)
{
var info = db.Queryable()
.Where(x => x.UserId == long.Parse(user.UserId) && x.PermissionId == req.PermissionId && x.TagNo == req.TagNo).First();
if (info.IsNull())
{
var entity = new SysFieldSet
{
UserId = long.Parse(user.UserId),
TagNo = req.TagNo,
PermissionId = req.PermissionId,
Content = req.Content
};
db.Insertable(entity).ExecuteCommand();
}
else
{
info.Content = req.Content;
db.Updateable(info).ExecuteCommand();
}
return DataResult.Successed("更新成功");
}
///
/// 更新任务台用户字段设置
///
public async Task UpdateUserTaskPlatFieldSet(UserFieldSetUpdateReq req)
{
int tagNo;
if (req.TaskTypeCode.ToUpper() == TASK_PLAT_BASIC_CODE)
{
tagNo = -1;
}
else if (Enum.TryParse(typeof(TaskBaseTypeEnum), req.TaskTypeCode, out object? type))
{
tagNo = (int)type;
}
else
{
throw new Exception(nameof(req.TaskTypeCode) + "取值有误:" + req.TaskTypeCode);
}
var tenantId = long.Parse(user.TenantId);
var userId = long.Parse(user.UserId);
var info = await db.Queryable()
.Where(x => x.PermissionId == req.PermissionId && x.TenantId == tenantId && x.TagNo == tagNo)
.WhereIF(req.IsSetDefault, x => x.UserId == 0)
.WhereIF(!req.IsSetDefault, x => x.UserId == userId)
.FirstAsync();
if (info.IsNull())
{
var entity = new SysFieldSet
{
UserId = req.IsSetDefault ? 0 : userId,
PermissionId = req.PermissionId,
Content = req.Content,
TenantId = tenantId,
TagNo = tagNo,
};
await db.Insertable(entity).ExecuteCommandAsync();
}
else
{
info.Content = req.Content;
await db.Updateable(info).ExecuteCommandAsync();
}
return DataResult.Successed("更新成功");
}
#endregion
#region 获取字典值
///
/// 获取下拉字典
///
///
///
public DataResult GetDictTypeDropDown(DropDownDictTypeInput req)
{
var language = IhttpContext.HttpContext.Request.Headers["LanguageType"].FirstOrDefault();
var code = req.Code;
if (language.IsNullOrEmpty())
{
language = "CN";
}
language = language.ToUpper();
var type = db.Queryable().Where(x => x.Code == req.Code && x.Status == StatusEnum.Enable).First();
if (type.IsNull())
{
return DataResult.Failed("字典类型不存在!");
}
var dictValues = new List();
if (language == "CN")
{
dictValues = db.Queryable().Where(x => x.TypeId == type.Id && x.Status == StatusEnum.Enable)
.Select().ToList();
}
else if (language == "EN")
{
if (db.Queryable().Where(x => x.TypeId == type.Id && x.Status == StatusEnum.Enable && string.IsNullOrEmpty(x.EnName)).Any())
{
//return DataResult.Failed(string.Format("未配置语言代码:{0}下的字典代码:{1}", language, code), MultiLanguageConst.DictCodeLanguageNoConfig);
return DataResult.FailedWithPlaceholder(db, IhttpContext, MultiLanguageConst.DictCodeLanguageNoConfig, language, code);
}
dictValues = db.Queryable().Where(x => x.TypeId == type.Id && x.Status == StatusEnum.Enable)
.Select(x => new DropDownData
{
Name = x.EnName,
Value = x.Value,
}).ToList();
}
else if (language == "AR")
{
if (db.Queryable().Where(x => x.TypeId == type.Id && x.Status == StatusEnum.Enable && string.IsNullOrEmpty(x.ArName)).Any())
{
return DataResult.FailedWithPlaceholder(db, IhttpContext, MultiLanguageConst.DictCodeLanguageNoConfig, language, code);
}
dictValues = db.Queryable().Where(x => x.TypeId == type.Id && x.Status == StatusEnum.Enable)
.Select(x => new DropDownData
{
Name = x.ArName,
Value = x.Value,
}).ToList();
}
else if (language == "FR")
{
if (db.Queryable().Where(x => x.TypeId == type.Id && x.Status == StatusEnum.Enable && string.IsNullOrEmpty(x.FrName)).Any())
{
return DataResult.FailedWithPlaceholder(db, IhttpContext, MultiLanguageConst.DictCodeLanguageNoConfig, language, code);
}
dictValues = db.Queryable().Where(x => x.TypeId == type.Id && x.Status == StatusEnum.Enable)
.Select(x => new DropDownData
{
Name = x.FrName,
Value = x.Value,
}).ToList();
}
else if (language == "RU")
{
if (db.Queryable().Where(x => x.TypeId == type.Id && x.Status == StatusEnum.Enable && string.IsNullOrEmpty(x.RuName)).Any())
{
return DataResult.FailedWithPlaceholder(db, IhttpContext, MultiLanguageConst.DictCodeLanguageNoConfig, language, code);
}
dictValues = db.Queryable().Where(x => x.TypeId == type.Id && x.Status == StatusEnum.Enable)
.Select(x => new DropDownData
{
Name = x.ArName,
Value = x.Value,
}).ToList();
}
else if (language == "ES")
{
if (db.Queryable().Where(x => x.TypeId == type.Id && x.Status == StatusEnum.Enable && string.IsNullOrEmpty(x.EsName)).Any())
{
return DataResult.FailedWithPlaceholder(db, IhttpContext, MultiLanguageConst.DictCodeLanguageNoConfig, language, code);
}
dictValues = db.Queryable().Where(x => x.TypeId == type.Id && x.Status == StatusEnum.Enable)
.Select(x => new DropDownData
{
Name = x.ArName,
Value = x.Value,
}).ToList();
}
//var data = language == "CN"
// ? db.Queryable().Where(x => x.TypeId == type.Id && x.Status == StatusEnum.Enable)
// .Select().ToList()
// : db.Queryable().Where(x => x.TypeId == type.Id && x.Status == StatusEnum.Enable)
// .Select(x => new DropDownData
// {
// Name = x.EnName,
// Value = x.Value,
// }).ToList();
return DataResult.Successed("获取字典成功!", dictValues);
}
///
/// 批量获取字典值
///
///
///
public DataResult> GetDictOptions(DropDownDictTypeInput model)
{
var language = IhttpContext.HttpContext.Request.Headers["LanguageType"].FirstOrDefault().ToUpper();
if (language.IsNullOrEmpty())
{
language = "CN";
}
var codes = model.Code.Split(',');
if (codes.Length == 0)
{
return DataResult>.Failed("请传入正确的字典代码!");
}
var types = db.Queryable().Where(x => codes.Contains(x.Code) && x.Status == StatusEnum.Enable)
.ToList();
var list = new List