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.

2644 lines
101 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;
using NPOI.SS.Formula.Functions;
using DS.WMS.Core.Flow.Dtos;
using Microsoft.Extensions.Logging;
using DS.Module.Core.Constants;
using DS.WMS.Core.Op.Entity;
using DS.Module.Core.Data;
using DS.WMS.Core.TaskPlat.Entity;
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;
private readonly ILogger<CommonService> _logger;
/// <summary>
/// 任务台基础表自定义列对应的Code
/// </summary>
private const string TASK_PLAT_BASIC_CODE = "BASIC";
/// <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>();
_logger = _serviceProvider.GetRequiredService<ILogger<CommonService>>();
}
#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(),
TenantName = userInfo.TenantName,
};
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 = long.Parse(user.TenantId);
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,
TenantName = user.TenantName,
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.UserName,
TenantId = tenantId,
UserType = a.UserType,
CompanyId = a.CompanyId,
// ClientId = a.ClientId,
IsUseSystem = a.IsUseSystem,
RefreshToken = refreshToken,
// OrgId = a.OrgId.ToString(), CompanyName = a.CustomerName
})
.Mapper(it =>
{
//只能写在Select后面
it.HomePath = "/analysis";
})
.First();
// var context = IhttpContext.HttpContext;
// var log = new SysLogVisit()
// {
// Ip = HttpUtil.GetClientIP(context),
// Location = HttpUtil.GetRequestUrlAddress(request),
// Browser = clientInfo?.UA.Family + clientInfo?.UA.Major,
// Os = clientInfo?.OS.Family + clientInfo?.OS.Major,
// OpTime = DateTime.Now,
// };
return DataResult<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 = long.Parse(user.TenantId);
var tokenModel = new JwtHelper.JwtTokenModel
{
Uid = user.UserId,
Name = db.Queryable<SysUser>().Filter(null, true).First(x => x.Id == userId).UserName,
TenantId = tenantId.ToString(),
TenantName = user.TenantName,
};
var data = new RefreshTokenRes
{
AccessToken = JwtHelper.Encrypt(tokenModel),
RefreshToken = JwtHelper.Encrypt(tokenModel, true)
};
return DataResult<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(result["jti"]);
var userInfo = db.Queryable<SysUser>().Filter(null, true).First(x => x.Id == userId);
var tenantId = result["TenantId"];
var orgId = result["OrgId"];
var tokenModel = new JwtHelper.JwtTokenModel
{
Uid = userId.ToString(),
Name = userInfo.UserName,
OrgId = orgId.ToString(),
TenantId = tenantId.ToString(),
TenantName = userInfo.TenantName,
};
var data = new RefreshTokenRes
{
AccessToken = JwtHelper.Encrypt(tokenModel, false, true),
RefreshToken = JwtHelper.Encrypt(tokenModel, true, true)
};
return DataResult<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 async Task<DataResult<string>> ClientUserLogin(UserLoginModel model)
{
if (model.UserName.ToLower().Trim() == "admin")
{
return await Task.FromResult(DataResult<string>.Failed("非租户端用户!"));
}
var userInfo = await db.Queryable<SysUser>().Filter(null, true)
.FirstAsync(x => x.UserCode == model.UserName && x.IsUseSystem == true);
if (userInfo == null)
{
return await Task.FromResult(DataResult<string>.Failed("账号不存在或账号禁用,请检查!"));
}
if (userInfo.MD5Password != model.Password)
{
return await Task.FromResult(DataResult<string>.Failed("密码错误!"));
}
var tenant = await db.Queryable<SysTenant>().Filter(null, true)
.FirstAsync(x => x.Id == userInfo.TenantId);
var tokenModel = new JwtHelper.JwtTokenModel
{
Uid = userInfo.Id.ToString(),
Name = userInfo.UserName,
OrgId = userInfo.DefaultOrgId.ToString(),
TenantId = userInfo.TenantId.ToString(),
TenantName = tenant.Name,
};
var token = JwtHelper.Encrypt(tokenModel, false, true);
var visLog = new SysLogVisit()
{
LoginType = 0,
UserName = userInfo.UserName,
UserCode = userInfo.UserCode,
TenantId = userInfo.TenantId,
OpTime = DateTime.Now,
Message = "登录成功"
};
await saasService.GetLogDb().Insertable(visLog).ExecuteCommandAsync();
return await Task.FromResult(DataResult<string>.Success(token));
}
/// <summary>
/// 用户登录 邮箱
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public async Task<DataResult<string>> ClientUserEmailLogin(UserEmailLoginModel model)
{
var userInfo = await db.Queryable<SysUser>().Filter(null, true)
.FirstAsync(x => x.Email == model.Email && x.IsUseSystem == true);
if (userInfo == null)
{
return await Task.FromResult(DataResult<string>.Failed("用户邮箱不存在或邮箱账号禁用,请检查!"));
}
if (userInfo.MD5Password != model.Password)
{
return await Task.FromResult(DataResult<string>.Failed("密码错误!"));
}
var tenant = await db.Queryable<SysTenant>().Filter(null, true)
.FirstAsync(x => x.Id == userInfo.TenantId);
var tokenModel = new JwtHelper.JwtTokenModel
{
Uid = userInfo.Id.ToString(),
Name = userInfo.UserName,
OrgId = userInfo.DefaultOrgId.ToString(),
TenantId = userInfo.TenantId.ToString(),
TenantName = tenant.Name,
};
var token = JwtHelper.Encrypt(tokenModel, false, true);
var visLog = new SysLogVisit()
{
LoginType = 0,
UserName = userInfo.UserName,
UserCode = userInfo.UserCode,
TenantId = userInfo.TenantId,
OpTime = DateTime.Now,
Message = "登录成功"
};
await saasService.GetLogDb().Insertable(visLog).ExecuteCommandAsync();
return await Task.FromResult(DataResult<string>.Success(token));
}
/// <summary>
/// 用户登录 手机号
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public async Task<DataResult<string>> ClientUserPhoneLogin(UserPhoneLoginModel model)
{
var userInfo = await db.Queryable<SysUser>().Filter(null, true)
.FirstAsync(x => x.Phone == model.Phone && x.IsUseSystem == true);
if (userInfo == null)
{
return await Task.FromResult(DataResult<string>.Failed("用户手机号不存在或手机号账号禁用,请检查!"));
}
if (userInfo.MD5Password != model.Password)
{
return await Task.FromResult(DataResult<string>.Failed("密码错误!"));
}
var tenant = await db.Queryable<SysTenant>().Filter(null, true)
.FirstAsync(x => x.Id == userInfo.TenantId);
var tokenModel = new JwtHelper.JwtTokenModel
{
Uid = userInfo.Id.ToString(),
Name = userInfo.UserName,
OrgId = userInfo.DefaultOrgId.ToString(),
TenantId = userInfo.TenantId.ToString(),
TenantName = tenant.Name,
};
var token = JwtHelper.Encrypt(tokenModel, false, true);
var visLog = new SysLogVisit()
{
LoginType = 0,
UserName = userInfo.UserName,
UserCode = userInfo.UserCode,
TenantId = userInfo.TenantId,
OpTime = DateTime.Now,
Message = "登录成功"
};
await saasService.GetLogDb().Insertable(visLog).ExecuteCommandAsync();
return await Task.FromResult(DataResult<string>.Success(token));
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public async Task<DataResult<CurrentUserViewModel>> GetClientUserInfo()
{
var userId = long.Parse(user.UserId);
var tenantId = long.Parse(user.TenantId);
//取第一个机构
var orgRelations = await 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
})
.ToListAsync();
var userInfo = await db.Queryable<SysUser>().Filter(null, true).FirstAsync(x => x.Id == userId);
var tenant = await db.Queryable<SysTenant>().Filter(null, true)
.FirstAsync(x => x.Id == userInfo.TenantId);
var tokenModel = new JwtHelper.JwtTokenModel
{
Uid = user.UserId,
Name = userInfo.UserName,
OrgId = user.OrgId.ToString(),
TenantId = tenantId.ToString(),
TenantName = tenant.Name
};
var refreshToken = JwtHelper.Encrypt(tokenModel, true, true);
var data = await db.Queryable<SysUser>().Filter(null, true).Where(x => x.Id == userId)
.Select(a => new CurrentUserViewModel
{
UserId = a.Id,
UserCode = a.UserCode,
UserName = a.UserName,
TenantId = tenantId,
UserType = a.UserType,
CompanyId = a.CompanyId,
// ClientId = a.ClientId,
IsUseSystem = a.IsUseSystem,
RefreshToken = refreshToken,
OrgId = user.OrgId.ToString(),
Tel = a.Tel,
Email = a.Email,
Phone = a.Phone,
OfficePhone = a.OfficePhone,
HomePath = string.IsNullOrEmpty(a.HomePath) ? "/taskmanage" : a.HomePath
// UserOrgs = orgRelations,
//OrgId = a.OrgId.ToString(), CompanyName = a.CustomerName
})
//.Mapper(it =>
//{
// //只能写在Select后面
// //it.HomePath = "/analysis";
// it.HomePath = string.IsNullOrEmpty(it.HomePath) ? "/taskmanage": it.HomePath;
//})
.FirstAsync();
data.UserOrgs = orgRelations;
return await Task.FromResult(DataResult<CurrentUserViewModel>.Success(data));
}
#region 更换机构
/// <summary>
/// 更换机构
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public DataResult<RefreshTokenRes> ChangeOrg(string id)
{
var userId = user.UserId;
var tenantId = long.Parse(user.TenantId);
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(),
TenantName = sysUser.TenantName,
};
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 async Task<DataResult<List<RouteItem>>> GetClientUserPermissionByToken()
{
List<RouteItem> list = new List<RouteItem>();
_logger.LogInformation("GetClientUserPermissionByToken临时日志user.UserId={userId},user.TenantId={TenantId}", user.UserId, user.TenantId);
var userId = long.Parse(user.UserId);
var userInfo = await db.Queryable<SysUser>().Where(x => x.Id == userId).FirstAsync();
var sql = db.Queryable<SysUser>().Where(x => x.Id == userId).ToSqlString();
_logger.LogInformation("GetClientUserPermissionByToken临时日志sql={sql}", sql);
//超级管理员
if (userInfo.UserType == UserTypeEnum.SupperAdmin.ToEnumInt())
{
list = await 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,
}
})
.ToListAsync();
foreach (var item in list)
{
var childs = await db.Queryable<SysPermission>().Filter(null, true)
.Where(x => (x.MenuType == 1 || x.MenuType == 2) && x.ParentId == item.Id && x.IsHidden == false &&
(x.PermissionType == 1 || x.PermissionType == 0))
.OrderBy(x => x.SortCode)
.Select(a => new RouteItem
{
Id = a.Id,
ParentId = a.ParentId,
Path = a.Url,
Name = a.PermissionName,
Component = a.Component,
IsCache = a.IsCache,
Meta = new RouteMeta()
{
Title = a.Title,
Icon = a.Icon,
}
}).ToListAsync();
item.Children = childs;
}
}
else if (userInfo.UserType == UserTypeEnum.ApplyUser.ToEnumInt()) //租户申请用户
{
var roleIds = await db.Queryable<SysRoleUser>().Where(x => x.UserId == userId).Select(x => x.RoleId).ToListAsync();
var permissions = await db.Queryable<SysRolePermission>().Where(x => roleIds.Contains(x.RoleId))
.Select(x => x.PermissionId).Distinct().ToListAsync();
var perlist = await 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,
}
})
.ToListAsync();
list.AddRange(perlist);
//去重
list.Distinct();
//排序
list = list.OrderBy(x => x.SortCode).ToList();
foreach (var item in list)
{
var childs = await 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,
}
}).ToListAsync();
//去重
childs.Distinct();
//排序
childs = childs.OrderBy(x => x.SortCode).ToList();
item.Children = childs;
}
}
else
{
var roleIds = await db.Queryable<SysRoleUser>().Where(x => x.UserId == userId).Select(x => x.RoleId).ToListAsync();
var permissions = await db.Queryable<SysRolePermission>().Where(x => roleIds.Contains(x.RoleId))
.Select(x => x.PermissionId).Distinct().ToListAsync();
var perlist = await 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,
EnName = a.PermissionEnName,
Component = a.Component,
Redirect = a.Redirect,
SortCode = a.SortCode,
Meta = new RouteMeta()
{
Title = a.Title,
Icon = a.Icon,
}
})
.ToListAsync();
list.AddRange(perlist);
//去重
list.Distinct();
//排序
list = list.OrderBy(x => x.SortCode).ToList();
foreach (var item in list)
{
var childs = await db.Queryable<SysPermissionTenant>().Where(x =>
(x.MenuType == 1 || x.MenuType == 2) && x.ParentId == item.ParentId && x.IsHidden == false &&
permissions.Contains(x.PermissionId) &&
(x.PermissionType == 1 || x.PermissionType == 0) &&
x.PermissionId != 1744968217220222976) //排除企业用户维护
.OrderBy(x => x.SortCode)
.Select(a => new RouteItem
{
Id = a.Id,
ParentId = a.PermissionId,
Path = a.Url,
Name = a.PermissionName,
EnName = a.PermissionEnName,
Component = a.Component,
IsCache = a.IsCache,
Meta = new RouteMeta()
{
Title = a.Title,
Icon = a.Icon,
}
}).ToListAsync();
//去重
childs.Distinct();
//排序
childs = childs.OrderBy(x => x.SortCode).ToList();
foreach (var child in childs)
{
var grandsons = await db.Queryable<SysPermissionTenant>().Where(x =>
x.MenuType == 2 && x.ParentId == child.ParentId && x.IsHidden == false &&
permissions.Contains(x.PermissionId)) //获取第三层路由
.OrderBy(x => x.SortCode)
.Select(a => new RouteItem
{
Id = a.Id,
ParentId = a.PermissionId,
Path = a.Url,
Name = a.PermissionName,
EnName = a.PermissionEnName,
Component = a.Component,
IsCache = a.IsCache,
Meta = new RouteMeta()
{
Title = a.Title,
Icon = a.Icon,
}
}).ToListAsync();
if (grandsons.Count > 0)
{
//去重
grandsons.Distinct();
//排序
grandsons = grandsons.OrderBy(x => x.SortCode).ToList();
child.Children = grandsons;
}
}
item.Children = childs;
}
}
// list = list.OrderBy(x => x.Id).ToList();
return await Task.FromResult(DataResult<List<RouteItem>>.Success("获取数据成功!", list));
}
/// <summary>
/// 获取客户端按钮权限
/// </summary>
/// <returns></returns>
public async Task<DataResult<string[]>> GetClientUserPermissionCode()
{
var userId = long.Parse(user.UserId);
var roleList = await db.Queryable<SysRoleUser>()
.Where(x => x.UserId == userId).Select(n => n.RoleId).ToListAsync();
roleList.Distinct();
var list = await 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
).ToArrayAsync();
return await Task.FromResult(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,
EnTitle = a.PermissionEnName,
Key = a.Id,
Icon = a.Icon
})
.ToList();
foreach (var item in list)
{
var childs = db.Queryable<SysPermission>().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<SysPermission>().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<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(string queryKey = "")
{
var list = db.Queryable<SysUser>().Where(a => a.UserType != UserTypeEnum.ApplyUser.ToEnumInt())
.WhereIF(!string.IsNullOrEmpty(queryKey), a => a.PinYinCode.Contains(queryKey) || a.UserCode.Contains(queryKey) || a.UserName.Contains(queryKey))
.Select(a => new ApiSelectViewModel
{
Label = a.UserName,
Value = a.Id,
})
.Take(20)
.WithCache($"{SqlSugarCacheConst.User}{user.TenantId}", SqlSugarCacheConst.CacheDurationInSeconds).ToList();
return DataResult<List<ApiSelectViewModel>>.Success("获取数据成功!", list);
}
#endregion 获取用户下拉列表
#region 获取机构下拉列表
/// <summary>
/// 获取机构下拉列表
/// </summary>
/// <returns></returns>
public DataResult<List<OrgApiSelectViewModel>> GetOrgList(string queryKey = "")
{
var list = db.Queryable<SysOrg>().Where(a => a.Status == StatusEnum.Enable && a.IsDepartment == false)
.WhereIF(!string.IsNullOrEmpty(queryKey), a => (a.OrgName.Contains(queryKey) || a.OrgFullName.Contains(queryKey) || a.OrgEnName.Contains(queryKey)))
.Select(a => new OrgApiSelectViewModel
{
Label = a.OrgName,
Id = a.Id,
})
.Take(20)
.WithCache($"{SqlSugarCacheConst.Org}{user.TenantId}", SqlSugarCacheConst.CacheDurationInSeconds)
.ToList();
return DataResult<List<OrgApiSelectViewModel>>.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 async Task<DataResult<List<CodePortSelectRes>>> GetClientPortSelectList(string queryKey = "")
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var list = await tenantDb.Queryable<CodePort>()
.Where(x => x.Status == StatusEnum.Enable)
.WhereIF(!string.IsNullOrEmpty(queryKey), x => x.PortName.Contains(queryKey) || x.CnName.Contains(queryKey) || x.EdiCode.Contains(queryKey))
.Select(x => new CodePortSelectRes()
{
PinYinCode = !String.IsNullOrEmpty(x.EdiCode) ? x.EdiCode + "/" + x.PortName : x.PortName,
}, true)
.Take(20)
.WithCache(SqlSugarCacheConst.Port + user.TenantId, SqlSugarCacheConst.CacheDurationInSeconds)
.ToListAsync();
return await Task.FromResult(DataResult<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),
Email = "",
Phone = req.Phone,
UserType = UserTypeEnum.ApplyUser.ToEnumInt(), //管理员
Status = 0, //正常
IsUseSystem = true,
TenantId = 1288018625843826688,
};
var adminUser = db.Insertable(userEntity).ExecuteReturnEntity();
//写入用户角色 指定角色
var roleUser = new SysRoleUser
{
RoleId = 1744922920100171776,
UserId = adminUser.Id
};
db.Insertable(roleUser).ExecuteCommand();
db.Ado.CommitTran();
return DataResult.Successed("企业注册成功!请登录后完善相关资料并提交审核!");
}
catch (Exception ex)
{
db.Ado.RollbackTran();
ex.LogAsync(db).GetAwaiter().GetResult();
return DataResult.Failed("企业注册失败!");
}
}
#endregion
public DataResult<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>(); //没有设置数据规则,那么视为该资源允许被任何主体查看
#region 数据权限
var rules = db.Queryable<SysDataRule>()
.Where(u => u.PermissionEntity.ToLower() == moduleName && u.Status == StatusEnum.Enable && u.RuleType == "user").ToList();
if (rules.Count > 0)//检索制定用户的数据权限
{
var ruleIds = rules.Select(x => x.Id);
var ruleUser = db.Queryable<SysRuleUser>()
.First(u => ruleIds.Contains((long)u.RuleId) && u.UserId == long.Parse(user.UserId));
if (ruleUser.IsNull())
{
// 检索公共数据权限
rule = db.Queryable<SysDataRule>()
.First(u => u.PermissionEntity.ToLower() == moduleName && u.Status == StatusEnum.Enable && u.RuleType == "public");
if (rule == null) return db.Queryable<T>();
}
else
{
rule = rules.Find(x => x.Id == ruleUser.RuleId);
}
}
else
{
// 检索公共数据权限
rule = db.Queryable<SysDataRule>()
.First(u => u.PermissionEntity.ToLower() == moduleName && u.Status == StatusEnum.Enable && u.RuleType == "public");
if (rule == null) return db.Queryable<T>();
}
#endregion
//if (db.Queryable<SysDataRule>()
// .Where(u => u.PermissionEntity.ToLower() == moduleName && u.Status == StatusEnum.Enable && u.RuleType == "user").Any())
//{
// //此处取第一个
// var ruleUser = db.Queryable<SysRuleUser>()
// .First(u => u.PermissionEntity.ToLower() == moduleName && u.Status == StatusEnum.Enable);
//}
if (rule.DataRules.Contains(DataRuleConst.LoginUser))
{
//即把{loginUser} =='xxxxxxx'换为 user.UserId =='xxxxxxx'从而把当前登录的用户名与当时设计规则时选定的用户id对比
rule.DataRules = rule.DataRules.Replace(DataRuleConst.LoginUser, user.UserId);
}
if (rule.DataRules.Contains(DataRuleConst.LoginRole))
{
var roles = db.Queryable<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);
}
/// <summary>
/// 获取操作规则条件组
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public List<IConditionalModel> GetOperationRuleConditional<T>()
{
var userInfo = db.Queryable<SysUser>().First(x => x.Id == long.Parse(user.UserId));
if (userInfo.UserType == 0)
{
return new List<IConditionalModel>(); //超级管理员特权
}
var moduleName = typeof(T).Name.ToLower();
var rule = db.Queryable<SysOperationRule>()
.First(u => u.PermissionEntity.ToLower() == moduleName && u.Status == StatusEnum.Enable);
if (rule == null) return new List<IConditionalModel>(); //没有设置数据规则,那么视为该资源允许被任何主体查看
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 conditionalModels;
}
#region 可视权限
/// <summary>
/// 获取当前用户的可视权限范围
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tenantDb"></param>
/// <returns></returns>
public async Task<(ISugarQueryable<T> queryable, string? ruleScope)> GetVisibleDataRuleFilter<T>(SqlSugarScopeProvider tenantDb)
{
var queryable = tenantDb.Queryable<T>();
// 因为TaskBaseAllocation不能继承IOrgId所以在这里根据条件在需要的时候手动添加IOrgId查询筛选器
bool isTask = typeof(T) == typeof(TaskBaseAllocation);
var userInfo = db.Queryable<SysUser>().First(x => x.Id == long.Parse(user.UserId));
if (userInfo.UserType == 0)
{
if (isTask) queryable.Filter(typeof(IOrgId));
return (queryable, "all"); //超级管理员特权
}
var moduleName = typeof(T).Name.ToLower();
var rule = tenantDb.Queryable<CodeDataRule>()
.First(u => u.UserId == long.Parse(user.UserId) && u.PermissionEntity.ToLower() == moduleName && u.Status == StatusEnum.Enable);
if (rule.IsNull())
{
return (queryable, null); //默认查询
}
else
{
var contidions = new List<IConditionalModel>();
#region 可视权限
if ((long)rule.VisibleTemplateId == 0)
{
contidions.Add(new ConditionalModel { FieldName = "CreateBy", ConditionalType = ConditionalType.Equal, FieldValue = user.UserId });
return (queryable.Where(contidions), "self"); //查询自身
}
var ruleInfo = tenantDb.Queryable<CodeDataRuleTemplate>().First(x => x.Id == (long)rule.VisibleTemplateId);
if (ruleInfo.RuleScope == "all")
{
return (queryable.ClearFilter<IOrgId>(), ruleInfo.RuleScope); //查询全部
}
else if (ruleInfo.RuleScope == "none")
{
if (isTask)
{ return (queryable, ruleInfo.RuleScope); }
else
{
SqlSugar.Check.ExceptionEasy("NO Operation", "没有数据查看权限!");//返回提示
}
}
else if (ruleInfo.RuleScope == "self_org")
{
if (isTask) queryable.Filter(typeof(IOrgId));
var conditionalModels = ConvertConditionalModel(ruleInfo.DataRules);
if (conditionalModels.Count > 0)
{
return (queryable.Where(conditionalModels), ruleInfo.RuleScope);//自定义查询
}
else
{
return (queryable, ruleInfo.RuleScope);//默认查询
}
}
else if (ruleInfo.RuleScope == "self_org_with_child") // 当前机构及下属机构
{
List<SysOrg> orgList = await db.Queryable<SysOrg>().ToChildListAsync(s => s.ParentId, user.OrgId);
IEnumerable<long> orgIdList = orgList.Select(x => x.Id);
contidions.Add(new ConditionalModel { FieldName = "OrgId", ConditionalType = ConditionalType.In, FieldValue = string.Join(",", orgIdList) });
return (queryable.Where(contidions), ruleInfo.RuleScope);
}
else if (ruleInfo.RuleScope == "self")
{
var conditionalModels = ConvertConditionalModel(ruleInfo.DataRules);
if (conditionalModels.Count > 0)
{
return (queryable.Where(conditionalModels), ruleInfo.RuleScope);//自定义查询
}
else
{
contidions.Add(new ConditionalModel { FieldName = "CreateBy", ConditionalType = ConditionalType.Equal, FieldValue = user.UserId });
return (queryable.Where(contidions), ruleInfo.RuleScope); //查询创建人自身信息
}
}
else if (ruleInfo.RuleScope == "self_dept")
{
if (String.IsNullOrEmpty(userInfo.DeptName))
{
if (!isTask)
{
SqlSugar.Check.ExceptionEasy("NO Operation", "当前员工没有默认归属部门!");
}
}
var conditionalModels = ConvertConditionalModel(ruleInfo.DataRules);
if (conditionalModels.Count > 0)
{
return (queryable.Where(conditionalModels), ruleInfo.RuleScope);//自定义查询
}
else
{
var deptUsers = db.Queryable<SysUser>().Where(x => x.DeptId == userInfo.DeptId).Select(x => x.Id).ToList();
contidions.Add(new ConditionalModel { FieldName = "CreateBy", ConditionalType = ConditionalType.In, FieldValue = string.Join(",", deptUsers) });
return (queryable.Where(contidions), ruleInfo.RuleScope); //查询本部门
}
}
else if (ruleInfo.RuleScope == "select_org")
{
var conditionalModels = ConvertConditionalModel(ruleInfo.DataRules);
//var conditions = ruleInfo.DataRules.ConvertSqlSugarExpression();
//var conditionalModels =
// db.ConfigQuery.Context.Utilities.JsonToConditionalModels(
// JsonConvert.SerializeObject(conditions));
return (queryable.ClearFilter<IOrgId>().Where(conditionalModels), ruleInfo.RuleScope); //查询指定机构
}
else if (ruleInfo.RuleScope == "select_user")
{
//var conditionalModels = ConvertConditionalModel(ruleInfo.DataRules);
var conditionalModels = ConvertConditionalModel(ruleInfo.DataRules);
return (queryable.ClearFilter<IOrgId>().Where(conditionalModels), ruleInfo.RuleScope);//查询指定人员
}
else if (ruleInfo.RuleScope == "customize")
{
//var conditionalModels = ConvertConditionalModel(ruleInfo.DataRules);
var conditionalModels = ConvertConditionalModel(ruleInfo.DataRules);
return (queryable.Where(conditionalModels), ruleInfo.RuleScope);//自定义查询
}
else if (ruleInfo.DataRules.IsNull())
{
contidions.Add(new ConditionalModel { FieldName = "CreateBy", ConditionalType = ConditionalType.Equal, FieldValue = user.UserId });
return (queryable.Where(contidions), ruleInfo.RuleScope); //没有设置数据规则,那么视为该资源允许被创建人查看
}
return (queryable, ruleInfo.RuleScope);
#endregion
}
}
private List<IConditionalModel> ConvertConditionalModel(string rules)
{
if (!string.IsNullOrEmpty(rules))
{
if (rules.Contains(DataRuleConst.LoginUser))
{
//即把{loginUser} =='xxxxxxx'换为 user.UserId =='xxxxxxx'从而把当前登录的用户名与当时设计规则时选定的用户id对比
rules = rules.Replace(DataRuleConst.LoginUser, user.UserId);
}
if (rules.Contains(DataRuleConst.LoginOrg))
{
rules = rules.Replace(DataRuleConst.LoginOrg, user.OrgId.ToString());
}
if (rules.Contains(DataRuleConst.LoginDept))
{
var userInfo = db.Queryable<SysUser>().First(x => x.Id == long.Parse(user.UserId));
rules = rules.Replace(DataRuleConst.LoginOrg, userInfo.DeptId.ToString());
}
var conditions = rules.ConvertSqlSugarExpression();
var conditionalModels =
db.ConfigQuery.Context.Utilities.JsonToConditionalModels(
JsonConvert.SerializeObject(conditions));
return conditionalModels;
}
else
{
return new List<IConditionalModel>();
}
}
#endregion
#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>
/// <param name="tagNo">标识序号</param>
/// <returns></returns>
public DataResult<SysFieldSet> GetUserFieldSet(string permissionId, int tagNo = 0)
{
var info = db.Queryable<SysFieldSet>()
.Where(x => x.UserId == long.Parse(user.UserId) && x.PermissionId == long.Parse(permissionId) && x.TagNo == tagNo).First();
return DataResult<SysFieldSet>.Success(info);
}
/// <summary>
/// 批量获取任务台用户字段设置
/// </summary>
/// <returns></returns>
public async Task<DataResult<List<SysFieldSetTaskPlatResultDto>>> GetUserTaskPlatFieldSet(SysFieldSetTaskPlatQueryDto query)
{
if (query.TaskTypeCodeArray == null || query.TaskTypeCodeArray.Length == 0)
{
return DataResult<List<SysFieldSetTaskPlatResultDto>>.Success(null);
}
long userId = long.Parse(user.UserId);
Dictionary<int, string> tagNoDic = new(query.TaskTypeCodeArray.Length);
foreach (var item in query.TaskTypeCodeArray)
{
if (item.ToUpper() == TASK_PLAT_BASIC_CODE)
{
var typeInt = -1;
if (!tagNoDic.ContainsKey(typeInt))
{
tagNoDic.Add(typeInt, TASK_PLAT_BASIC_CODE);
}
}
else
{
if (Enum.TryParse(typeof(TaskBaseTypeEnum), item, out object? typeEnum))
{
var typeInt = (int)typeEnum;
if (!tagNoDic.ContainsKey(typeInt))
{
tagNoDic.Add(typeInt, item);
}
}
}
}
var tenantId = long.Parse(user.TenantId);
var tagNoList = tagNoDic.Select(x => x.Key);
var infoList = await db.Queryable<SysFieldSet>()
.Where(x => x.PermissionId == long.Parse(query.PermissionId) && x.TenantId == tenantId && tagNoList.Contains(x.TagNo))
.WhereIF(query.IsGetDefault, x => x.UserId == 0)
.WhereIF(!query.IsGetDefault, x => (x.UserId == userId || x.UserId == 0))
.Select(x => new SysFieldSetTaskPlatResultDto(), true)
.ToListAsync();
var result = new List<SysFieldSetTaskPlatResultDto>();
foreach (var item in tagNoDic)
{
var temp = infoList.FirstOrDefault(x => x.TagNo == item.Key && x.UserId == userId);
if (temp != null)
{
temp.IsDefault = false;
temp.TaskTypeCode = item.Value;
result.Add(temp);
}
else
{
temp = infoList.FirstOrDefault(x => x.TagNo == item.Key);
if (temp != null)
{
temp.IsDefault = true;
temp.TaskTypeCode = item.Value;
result.Add(temp);
}
}
}
return DataResult<List<SysFieldSetTaskPlatResultDto>>.Success(result);
}
/// <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 && 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("更新成功");
}
/// <summary>
/// 更新任务台用户字段设置
/// </summary>
public async Task<DataResult> UpdateUserTaskPlatFieldSet(UserFieldSetUpdateReq req)
{
int tagNo;
if (req.TaskTypeCode.ToUpper() == TASK_PLAT_BASIC_CODE)
{
tagNo = -1;
}
else if (Enum.TryParse(typeof(TaskBaseTypeEnum), req.TaskTypeCode, out object? type))
{
tagNo = (int)type;
}
else
{
throw new Exception(nameof(req.TaskTypeCode) + "取值有误:" + req.TaskTypeCode);
}
var tenantId = long.Parse(user.TenantId);
var userId = long.Parse(user.UserId);
var info = await db.Queryable<SysFieldSet>()
.Where(x => x.PermissionId == req.PermissionId && x.TenantId == tenantId && x.TagNo == tagNo)
.WhereIF(req.IsSetDefault, x => x.UserId == 0)
.WhereIF(!req.IsSetDefault, x => x.UserId == userId)
.FirstAsync();
if (info.IsNull())
{
var entity = new SysFieldSet
{
UserId = req.IsSetDefault ? 0 : userId,
PermissionId = req.PermissionId,
Content = req.Content,
TenantId = tenantId,
TagNo = tagNo,
};
await db.Insertable(entity).ExecuteCommandAsync();
}
else
{
info.Content = req.Content;
await db.Updateable(info).ExecuteCommandAsync();
}
return DataResult.Successed("更新成功");
}
#endregion
#region 获取字典值
/// <summary>
/// 获取下拉字典
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
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<SysDictType>().Where(x => x.Code == req.Code && x.Status == StatusEnum.Enable).First();
if (type.IsNull())
{
return DataResult.Failed("字典类型不存在!");
}
var dictValues = new List<DropDownData>();
if (language == "CN")
{
dictValues = db.Queryable<SysDictData>().Where(x => x.TypeId == type.Id && x.Status == StatusEnum.Enable)
.Select<DropDownData>().ToList();
}
else if (language == "EN")
{
if (db.Queryable<SysDictData>().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<SysDictData>().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<SysDictData>().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<SysDictData>().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<SysDictData>().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<SysDictData>().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<SysDictData>().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<SysDictData>().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<SysDictData>().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<SysDictData>().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<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("获取字典成功!", dictValues);
}
/// <summary>
/// 批量获取字典值
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public DataResult<List<DictOptions>> 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<List<DictOptions>>.Failed("请传入正确的字典代码!");
}
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 dictValues = new List<DropDownData>();
if (language == "CN")
{
dictValues = db.Queryable<SysDictData>().Where(x => x.TypeId == item.Id && x.Status == StatusEnum.Enable)
.Select<DropDownData>().ToList();
}
else if (language == "EN")
{
dictValues = db.Queryable<SysDictData>().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<SysDictData>().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<SysDictData>().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<SysDictData>().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<SysDictData>().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<List<DictOptions>>.Success("获取字典成功!", list);
}
#endregion
#region 获取单据编码
//SqlSugarScopeProvider tenantDb, IUser user
/// <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 "variable": //变量方式 TODO
// 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;
}
#region 新的编码规则
/// <summary>
/// 获取最新业务单据编码
/// </summary>
/// <returns></returns>
public async Task<DataResult<string>> GetSequenceNextAsync<T>(SqlSugarScopeProvider tenantDb, IUser user, long saleId = 0, DateTime? date = null)
{
//生成编号
string sequenceNewNo = "";
#region 获取序号生成器属性
var moduleName = typeof(T).Name.ToLower();
//获取序号生成器属性
var sequence = await db.Queryable<SysSequence>()
.FirstAsync(u => u.PermissionEntity.ToLower() == moduleName && u.Status == StatusEnum.Enable);
if (sequence != null)
{
var ruleList = await db.Queryable<SysSequenceRule>().OrderBy(x => x.OrderNo)
.Where(u => u.SequenceId == sequence.Id && u.Status == StatusEnum.Enable).ToListAsync();
var businessSeq = new BusinessSequence();
if (ruleList.Any())
{
int delimiterNum = 0;
for (global::System.Int32 i = 0; i < ruleList.Count; i++)
{
var item = ruleList[i];
delimiterNum++;
switch (item.RuleType)
{
case "const": //常量方式
sequenceNewNo += item.RuleValue;
break;
case "variable": //变量方式 TODO
if (item.RuleValue == "UserNumber")
{
if (saleId == 0)
{
return await Task.FromResult(DataResult<string>.Failed("请维护订单揽货人信息!"));
}
var userInfo = await db.Queryable<SysUser>().FirstAsync(x => x.Id == saleId);
if (userInfo.UserNumber.IsNull())
{
return await Task.FromResult(DataResult<string>.Failed("该揽货人用户编码未维护!"));
}
sequenceNewNo += userInfo.UserNumber;
}
break;
case "shortdate": //短日期 年2位月2位日期2位
sequenceNewNo += date.HasValue ? date.Value.ToString("yyyyMMdd").Substring(2) : DateTime.Now.ToString("yyyyMMdd").Substring(2);
break;
case "date": //日期年4位
sequenceNewNo += date.HasValue ? date.Value.ToString("yyyyMMdd") : DateTime.Now.ToString("yyyyMMdd");
break;
case "ydate": //年月年4位月2位
sequenceNewNo += date.HasValue ? date.Value.ToString("yyyyMMdd").Substring(0, 6) : DateTime.Now.ToString("yyyyMMdd").Substring(0, 6);
break;
case "sydate": //年月年2位月2位
sequenceNewNo += date.HasValue ? date.Value.ToString("yyyyMMdd").Substring(2, 4) : DateTime.Now.ToString("yyyyMMdd").Substring(2, 4);
break;
case "timestamp": //日期时间精确到毫秒
sequenceNewNo += date.HasValue ? date.Value.ToString("yyyyMMddHHmmssffff") : DateTime.Now.ToString("yyyyMMddHHmmssffff");
break;
case "number": //计数,流水号
var prefix = sequenceNewNo;//前缀
businessSeq = await tenantDb.Queryable<BusinessSequence>().Where(x => x.SequenceId == sequence.Id && x.Prefix == prefix).FirstAsync();
int num = CurrentReset(sequence, item, businessSeq, tenantDb);
//计数拼接
sequenceNewNo += NumberingSeqRule(item, num).ToString();
//更新当前序号,
sequence.CurrentNo = num;
if (businessSeq.IsNull())
{
businessSeq = new BusinessSequence()
{
SequenceId = sequence.Id,
Prefix = prefix,
CurrentNo = num
};
}
else
{
businessSeq.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");
businessSeq.CurrentCode = sequenceNewNo;
businessSeq.CurrentReset = DateTime.Now.ToString("yyyyMMdd");
await db.Updateable(sequence).ExecuteCommandAsync();
await tenantDb.Storageable(businessSeq).ExecuteCommandAsync();
return await Task.FromResult(DataResult<string>.Success(sequenceNewNo));
}
else
{
return await Task.FromResult(DataResult<string>.Failed("未查询到业务编码对应的编码规则配置, 请检查编码规则配置!"));
}
}
else
{
return await Task.FromResult(DataResult<string>.Failed("请定义" + moduleName + "的单据编码!"));
}
#endregion
}
private static object ImportLockObj = new object();
/// <summary>
/// 获取最新业务单据编码(锁)
/// </summary>
/// <returns></returns>
public DataResult<string> GetSequenceNext<T>(SqlSugarScopeProvider tenantDb, IUser user, long saleId = 0, DateTime? date = null)
{
//生成编号
string sequenceNewNo = "";
#region 获取序号生成器属性
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();
var businessSeq = new BusinessSequence();
if (ruleList.Any())
{
try
{
Monitor.Enter(ImportLockObj);
int delimiterNum = 0;
for (global::System.Int32 i = 0; i < ruleList.Count; i++)
{
var item = ruleList[i];
delimiterNum++;
switch (item.RuleType)
{
case "const": //常量方式
sequenceNewNo += item.RuleValue;
break;
case "variable": //变量方式 TODO
if (item.RuleValue == "UserNumber")
{
if (saleId == 0)
{
return DataResult<string>.Failed("请维护订单揽货人信息!");
}
var userInfo = db.Queryable<SysUser>().First(x => x.Id == saleId);
if (userInfo.UserNumber.IsNull())
{
return DataResult<string>.Failed("该揽货人用户编码未维护!");
}
sequenceNewNo += userInfo.UserNumber;
}
break;
case "shortdate": //短日期 年2位月2位日期2位
sequenceNewNo += date.HasValue ? date.Value.ToString("yyyyMMdd").Substring(2) : DateTime.Now.ToString("yyyyMMdd").Substring(2);
break;
case "date": //日期年4位
sequenceNewNo += date.HasValue ? date.Value.ToString("yyyyMMdd") : DateTime.Now.ToString("yyyyMMdd");
break;
case "ydate": //年月年4位月2位
sequenceNewNo += date.HasValue ? date.Value.ToString("yyyyMMdd").Substring(0, 6) : DateTime.Now.ToString("yyyyMMdd").Substring(0, 6);
break;
case "sydate": //年月年2位月2位
sequenceNewNo += date.HasValue ? date.Value.ToString("yyyyMMdd").Substring(2, 4) : DateTime.Now.ToString("yyyyMMdd").Substring(2, 4);
break;
case "timestamp": //日期时间精确到毫秒
sequenceNewNo += date.HasValue ? date.Value.ToString("yyyyMMddHHmmssffff") : DateTime.Now.ToString("yyyyMMddHHmmssffff");
break;
case "number": //计数,流水号
var prefix = sequenceNewNo;//前缀
businessSeq = tenantDb.Queryable<BusinessSequence>().Where(x => x.SequenceId == sequence.Id && x.Prefix == prefix).First();
int num = CurrentReset(sequence, item, businessSeq, tenantDb);
//计数拼接
sequenceNewNo += NumberingSeqRule(item, num).ToString();
//更新当前序号,
sequence.CurrentNo = num;
if (businessSeq.IsNull())
{
businessSeq = new BusinessSequence()
{
SequenceId = sequence.Id,
Prefix = prefix,
CurrentNo = num
};
}
else
{
businessSeq.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");
businessSeq.CurrentCode = sequenceNewNo;
businessSeq.CurrentReset = DateTime.Now.ToString("yyyyMMdd");
db.Updateable(sequence).ExecuteCommand();
tenantDb.Storageable(businessSeq).ExecuteCommand();
}
//catch (Exception)
//{
//}
finally
{
//if (Monitor.IsEntered(ImportLockObj))
Monitor.Exit(ImportLockObj);
}
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, BusinessSequence businessSeq, SqlSugarScopeProvider tenantDb)
{
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 (businessSeq.IsNull() || businessSeq.CurrentNo == 0)
{
newNo = ruleNo;
}
else
{
//当前序号+步长
//newNo = seq.CurrentNo + seq.Step;
newNo = businessSeq.CurrentNo + seq.Step;
}
}
return newNo;
}
#endregion
#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
}