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.

1615 lines
56 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.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;
namespace DS.WMS.Core.Sys.Method;
/// <summary>
/// 公共服务
/// </summary>
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;
/// <summary>
///
/// </summary>
/// <param name="serviceProvider"></param>
public CommonService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
db = _serviceProvider.GetRequiredService<ISqlSugarClient>();
user = _serviceProvider.GetRequiredService<IUser>();
saasService = _serviceProvider.GetRequiredService<ISaasDbService>();
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(),
Name = userInfo.UserName,
// OrgId = userInfo.OrgId,
// 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 tokenModel = new JwtHelper.JwtTokenModel
{
Uid = user.UserId,
Name = db.Queryable<SysUser>().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<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,
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<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
{
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<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
{
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<List<RouteItem>>.Success("获取数据成功!", list);
}
#region 刷新Token
/// <summary>
/// 后台端刷新Token
/// </summary>
/// <returns></returns>
public DataResult<RefreshTokenRes> UserRefreshToken()
{
var refreshToken = IhttpContext.HttpContext!.Request.Headers["RefreshToken"].First();
if (string.IsNullOrWhiteSpace(refreshToken))
{
return DataResult<RefreshTokenRes>.Failed("RefreshToken值为空");
}
try
{
var result = JwtHelper.DecodeJwt(refreshToken);
if (result.Count <= 0 && !string.IsNullOrWhiteSpace(result["TenantId"]))
{
return DataResult<RefreshTokenRes>.Failed("Token解密失败!");
}
var userId = long.Parse(user.UserId);
var tenantId = user.GetTenantId();
var tokenModel = new JwtHelper.JwtTokenModel
{
Uid = user.UserId,
Name = db.Queryable<SysUser>().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<RefreshTokenRes>.Success(data);
}
catch (SecurityTokenExpiredException e)
{
IhttpContext.HttpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
return DataResult<RefreshTokenRes>.Failed("Token过期!");
}
}
/// <summary>
/// 客户端刷新Token
/// </summary>
/// <returns></returns>
public DataResult<RefreshTokenRes> ClientUserRefreshToken()
{
var refreshToken = IhttpContext.HttpContext!.Request.Headers["RefreshToken"].First();
if (string.IsNullOrWhiteSpace(refreshToken))
{
return DataResult<RefreshTokenRes>.Failed("RefreshToken值为空");
}
try
{
var result = JwtHelper.DecodeJwt(refreshToken);
if (result.Count <= 0 && !string.IsNullOrWhiteSpace(result["TenantId"]))
{
return DataResult<RefreshTokenRes>.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<SysUser>().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<RefreshTokenRes>.Success(data);
}
catch (SecurityTokenExpiredException e)
{
IhttpContext.HttpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
return DataResult<RefreshTokenRes>.Failed("Token过期!");
}
}
#endregion
#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(),
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<string>.Success(token);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public DataResult<CurrentUserViewModel> GetClientUserInfo()
{
var userId = long.Parse(user.UserId);
var tenantId = user.GetTenantId();
//取第一个机构
var orgRelations = db.Queryable<SysOrgUser>().Filter(null, true)
.LeftJoin<SysOrg>((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<SysUser>().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<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,
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<CurrentUserViewModel>.Success(data);
}
#region 更换机构
/// <summary>
/// 更换机构
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public DataResult<RefreshTokenRes> ChangeOrg(string id)
{
var userId = user.UserId;
var tenantId = user.GetTenantId();
var sysUser = db.Queryable<SysUser>().First(x => x.Id == long.Parse(userId));
if (sysUser.IsNull())
{
return DataResult<RefreshTokenRes>.Failed("非法用户!");
}
var relation = db.Queryable<SysOrgUser>()
.First(x => x.UserId == long.Parse(userId) && x.OrgId == long.Parse(id));
if (relation.IsNull())
{
return DataResult<RefreshTokenRes>.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<RefreshTokenRes>.Success(token);
}
#endregion
/// <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 == UserTypeEnum.SupperAdmin.ToEnumInt())
{
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 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
{
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 if (userInfo.UserType == UserTypeEnum.ApplyUser.ToEnumInt()) //租户申请用户
{
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
{
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<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.Id,
ParentId = 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.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,
Component = a.Component,
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<SysPermission>().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,
Component = a.Component,
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<List<RouteItem>>.Success("获取数据成功!", list);
}
/// <summary>
/// 获取客户端按钮权限
/// </summary>
/// <returns></returns>
public DataResult<string[]> GetClientUserPermissionCode() {
var userId = long.Parse(user.UserId);
var roleList = db.Queryable<SysRoleUser>()
.Where(x => x.UserId == userId).Select(n => n.RoleId).ToList();
roleList.Distinct();
var list = db.Queryable<SysRolePermission>().Where(a => roleList.Contains(a.RoleId) && a.IsPermission == 1)
.InnerJoin<SysPermission>((a,b)=>a.PermissionId == b.Id)
.Where((a, b) => b.MenuType == 3)
.Select((a, b) => b.PermissionCode
).ToArray();
return DataResult<string[]>.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<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>
/// <returns></returns>
public DataResult<List<ApiSelectViewModel>> GetUserList()
{
var list = db.Queryable<SysUser>().Where(a => a.UserType != UserTypeEnum.ApplyUser.ToEnumInt())
.Select(a => new ApiSelectViewModel
{
Label = a.UserName,
Value = a.Id,
})
.ToList();
return DataResult<List<ApiSelectViewModel>>.Success("获取数据成功!", list);
}
#endregion 获取用户下拉列表
#region 获取机构下拉列表
/// <summary>
/// 获取机构下拉列表
/// </summary>
/// <returns></returns>
public DataResult<List<ApiSelectViewModel>> GetOrgList()
{
var list = db.Queryable<SysOrg>()
.Select(a => new ApiSelectViewModel
{
Label = a.OrgName,
Value = a.Id,
})
.ToList();
return DataResult<List<ApiSelectViewModel>>.Success("获取数据成功!", list);
}
#endregion 获取机构下拉列表
#region 商品类型分类
/// <summary>
/// 获取商品类型下拉列表
/// </summary>
/// <returns></returns>
public DataResult<List<ApiSelectViewModel>> GetGoodsTypeList()
{
var list = db.Queryable<CodeGoodsType>()
.Select(a => new ApiSelectViewModel
{
Label = a.GoodsTypeName,
Value = a.Id,
})
.ToList();
return DataResult<List<ApiSelectViewModel>>.Success("获取数据成功!", list);
}
/// <summary>
/// 获取商品类型下拉列表-客户端
/// </summary>
/// <returns></returns>
public DataResult<List<ApiSelectViewModel>> GetClientGoodsTypeList()
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var list = tenantDb.Queryable<CodeGoodsType>()
.Select(a => new ApiSelectViewModel
{
Label = a.GoodsTypeName,
Value = a.Id,
})
.ToList();
return DataResult<List<ApiSelectViewModel>>.Success("获取数据成功!", list);
}
#endregion
#region 国家信息下拉
/// <summary>
/// 获取国家信息下拉列表
/// </summary>
/// <returns></returns>
public DataResult<List<CodeCountrySelectRes>> GetCountrySelectList()
{
var list = db.Queryable<CodeCountry>()
.Where(x => x.Status == StatusEnum.Enable)
.Select<CodeCountrySelectRes>()
.ToList();
return DataResult<List<CodeCountrySelectRes>>.Success("获取数据成功!", list);
}
/// <summary>
/// 获取国家信息下拉列表-客户端
/// </summary>
/// <returns></returns>
public DataResult<List<CodeCountrySelectRes>> GetClientCountrySelectList()
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var list = tenantDb.Queryable<CodeCountry>()
.Where(x => x.Status == StatusEnum.Enable)
.Select<CodeCountrySelectRes>()
.ToList();
return DataResult<List<CodeCountrySelectRes>>.Success("获取数据成功!", list);
}
#endregion
#region 航线信息下拉
/// <summary>
/// 获取航线信息下拉列表
/// </summary>
/// <returns></returns>
public DataResult<List<CodeLanesSelectRes>> GetLanesSelectList()
{
var list = db.Queryable<CodeLanes>()
.Where(x => x.Status == StatusEnum.Enable)
.Select<CodeLanesSelectRes>()
.ToList();
return DataResult<List<CodeLanesSelectRes>>.Success("获取数据成功!", list);
}
/// <summary>
/// 获取航线信息下拉列表-客户端
/// </summary>
/// <returns></returns>
public DataResult<List<CodeLanesSelectRes>> GetClientLanesSelectList()
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var list = tenantDb.Queryable<CodeLanes>()
.Where(x => x.Status == StatusEnum.Enable)
.Select<CodeLanesSelectRes>()
.ToList();
return DataResult<List<CodeLanesSelectRes>>.Success("获取数据成功!", list);
}
/// <summary>
/// 获取港口信息下拉列表
/// </summary>
/// <returns></returns>
public DataResult<List<CodePortSelectRes>> GetPortSelectList()
{
var list = db.Queryable<CodePort>()
.Where(x => x.Status == StatusEnum.Enable)
.Select<CodePortSelectRes>()
.ToList();
return DataResult<List<CodePortSelectRes>>.Success("获取数据成功!", list);
}
/// <summary>
/// 获取港口信息下拉列表-客户端
/// </summary>
/// <returns></returns>
public DataResult<List<CodePortSelectRes>> GetClientPortSelectList()
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var list = tenantDb.Queryable<CodePort>()
.Where(x => x.Status == StatusEnum.Enable)
.Select<CodePortSelectRes>()
.ToList();
return DataResult<List<CodePortSelectRes>>.Success("获取数据成功!", list);
}
#endregion
#region 获取客户数据权限列表
/// <summary>
/// 获取客户数据权限列表
/// </summary>
/// <returns></returns>
public DataResult<List<ClientPermissionRes>> GetClientPermissionList()
{
var list = db.Queryable<SysPermission>().Where(x => x.MenuType == 2 && x.IsHidden == false &&
(x.PermissionType == 1 || x.PermissionType == 0) &&
x.Id != 1744968217220222976 &&
(x.PermissionEntity != "" || x.PermissionEntity != null))
.Select<ClientPermissionRes>()
.ToList();
return DataResult<List<ClientPermissionRes>>.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.ToLower();
var rule = db.Queryable<SysDataRule>()
.First(u => u.PermissionEntity.ToLower() == moduleName && u.Status == StatusEnum.Enable);
if (rule == null) return db.Queryable<T>(); //没有设置数据规则,那么视为该资源允许被任何主体查看
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<SysRoleUser>().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<SysOrgUser>().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<T>().Where(conditionalModels);
}
#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);
}
/// <summary>
/// 获取数据库表-按客户
/// </summary>
/// <returns></returns>
public DataResult<List<DbTableInfo>> GetTablesByClient()
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var data = tenantDb.DbMaintenance.GetTableInfoList();
return DataResult<List<DbTableInfo>>.Success("获取数据成功", data);
}
/// <summary>
/// 获取数据库表字段-按客户
/// </summary>
/// <param name="tableViewName"></param>
/// <returns></returns>
public DataResult<List<DbColumnInfo>> GetColumnsByClient(string tableViewName)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var data = tenantDb.DbMaintenance.GetColumnInfosByTableName(tableViewName);
return DataResult<List<DbColumnInfo>>.Success("获取数据成功", data);
}
#endregion
#region 用户字段设置
/// <summary>
/// 获取用户字段设置
/// </summary>
/// <param name="permissionId"></param>
/// <returns></returns>
public DataResult<SysFieldSet> GetUserFieldSet(string permissionId)
{
var info = db.Queryable<SysFieldSet>()
.Where(x => x.UserId == long.Parse(user.UserId) && x.PermissionId == long.Parse(permissionId)).First();
return DataResult<SysFieldSet>.Success(info);
}
/// <summary>
/// 更新用户字段设置
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
public DataResult UpdateUserFieldSet(UserFieldSetUpdateReq req)
{
var info = db.Queryable<SysFieldSet>()
.Where(x => x.UserId == long.Parse(user.UserId) && x.PermissionId == req.PermissionId).First();
if (info.IsNull())
{
var entity = new SysFieldSet
{
UserId = long.Parse(user.UserId),
PermissionId = req.PermissionId,
Content = req.Content
};
db.Insertable(entity).ExecuteCommand();
}
else
{
info.Content = req.Content;
db.Updateable(info).ExecuteCommand();
}
return DataResult.Successed("更新成功");
}
#endregion
#region 获取字典值
/// <summary>
/// 获取下拉字典
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
public DataResult GetDictTypeDropDown(DropDownDictTypeInput req)
{
var language = IhttpContext.HttpContext.Request.Headers["LanguageType"].FirstOrDefault();
if (language.IsNullOrEmpty())
{
language = "CN";
}
var type = db.Queryable<SysDictType>().Where(x => x.Code == req.Code && x.Status == StatusEnum.Enable).First();
if (type.IsNull())
{
return DataResult.Failed("字典类型不存在!");
}
var data = language == "CN"
? db.Queryable<SysDictData>().Where(x => x.TypeId == type.Id && x.Status == StatusEnum.Enable)
.Select<DropDownData>().ToList()
: db.Queryable<SysDictData>().Where(x => x.TypeId == type.Id && x.Status == StatusEnum.Enable)
.Select(x => new DropDownData
{
Name = x.EnName,
Value = x.Value,
}).ToList();
return DataResult.Successed("获取字典成功!", data);
}
/// <summary>
/// 批量获取字典值
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public DataResult<List<DictOptions>> GetDictOptions(DropDownDictTypeInput model)
{
var language = IhttpContext.HttpContext.Request.Headers["LanguageType"].FirstOrDefault();
if (language.IsNullOrEmpty())
{
language = "CN";
}
var codes = model.Code.Split(',');
var types = db.Queryable<SysDictType>().Where(x => codes.Contains(x.Code) && x.Status == StatusEnum.Enable)
.ToList();
var list = new List<DictOptions>();
foreach (var item in types)
{
var temp = new DictOptions
{
DictCode = item.Code,
Data = language == "CN"
? db.Queryable<SysDictData>().Where(x => x.TypeId == item.Id && x.Status == StatusEnum.Enable)
.Select<DropDownData>().ToList()
: db.Queryable<SysDictData>().Where(x => x.TypeId == item.Id && x.Status == StatusEnum.Enable)
.Select(x => new DropDownData
{
Name = x.EnName,
Value = x.Value,
}).ToList()
};
list.Add(temp);
}
return DataResult<List<DictOptions>>.Success("获取字典成功!", list);
}
#endregion
#region 获取单据编码
/// <summary>
/// 获取最新业务单据编码
/// </summary>
/// <returns></returns>
public DataResult<string> GetSequenceNext<T>()
{
//生成编号
string sequenceNewNo = "";
#region 获取序号生成器属性
// if (string.IsNullOrWhiteSpace(sequenceName))
// {
// result.ErrMsg = "参数错误:业务编码编号";
// return result.ErrMsg;
// }
var moduleName = typeof(T).Name.ToLower();
//获取序号生成器属性
var sequence = db.Queryable<SysSequence>()
.First(u => u.PermissionEntity.ToLower() == moduleName && u.Status == StatusEnum.Enable);
if (sequence != null)
{
var ruleList = db.Queryable<SysSequenceRule>().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<string>.Success(sequenceNewNo);
}
else
{
return DataResult<string>.Failed("未查询到业务编码对应的编码规则配置, 请检查编码规则配置!");
}
}
else
{
return DataResult<string>.Failed("请定义" + moduleName + "的单据编码!");
}
#endregion
}
/// <summary>
/// 计数 方式 重置规则
/// </summary>
/// <param name="seq"></param>
/// <param name="seqRule"></param>
/// <returns></returns>
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;
}
/// <summary>
/// 计数规则
/// </summary>
/// <param name="seqRule"></param>
/// <param name="code"></param>
/// <returns></returns>
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 租户下拉信息
/// <summary>
/// 获取付费方式下拉列表-客户端
/// </summary>
/// <returns></returns>
public DataResult<List<CodeFrtSelectRes>> GetClientFrtSelectList()
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var list = tenantDb.Queryable<CodeFrt>()
.Where(x => x.Status == StatusEnum.Enable)
.Select<CodeFrtSelectRes>()
.ToList();
return DataResult<List<CodeFrtSelectRes>>.Success("获取数据成功!", list);
}
/// <summary>
/// 获取结算方式下拉列表-客户端
/// </summary>
/// <returns></returns>
public DataResult<List<CodeStlModeSelectRes>> GetClientStlModeSelectList()
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var list = tenantDb.Queryable<CodeStlMode>()
.Where(x => x.Status == StatusEnum.Enable)
.Select<CodeStlModeSelectRes>()
.ToList();
return DataResult<List<CodeStlModeSelectRes>>.Success("获取数据成功!", list);
}
/// <summary>
/// 获取业务来源下拉列表-客户端
/// </summary>
/// <returns></returns>
public DataResult<List<CodeSourceSelectRes>> GetClientSourceSelectList()
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var list = tenantDb.Queryable<CodeSource>()
.Where(x => x.Status == StatusEnum.Enable)
.Select<CodeSourceSelectRes>()
.ToList();
return DataResult<List<CodeSourceSelectRes>>.Success("获取数据成功!", list);
}
/// <summary>
/// 获取业务来源明细下拉列表-客户端
/// </summary>
/// <returns></returns>
public DataResult<List<CodeSourceDetailSelectRes>> GetClientSourceDetailSelectList(string id)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var list = tenantDb.Queryable<CodeSourceDetail>()
.Where(x => x.Status == StatusEnum.Enable && x.SourceId == long.Parse(id))
.Select<CodeSourceDetailSelectRes>()
.ToList();
return DataResult<List<CodeSourceDetailSelectRes>>.Success("获取数据成功!", list);
}
#endregion
}