You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

811 lines
28 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using DS.Module.Core;
using DS.Module.Core.Extensions;
using DS.Module.Core.Helpers;
using DS.Module.UserModule;
using DS.WMS.Core.System.Dtos;
using DS.WMS.Core.System.Entity;
using DS.WMS.Core.System.Interface;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Mapster;
using Newtonsoft.Json;
namespace DS.WMS.Core.System.Method;
/// <summary>
/// 公共服务
/// </summary>
public class CommonService : ICommonService
{
private readonly IServiceProvider _serviceProvider;
private readonly ISqlSugarClient db;
private readonly IUser user;
private readonly IHttpContextAccessor IhttpContext;
private readonly IWebHostEnvironment _environment;
/// <summary>
///
/// </summary>
/// <param name="serviceProvider"></param>
public CommonService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
db = _serviceProvider.GetRequiredService<ISqlSugarClient>();
user = _serviceProvider.GetRequiredService<IUser>();
IhttpContext = _serviceProvider.GetRequiredService<IHttpContextAccessor>();
_environment = _serviceProvider.GetRequiredService<IWebHostEnvironment>();
}
#region 后台登录
/// <summary>
/// 用户登录
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public DataResult<string> UserLogin(UserLoginModel model)
{
var userInfo = db.Queryable<SysUser>().Filter(null, true)
.First(x => x.UserCode == model.UserName);
if (userInfo == null)
{
return DataResult<string>.Failed("账号不存在,请检查!");
}
if (userInfo.MD5Password != model.Password)
{
return DataResult<string>.Failed("密码错误!");
}
var tokenModel = new JwtHelper.JwtTokenModel
{
Uid = userInfo.Id.ToString(),
// CompanyId = userInfo.CompanyId,
// GID = userInfo.GID,
TenantId = userInfo.TenantId.ToString(),
};
var token = JwtHelper.Encrypt(tokenModel);
return DataResult<string>.Success(token);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public DataResult<CurrentUserViewModel> GetUserInfo()
{
var userId = long.Parse(user.UserId);
var tenantId = user.GetTenantId();
var data = db.Queryable<SysUser>().Filter(null, true).Where(x => x.Id == userId)
.Select(a => new CurrentUserViewModel
{
UserId = a.Id,
UserCode = a.UserCode,
UserName = a.NickName,
TenantId = tenantId,
UserType = a.UserType,
CompanyId = a.CompanyId,
ClientId = a.ClientId,
IsLimitClient = a.IsLimitClient
// CompanyId = a.CompanyId.ToString(), CompanyName = a.CustomerName
})
.Mapper(it =>
{
//只能写在Select后面
it.HomePath = "/analysis";
})
.First();
return DataResult<CurrentUserViewModel>.Success(data);
}
/// <summary>
/// 查询用户拥有的菜单权限
/// </summary>
/// <returns></returns>
public DataResult<List<RouteItem>> GetUserPermissionByToken()
{
List<RouteItem> list = new List<RouteItem>();
var userId = long.Parse(user.UserId);
var userInfo = db.Queryable<SysUser>().Filter(null, true).Where(x => x.Id == userId).First();
//超级管理员
if (userInfo.UserType == 0)
{
list = db.Queryable<SysPermission>().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<SysPermission>().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
{
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<SysRoleUser>().Where(x => x.UserId == userId).Select(x => x.RoleId).ToList();
var permissions = db.Queryable<SysRolePermission>().Where(x => roleIds.Contains(x.RoleId))
.Select(x => x.PermissionId).Distinct().ToList();
var perlist = db.Queryable<SysPermission>()
.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<SysPermission>().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
{
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<List<RouteItem>>.Success("获取数据成功!", list);
}
#endregion
#region 客户端登录
/// <summary>
/// 用户登录
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public DataResult<string> ClientUserLogin(UserLoginModel model)
{
var userInfo = db.Queryable<SysUser>().Filter(null, true)
.First(x => x.UserCode == model.UserName);
if (userInfo == null)
{
return DataResult<string>.Failed("账号不存在,请检查!");
}
if (userInfo.MD5Password != model.Password)
{
return DataResult<string>.Failed("密码错误!");
}
var tokenModel = new JwtHelper.JwtTokenModel
{
Uid = userInfo.Id.ToString(),
// CompanyId = userInfo.CompanyId,
// GID = userInfo.GID,
TenantId = userInfo.TenantId.ToString(),
};
var token = JwtHelper.Encrypt(tokenModel);
return DataResult<string>.Success(token);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public DataResult<CurrentUserViewModel> GetClientUserInfo()
{
var userId = long.Parse(user.UserId);
var tenantId = user.GetTenantId();
var data = db.Queryable<SysUser>().Filter(null, true).Where(x => x.Id == userId)
.Select(a => new CurrentUserViewModel
{
UserId = a.Id,
UserCode = a.UserCode,
UserName = a.NickName,
TenantId = tenantId,
UserType = a.UserType,
CompanyId = a.CompanyId,
ClientId = a.ClientId,
IsLimitClient = a.IsLimitClient
// CompanyId = a.CompanyId.ToString(), CompanyName = a.CustomerName
})
.Mapper(it =>
{
//只能写在Select后面
it.HomePath = "/analysis";
})
.First();
return DataResult<CurrentUserViewModel>.Success(data);
}
/// <summary>
/// 查询客户 用户拥有的菜单权限
/// </summary>
/// <returns></returns>
public DataResult<List<RouteItem>> GetClientUserPermissionByToken()
{
List<RouteItem> list = new List<RouteItem>();
var userId = long.Parse(user.UserId);
var userInfo = db.Queryable<SysUser>().Where(x => x.Id == userId).First();
//超级管理员
if (userInfo.UserType == 0)
{
list = db.Queryable<SysPermissionTenant>().Where(x =>
x.MenuType == 1 && x.IsHidden == false && (x.PermissionType == 1 || x.PermissionType == 0))
.OrderBy(x => x.SortCode)
.Select(a => new RouteItem
{
Id = a.PermissionId,
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<SysPermissionTenant>().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
{
Path = a.Url,
Name = a.PermissionName,
Component = a.Component,
Meta = new RouteMeta()
{
Title = a.Title,
Icon = a.Icon,
}
}).ToList();
item.Children = childs;
}
}
else if (userInfo.UserType == 3) //租户申请用户
{
var roleIds = db.Queryable<SysRoleUser>().Where(x => x.UserId == userId).Select(x => x.RoleId).ToList();
var permissions = db.Queryable<SysRolePermission>().Where(x => roleIds.Contains(x.RoleId))
.Select(x => x.PermissionId).Distinct().ToList();
var perlist = db.Queryable<SysPermission>()
.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<SysPermission>().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
{
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;
}
}
else
{
var roleIds = db.Queryable<SysRoleUser>().Where(x => x.UserId == userId).Select(x => x.RoleId).ToList();
var permissions = db.Queryable<SysRolePermission>().Where(x => roleIds.Contains(x.RoleId))
.Select(x => x.PermissionId).Distinct().ToList();
var perlist = db.Queryable<SysPermissionTenant>()
.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.PermissionId,
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<SysPermissionTenant>().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
{
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<List<RouteItem>>.Success("获取数据成功!", list);
}
#endregion
#region 客户端通用
/// <summary>
/// 获取权限树列表-客户端
/// </summary>
/// <returns></returns>
public DataResult<List<PermissionTreeList>> GetClientPermissionTreeList()
{
var list = db.Queryable<SysPermission>()
.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,
Key = a.Id,
Icon = a.Icon
})
.ToList();
foreach (var item in list)
{
var childs = db.Queryable<SysPermission>().Where(x =>
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,
Key = a.Id,
Icon = a.Icon
}).ToList();
item.Children = childs;
}
return DataResult<List<PermissionTreeList>>.Success("获取数据成功!", list);
}
#endregion
#region 获取服务器信息
/// <summary>
/// 获取服务器信息
/// </summary>
/// <returns></returns>
public DataResult<dynamic> GetServerInfo()
{
//核心数
int cpuNum = Environment.ProcessorCount;
string computerName = Environment.MachineName;
string osName = RuntimeInformation.OSDescription;
string osArch = RuntimeInformation.OSArchitecture.ToString();
string version = RuntimeInformation.FrameworkDescription;
string appRAM = ((double)Process.GetCurrentProcess().WorkingSet64 / 1048576).ToString("N2") + " MB";
string startTime = Process.GetCurrentProcess().StartTime.ToString("yyyy-MM-dd HH:mm:ss");
string sysRunTime = ComputerHelper.GetRunTime();
string serverIP = IhttpContext.HttpContext.Connection.LocalIpAddress.MapToIPv4().ToString() + ":"
+ IhttpContext.HttpContext.Connection.LocalPort; //获取服务器IP
var programStartTime = Process.GetCurrentProcess().StartTime;
string programRunTime =
DateTimeHelper.FormatTime((DateTime.Now - programStartTime).TotalMilliseconds.ToString().Split('.')[0]
.ParseToLong());
var data = new
{
cpu = ComputerHelper.GetComputerInfo(),
disk = ComputerHelper.GetDiskInfos(),
sys = new { cpuNum, computerName, osName, osArch, serverIP, runTime = sysRunTime },
app = new
{
name = _environment.EnvironmentName,
rootPath = _environment.ContentRootPath,
webRootPath = _environment.WebRootPath,
version,
appRAM,
startTime,
runTime = programRunTime,
host = serverIP
},
};
return DataResult<dynamic>.Success(data);
}
#endregion 获取服务器信息
#region 获取角色下拉列表
/// <summary>
/// 获取角色下拉列表
/// </summary>
/// <returns></returns>
public DataResult<List<ApiSelectViewModel>> GetRoleList()
{
var list = db.Queryable<SysRole>()
.Select(a => new ApiSelectViewModel
{
Label = a.RoleName,
Value = a.Id,
})
.ToList();
return DataResult<List<ApiSelectViewModel>>.Success("获取数据成功!", list);
}
#endregion 获取角色下拉列表
#region 修改密码
/// <summary>
/// 修改密码
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public DataResult ChangePassword(ChangePasswordReq model)
{
var userId = long.Parse(user.UserId);
var userInfo = db.Queryable<SysUser>().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 租户注册
/// <summary>
/// 租户注册
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
public DataResult TenantRegister(TenantRegisterReq req)
{
if (!req.Policy)
{
return DataResult.Failed("请阅读并勾选合同规定!");
}
var existApply = db.Queryable<SysTenantApply>().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<SysTenantApply>().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<SysTenantApply>().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<SysTenantApply>();
// 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),
NickName = req.AdminUserCode,
Email = "",
Phone = req.Phone,
UserType = UserTypeEnum.ApplyUser.ToEnumInt(), //管理员
Status = 0, //正常
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();
return DataResult.Failed("企业注册失败!" + ex);
}
}
#endregion
public DataResult<List<EntityFieldProperty>> GetDataRuleEntityFields(string permissionId)
{
// var query = GetDataRuleFilter<SysUser>();
// SysUser us = new SysUser();
// var temp = us.GetEntityFieldProperty();
var role = new EntityFieldProperty()
{
FieldName = ComonConst.DataRule_LoginRole,
FieldComment = "当前登录用户的角色",
FieldType = "String"
};
var permission = db.Queryable<SysPermission>().First(x => x.Id == long.Parse(permissionId));
if (permission.IsNull())
{
return DataResult<List<EntityFieldProperty>>.Failed("权限模块不存在!");
}
var list = permission.PermissionEntity.GetEntityFieldByName();
// var entity = db.EntityMaintenance.GetEntityInfo(permission.PermissionEntity.GetEntity());
// var list = entity.GetEntityFieldByName();
if (list.Count == 0)
{
return DataResult<List<EntityFieldProperty>>.Failed("请配置实体属性!");
}
list.Add(role);
return DataResult<List<EntityFieldProperty>>.Success(list);
}
/// <summary>
/// 获取当前登录用户的数据访问权限
/// </summary>
/// <param name="parametername">linq表达式参数的名称如u=>u.name中的"u"</param>
/// <returns></returns>
public ISugarQueryable<T> GetDataRuleFilter<T>()
{
var userInfo = db.Queryable<SysUser>().First(x => x.Id == long.Parse(user.UserId));
if (userInfo.UserType == 0)
{
return db.Queryable<T>(); //超级管理员特权
}
var moduleName = typeof(T).Name;
var rule = db.Queryable<SysDataRule>().First(u => u.PermissionName == moduleName);
if (rule == null) return db.Queryable<T>(); //没有设置数据规则,那么视为该资源允许被任何主体查看
var ruleConditions = JsonConvert.DeserializeObject<DataRuleJson>(rule.DataRules);
if (ruleConditions.RoleCondition.Count > 0)
{
var roles = db.Queryable<SysRoleUser>().Where(x => x.UserId == long.Parse(user.UserId))
.Select(u => u.RoleId.ToString()).ToList();
roles.Sort(); //按字母排序,这样可以进行like操作
var ruleCondition = ruleConditions.RoleCondition[0];
if (ruleCondition.ConditionalType == SqlSugar.ConditionalType.In)
{
var s = ruleCondition.FieldValue.Split(',');
var intersectArr = roles.Intersect(s);
if (intersectArr.Count() == 0)
{
throw new Exception("该用户角色无权限!");
}
}
}
if (ruleConditions.QueryCondition.Count > 0)
{
return db.Queryable<T>()
.Where(ruleConditions.QueryCondition);
}
else
{
return db.Queryable<T>();
}
}
#region 获取数据库表及字段属性
/// <summary>
///
/// </summary>
/// <returns></returns>
public DataResult<List<DbTableInfo>> GetTables()
{
var data = db.DbMaintenance.GetTableInfoList();
return DataResult<List<DbTableInfo>>.Success("获取数据成功",data);
}
/// <summary>
///
/// </summary>
/// <param name="tableViewName"></param>
/// <returns></returns>
public DataResult<List<DbColumnInfo>> GetColumns(string tableViewName)
{
var data = db.DbMaintenance.GetColumnInfosByTableName(tableViewName);
return DataResult<List<DbColumnInfo>>.Success("获取数据成功",data);
}
#endregion
}