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;
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;
///
///
///
///
public CommonService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
db = _serviceProvider.GetRequiredService();
user = _serviceProvider.GetRequiredService();
saasService = _serviceProvider.GetRequiredService();
IhttpContext = _serviceProvider.GetRequiredService();
_environment = _serviceProvider.GetRequiredService();
}
#region 后台登录
///
/// 用户登录
///
///
///
public DataResult UserLogin(UserLoginModel model)
{
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(),
};
var token = JwtHelper.Encrypt(tokenModel);
return DataResult.Success(token);
}
///
/// 获取用户信息
///
///
public DataResult GetUserInfo()
{
var userId = long.Parse(user.UserId);
var tenantId = user.GetTenantId();
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,
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.NickName,
TenantId = tenantId,
UserType = a.UserType,
CompanyId = a.CompanyId,
// ClientId = a.ClientId,
IsLimitClient = a.IsLimitClient,
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 = user.GetTenantId();
var tokenModel = new JwtHelper.JwtTokenModel
{
Uid = user.UserId,
Name = db.Queryable().Filter(null, true).First(x => x.Id == userId).UserName,
TenantId = tenantId.ToString(),
};
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(user.UserId);
var tenantId = user.GetTenantId();
var orgId = user.GetOrgId();
var tokenModel = new JwtHelper.JwtTokenModel
{
Uid = user.UserId,
Name = db.Queryable().Filter(null, true).First(x => x.Id == userId).UserName,
OrgId = orgId.ToString(),
TenantId = tenantId.ToString(),
};
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 DataResult ClientUserLogin(UserLoginModel model)
{
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.DefaultOrgId.ToString(),
TenantId = userInfo.TenantId.ToString(),
};
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 = "登录成功"
};
saasService.GetLogDb().Insertable(visLog).ExecuteCommand();
return DataResult.Success(token);
}
///
///
///
///
public DataResult GetClientUserInfo()
{
var userId = long.Parse(user.UserId);
var tenantId = user.GetTenantId();
//取第一个机构
var orgRelations = 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
})
.ToList();
var tokenModel = new JwtHelper.JwtTokenModel
{
Uid = user.UserId,
Name = db.Queryable().Filter(null, true).First(x => x.Id == userId).UserName,
OrgId = user.GetOrgId().ToString(),
TenantId = tenantId.ToString(),
};
var refreshToken = JwtHelper.Encrypt(tokenModel, true, true);
var data = db.Queryable().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,
RefreshToken = refreshToken,
OrgId = user.GetOrgId().ToString()
// UserOrgs = orgRelations,
//OrgId = a.OrgId.ToString(), CompanyName = a.CustomerName
})
.Mapper(it =>
{
//只能写在Select后面
it.HomePath = "/analysis";
})
.First();
data.UserOrgs = orgRelations;
return DataResult.Success(data);
}
#region 更换机构
///
/// 更换机构
///
///
///
public DataResult ChangeOrg(string id)
{
var userId = user.UserId;
var tenantId = user.GetTenantId();
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(),
};
var token = new RefreshTokenRes
{
AccessToken = JwtHelper.Encrypt(tokenModel, false, true),
RefreshToken = JwtHelper.Encrypt(tokenModel, true, true)
};
return DataResult.Success(token);
}
#endregion
///
/// 查询客户 用户拥有的菜单权限
///
///
public DataResult> GetClientUserPermissionByToken()
{
List list = new List();
var userId = long.Parse(user.UserId);
var userInfo = db.Queryable().Where(x => x.Id == userId).First();
//超级管理员
if (userInfo.UserType == UserTypeEnum.SupperAdmin.ToEnumInt())
{
list = 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,
}
})
.ToList();
foreach (var item in list)
{
var childs = 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,
}
}).ToList();
item.Children = childs;
}
}
else if (userInfo.UserType == UserTypeEnum.ApplyUser.ToEnumInt()) //租户申请用户
{
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;
}
}
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.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,
}
})
.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 == 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.ParentId,
Path = a.Url,
Name = a.PermissionName,
EnName = a.PermissionEnName,
Component = a.Component,
IsCache = a.IsCache,
Meta = new RouteMeta()
{
Title = a.Title,
Icon = a.Icon,
}
}).ToList();
//去重
childs.Distinct();
//排序
childs = childs.OrderBy(x => x.SortCode).ToList();
foreach (var child in childs)
{
var grandsons = db.Queryable().Where(x =>
x.MenuType == 2 && x.ParentId == child.Id && x.IsHidden == false &&
permissions.Contains(x.Id)) //获取第三层路由
.OrderBy(x => x.SortCode)
.Select(a => new RouteItem
{
Id = a.Id,
ParentId = a.ParentId,
Path = a.Url,
Name = a.PermissionName,
EnName = a.PermissionEnName,
Component = a.Component,
IsCache = a.IsCache,
Meta = new RouteMeta()
{
Title = a.Title,
Icon = a.Icon,
}
}).ToList();
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 DataResult>.Success("获取数据成功!", list);
}
///
/// 获取客户端按钮权限
///
///
public DataResult GetClientUserPermissionCode() {
var userId = long.Parse(user.UserId);
var roleList = db.Queryable()
.Where(x => x.UserId == userId).Select(n => n.RoleId).ToList();
roleList.Distinct();
var list = 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
).ToArray();
return 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()
{
var list = db.Queryable().Where(a => a.UserType != UserTypeEnum.ApplyUser.ToEnumInt())
.Select(a => new ApiSelectViewModel
{
Label = a.UserName,
Value = a.Id,
})
.ToList();
return DataResult>.Success("获取数据成功!", list);
}
#endregion 获取用户下拉列表
#region 获取机构下拉列表
///
/// 获取机构下拉列表
///
///
public DataResult> GetOrgList()
{
var list = db.Queryable()
.Select(a => new ApiSelectViewModel
{
Label = a.OrgName,
Value = a.Id,
})
.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 DataResult> GetClientPortSelectList()
{
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> 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),
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> 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(); //没有设置数据规则,那么视为该资源允许被任何主体查看
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 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 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("更新成功");
}
#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();
foreach (var item in types)
{
var dictValues = new List();
if (language == "CN")
{
dictValues = db.Queryable().Where(x => x.TypeId == item.Id && x.Status == StatusEnum.Enable)
.Select().ToList();
}
else if (language == "EN")
{
dictValues = db.Queryable().Where(x => x.TypeId == item.Id && x.Status == StatusEnum.Enable)
.Select(x => new DropDownData
{
Name = x.EnName,
Value = x.Value,
}).ToList();
}
else if (language == "AR")
{
dictValues = db.Queryable().Where(x => x.TypeId == item.Id && x.Status == StatusEnum.Enable)
.Select(x => new DropDownData
{
Name = x.ArName,
Value = x.Value,
}).ToList();
}
else if (language == "FR")
{
dictValues = db.Queryable().Where(x => x.TypeId == item.Id && x.Status == StatusEnum.Enable)
.Select(x => new DropDownData
{
Name = x.FrName,
Value = x.Value,
}).ToList();
}
else if (language == "RU")
{
dictValues = db.Queryable().Where(x => x.TypeId == item.Id && x.Status == StatusEnum.Enable)
.Select(x => new DropDownData
{
Name = x.ArName,
Value = x.Value,
}).ToList();
}
else if (language == "ES")
{
dictValues = db.Queryable().Where(x => x.TypeId == item.Id && x.Status == StatusEnum.Enable)
.Select(x => new DropDownData
{
Name = x.ArName,
Value = x.Value,
}).ToList();
}
var temp = new DictOptions
{
DictCode = item.Code,
Data = dictValues
};
list.Add(temp);
}
return DataResult>.Success("获取字典成功!", list);
}
#endregion
#region 获取单据编码
///
/// 获取最新业务单据编码
///
///
public DataResult GetSequenceNext()
{
//生成编号
string sequenceNewNo = "";
#region 获取序号生成器属性
// if (string.IsNullOrWhiteSpace(sequenceName))
// {
// result.ErrMsg = "参数错误:业务编码编号";
// return result.ErrMsg;
// }
var moduleName = typeof(T).Name.ToLower();
//获取序号生成器属性
var sequence = db.Queryable()
.First(u => u.PermissionEntity.ToLower() == moduleName && u.Status == StatusEnum.Enable);
if (sequence != null)
{
var ruleList = db.Queryable().OrderBy(x => x.OrderNo)
.Where(u => u.SequenceId == sequence.Id && u.Status == StatusEnum.Enable).ToList();
if (ruleList.Any())
{
int delimiterNum = 0;
for (global::System.Int32 i = 0; i < ruleList.Count; i++)
{
var item = ruleList[i];
//}
//foreach (var item in ruleList)
//{
delimiterNum++;
switch (item.RuleType)
{
case "const": //常量方式
sequenceNewNo += item.RuleValue;
break;
case "shortdate": //短日期 年2位月2位日期2位
sequenceNewNo += DateTime.Now.ToString("yyyyMMdd").Substring(2);
break;
case "date": //日期,年4位
sequenceNewNo += DateTime.Now.ToString("yyyyMMdd");
break;
case "ydate": //年月,年4位月2位
sequenceNewNo += DateTime.Now.ToString("yyyyMMdd").Substring(0, 6);
break;
case "sydate": //年月,年2位月2位
sequenceNewNo += DateTime.Now.ToString("yyyyMMdd").Substring(2, 4);
break;
case "timestamp": //日期时间精确到毫秒
sequenceNewNo += DateTime.Now.ToString("yyyyMMddHHmmssffff");
break;
case "number": //计数,流水号
int num = CurrentReset(sequence, item);
//计数拼接
sequenceNewNo += NumberingSeqRule(item, num).ToString();
//更新当前序号,
sequence.CurrentNo = num;
break;
case "guid": //Guid
sequenceNewNo += GuidHelper.NewGuidFormatN();
break;
case "random": //随机数
Random random = new Random();
string strMax = "9".ToString().PadLeft(item.RuleValue.Length, '9');
string strRandom = random.Next(item.RuleValue.ToInt(), strMax.ToInt()).ToString(); //生成随机编号
sequenceNewNo += strRandom;
break;
}
if (!string.IsNullOrEmpty(sequence.SequenceDelimiter) && delimiterNum != ruleList.Count())
{
sequenceNewNo += sequence.SequenceDelimiter;
}
}
//当前编号
sequence.CurrentCode = sequenceNewNo;
sequence.CurrentReset = DateTime.Now.ToString("yyyyMMdd");
db.Updateable(sequence).ExecuteCommand();
return DataResult.Success(sequenceNewNo);
}
else
{
return DataResult.Failed("未查询到业务编码对应的编码规则配置, 请检查编码规则配置!");
}
}
else
{
return DataResult.Failed("请定义" + moduleName + "的单据编码!");
}
#endregion
}
///
/// 计数 方式 重置规则
///
///
///
///
private static int CurrentReset(SysSequence seq, SysSequenceRule seqRule)
{
int newNo = 0, ruleNo = 0;
try
{
ruleNo = seqRule.RuleValue.ToInt();
}
catch (Exception ex)
{
newNo = 1;
// Log4NetHelper.Error(ex.Message, ex);
}
switch (seq.SequenceReset)
{
case "D": //每天重置
if (!string.IsNullOrEmpty(seq.CurrentReset) && seq.CurrentReset != DateTime.Now.ToString("yyyyMMdd"))
{
newNo = 1;
}
break;
case "M": //每月重置
if (!string.IsNullOrWhiteSpace(seq.CurrentReset))
{
if (!seq.CurrentReset.Contains(DateTime.Now.ToString("yyyyMM")))
{
newNo = ruleNo;
}
}
else
{
newNo = 1;
}
break;
case "Y": //每年重置
if (!string.IsNullOrWhiteSpace(seq.CurrentReset))
{
if (!seq.CurrentReset.Contains(DateTime.Now.ToString("yyyy")))
{
newNo = ruleNo;
}
}
else
{
newNo = 1;
}
break;
}
if (newNo == 0)
{
if (seq.CurrentNo == 0)
{
newNo = ruleNo;
}
else
{
//当前序号+步长
newNo = seq.CurrentNo + seq.Step;
}
}
return newNo;
}
///
/// 计数规则
///
///
///
///
private static string NumberingSeqRule(SysSequenceRule seqRule, int code)
{
string str = "";
if (seqRule.PaddingSide == "Left")
{
str += code.ToString().PadLeft(seqRule.PaddingWidth, seqRule.PaddingChar.ToChar());
}
if (seqRule.PaddingSide == "Right")
{
str += code.ToString().PadRight(seqRule.PaddingWidth, seqRule.PaddingChar.ToChar());
}
return str;
}
#endregion
#region 租户下拉信息
///
/// 获取付费方式下拉列表-客户端
///
///
public DataResult> GetClientFrtSelectList()
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var list = tenantDb.Queryable()
.Where(x => x.Status == StatusEnum.Enable)
.Select()
.ToList();
return DataResult>.Success("获取数据成功!", list);
}
///
/// 获取结算方式下拉列表-客户端
///
///
public DataResult> GetClientStlModeSelectList()
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var list = tenantDb.Queryable()
.Where(x => x.Status == StatusEnum.Enable)
.Select()
.ToList();
return DataResult>.Success("获取数据成功!", list);
}
///
/// 获取业务来源下拉列表-客户端
///
///
public DataResult> GetClientSourceSelectList()
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var list = tenantDb.Queryable()
.Where(x => x.Status == StatusEnum.Enable)
.Select()
.ToList();
return DataResult>.Success("获取数据成功!", list);
}
///
/// 获取业务来源明细下拉列表-客户端
///
///
public DataResult> GetClientSourceDetailSelectList(string id)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var list = tenantDb.Queryable()
.Where(x => x.Status == StatusEnum.Enable && x.SourceId == long.Parse(id))
.Select()
.ToList();
return DataResult>.Success("获取数据成功!", list);
}
#endregion
}