cjy 2 months ago
commit c69791586d

@ -158,6 +158,23 @@ public static partial class Extensions
return reval; return reval;
} }
/// <summary>
///
/// </summary>
/// <param name="thisValue"></param>
/// <returns></returns>
public static long ObjToLong(this object thisValue)
{
long reval = 0;
if (thisValue == null) return 0;
if (thisValue != DBNull.Value && long.TryParse(thisValue.ToString(), out reval))
{
return reval;
}
return reval;
}
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>

@ -57,17 +57,31 @@ namespace DS.Module.Core.Filters
if (user != null && tenant != null) if (user != null && tenant != null)
{ {
ClaimsIdentity identity = new ClaimsIdentity("AuthenticationTypes.Federation"); // 认证方式1生成Token赋值到httpContext.Headers["Authorization"]
identity.AddClaims(new List<Claim> var tokenModel = new JwtHelper.JwtTokenModel
{ {
new Claim(JwtRegisteredClaimNames.Jti, user.Id.ToString()), Uid = user!.Id.ToString(),
new Claim("UserName", user.UserName), Name = user.UserName,
new Claim("TenantId", user.TenantId.ToString()), OrgId = user.DefaultOrgId.ToString(),
new Claim("TenantName", tenant.Name), TenantId = user.TenantId.ToString(),
new Claim("OrgId", user.DefaultOrgId.ToString()), TenantName = tenant!.Name,
}); };
ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity); var token = JwtHelper.Encrypt(tokenModel, false, true);
httpContext.User = claimsPrincipal;
httpContext!.Request.Headers["Authorization"] = "Bearer " + token;
// 认证方式2生成ClaimsIdentity赋值到httpContext.User
//ClaimsIdentity identity = new ClaimsIdentity("AuthenticationTypes.Federation");
//identity.AddClaims(new List<Claim>
//{
// new Claim(JwtRegisteredClaimNames.Jti, user.Id.ToString()),
// new Claim("UserName", user.UserName),
// new Claim("TenantId", user.TenantId.ToString()),
// new Claim("TenantName", tenant.Name),
// new Claim("OrgId", user.DefaultOrgId.ToString()),
//});
//ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity);
//httpContext.User = claimsPrincipal;
return next(); return next();
} }
} }

@ -56,7 +56,7 @@ namespace DS.Module.SqlSugar
{ {
var orgId = ((dynamic)entityInfo.EntityValue).OrgId; var orgId = ((dynamic)entityInfo.EntityValue).OrgId;
if (orgId == null || orgId == 0) if (orgId == null || orgId == 0)
entityInfo.SetValue(user.GetOrgId()); entityInfo.SetValue(user.OrgId);
} }
if (entityInfo.PropertyName == "CreateBy") if (entityInfo.PropertyName == "CreateBy")

@ -85,8 +85,8 @@ public static class SqlsugarInstall
// } // }
// }); // });
//} //}
var httpContextAccessor = services.GetService<IHttpContextAccessor>(); //var httpContextAccessor = services.GetService<IHttpContextAccessor>();
var user = services.GetService<IUser>(); //var user = services.GetService<IUser>();
//if (user.IsNullOrEmpty()) //if (user.IsNullOrEmpty())
//{ //{
// user = new AspNetUser(httpContextAccessor) // user = new AspNetUser(httpContextAccessor)
@ -110,7 +110,7 @@ public static class SqlsugarInstall
var dbProvider = db.GetConnectionScope((string)c.ConfigId); var dbProvider = db.GetConnectionScope((string)c.ConfigId);
// var user = services.GetService<IUser>(); var user = services.GetService<IUser>();
//单例参数配置,所有上下文生效 //单例参数配置,所有上下文生效
dbProvider.Ado.CommandTimeOut = 30; dbProvider.Ado.CommandTimeOut = 30;
dbProvider.Aop.OnLogExecuting = (sql, pars) => dbProvider.Aop.OnLogExecuting = (sql, pars) =>
@ -189,7 +189,7 @@ public static class SqlsugarInstall
{ {
var orgId = ((dynamic)entityInfo.EntityValue).OrgId; var orgId = ((dynamic)entityInfo.EntityValue).OrgId;
if (orgId == null || orgId == 0) if (orgId == null || orgId == 0)
entityInfo.SetValue(user.GetOrgId()); entityInfo.SetValue(user.OrgId);
} }
if (entityInfo.PropertyName == "CreateBy") if (entityInfo.PropertyName == "CreateBy")
@ -273,7 +273,7 @@ public static class SqlsugarInstall
}; };
//全局过滤租户 //全局过滤租户
dbProvider.QueryFilter.AddTableFilter<ITenantId>(m => m.TenantId == user.GetTenantId()); dbProvider.QueryFilter.AddTableFilter<ITenantId>(m => m.TenantId == long.Parse(user.TenantId));
//全局过滤机构Id //全局过滤机构Id
dbProvider.QueryFilter.AddTableFilter<IOrgId>(m => m.OrgId == user.OrgId); dbProvider.QueryFilter.AddTableFilter<IOrgId>(m => m.OrgId == user.OrgId);
//全局软删除过滤 //全局软删除过滤

@ -1,7 +1,5 @@
using DS.Module.Core; using DS.Module.Core.Extensions;
using DS.Module.Core.Extensions;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System.IdentityModel.Tokens.Jwt; using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims; using System.Security.Claims;
@ -16,439 +14,67 @@ public class AspNetUser : IUser
_accessor = accessor; _accessor = accessor;
} }
public UserInfo UserInfo => GetUserInfo(); public string UserId => GetClaimValueByType("jti") ?? "90001";
public string UserName => GetClaimValueByType("UserName") ?? "IUser获取UserName意外为空";
public string TenantId => GetClaimValueByType("TenantId") ?? "90002";
public string TenantName => GetClaimValueByType("TenantName") ?? "IUser获取TenantName意外为空";
public long OrgId => GetClaimValueByType("OrgId")?.ObjToLong() ?? 90003;
//public string GetToken()
//{
// return _accessor.HttpContext?.Request?.Headers["Authorization"].ToString().Replace("Bearer ", "");
//}
//public string UserId => GetClaimValueByType("jti").FirstOrDefault().ObjToString();
private string _userId;
public string UserId
public string? GetClaimValueByType(string claimType)
{ {
get return Claims.Where(x => x.Type == claimType).Select(x => x.Value).FirstOrDefault();
{
if (_userId == null)
{
var claimValue = GetClaimValueByType("jti").FirstOrDefault();
_userId = claimValue != null ? claimValue.ObjToString() : GetUserId().ToString();
}
return _userId;
}
set
{
_userId = value;
}
} }
private string _userName;
public string UserName private List<Claim>? _claims;
public List<Claim> Claims
{ {
get get
{ {
if (_userName == null) if (_claims == null || _claims.Count == 0)
{ {
var claimValue = GetClaimValueByType("UserName").FirstOrDefault(); _claims = GetClaimsIdentity().ToList();
_userName = claimValue != null ? claimValue.ObjToString() : "管理员";
} }
return _userName; return _claims;
}
set
{
_userName = value;
} }
} }
private string _tenantName;
public string TenantName
{
get
{
if (_tenantName == null)
{
var claimValue = GetClaimValueByType("TenantName").FirstOrDefault();
_tenantName = claimValue != null ? claimValue.ObjToString() : "系统租户";
}
return _tenantName;
}
set
{
_tenantName = value;
}
}
public long GetTenantId()
{
var token = GetToken();
if (string.IsNullOrEmpty(token))
{
return 2;
}
var jwtHandler = new JwtSecurityTokenHandler();
if (!jwtHandler.CanReadToken(token))
{
return 3;
}
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token); IEnumerable<Claim> GetClaimsIdentity()
var tenantIdClaim = jwtToken.Claims.FirstOrDefault(x => x.Type == "TenantId");
return tenantIdClaim != null ? Convert.ToInt64(tenantIdClaim.Value) : 4;
}
//public long GetTenantId()
//{
// // return _accessor.HttpContext?.Request?.Headers["Authorization"].ToString().Replace("Bearer ", "");
// var tenantId = String.Empty;
// var token = _accessor.HttpContext?.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last()
// ?? _accessor.HttpContext?.Request.Headers["X-Token"].FirstOrDefault()
// ?? _accessor.HttpContext?.Request.Query["Token"].FirstOrDefault()
// ?? _accessor.HttpContext?.Request.Cookies["Token"];
// // token校验
// var jwtHandler = new JwtSecurityTokenHandler();
// if (!token.IsNullOrEmpty() && jwtHandler.CanReadToken(token))
// {
// JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
// tenantId = jwtToken.Claims.First(x => x.Type == "TenantId").Value;
// }
// return Convert.ToInt64(tenantId);
//}
public long GetOrgId()
{ {
//if (_orgId == 0) if (_accessor.HttpContext == null) return ArraySegment<Claim>.Empty;
//{
// var claimValue = GetClaimValueByType("OrgId").FirstOrDefault();
// _orgId = claimValue != null ? long.Parse(claimValue) : 0;
//}
//return _orgId;
var token = GetToken(); var token = GetToken();
if (string.IsNullOrEmpty(token))
{
return 5;
}
var jwtHandler = new JwtSecurityTokenHandler();
if (!jwtHandler.CanReadToken(token))
{
return 6;
}
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
var orgIdClaim = jwtToken.Claims.FirstOrDefault(x => x.Type == "OrgId");
return orgIdClaim != null ? Convert.ToInt64(orgIdClaim.Value) : 7;
}
public long GetUserId()
{
var token = GetToken();
if (string.IsNullOrEmpty(token))
{
return 8;
}
var jwtHandler = new JwtSecurityTokenHandler();
if (!jwtHandler.CanReadToken(token))
{
return 9;
}
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
var userIdClaim = jwtToken.Claims.FirstOrDefault(x => x.Type == "jti");
return userIdClaim != null ? Convert.ToInt64(userIdClaim.Value) : 10;
}
//public long GetOrgId()
//{
// // return _accessor.HttpContext?.Request?.Headers["Authorization"].ToString().Replace("Bearer ", "");
// var orgId = String.Empty;
// var token = _accessor.HttpContext?.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last()
// ?? _accessor.HttpContext?.Request.Headers["X-Token"].FirstOrDefault()
// ?? _accessor.HttpContext?.Request.Query["Token"].FirstOrDefault()
// ?? _accessor.HttpContext?.Request.Cookies["Token"];
// // token校验
// var jwtHandler = new JwtSecurityTokenHandler();
// if (!token.IsNullOrEmpty() && jwtHandler.CanReadToken(token))
// {
// JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
// orgId = jwtToken.Claims.First(x => x.Type == "OrgId").Value;
// }
// return Convert.ToInt64(orgId);
//}
//public string GetCompanyId()
//{
// // return _accessor.HttpContext?.Request?.Headers["Authorization"].ToString().Replace("Bearer ", "");
// var companyId = String.Empty;
// var token = _accessor.HttpContext?.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last()
// ?? _accessor.HttpContext?.Request.Headers["X-Token"].FirstOrDefault()
// ?? _accessor.HttpContext?.Request.Query["Token"].FirstOrDefault()
// ?? _accessor.HttpContext?.Request.Cookies["Token"];
// // token校验
// var jwtHandler = new JwtSecurityTokenHandler();
// if (!token.IsNullOrEmpty() && jwtHandler.CanReadToken(token))
// {
// JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
// companyId = jwtToken.Claims.First(x => x.Type == "OrgId").Value;
// }
// return companyId;
//}
public string GetCompanyId()
{
var token = GetToken();
if (string.IsNullOrEmpty(token))
{
return string.Empty;
}
var jwtHandler = new JwtSecurityTokenHandler(); var jwtHandler = new JwtSecurityTokenHandler();
if (!jwtHandler.CanReadToken(token)) if (token.IsNotEmptyOrNull() && jwtHandler.CanReadToken(token))
{
return string.Empty;
}
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
var companyIdClaim = jwtToken.Claims.FirstOrDefault(x => x.Type == "OrgId");
return companyIdClaim?.Value ?? "0000000001";
}
//public string TenantId => GetClaimValueByType("TenantId").FirstOrDefault().ObjToString();
private string _tenantId;
public string TenantId
{
get
{ {
if (_tenantId == null) JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
{ return jwtToken.Claims;
var tenantIdClaim = GetClaimValueByType("TenantId").FirstOrDefault();
_tenantId = tenantIdClaim != null ? tenantIdClaim.ObjToString() : GetTenantId().ToString();
}
return _tenantId;
} }
set else
{ {
_tenantId = value; return ArraySegment<Claim>.Empty;
} }
} }
public bool IsAuthenticated()
// public string CompanyId => GetClaimValueByType("CompanyId").FirstOrDefault().ObjToString();
private string _companyId;
public string CompanyId
{ {
get return _accessor.HttpContext?.User?.Identity?.IsAuthenticated ?? false;
{
if (_companyId == null)
{
var companyIdClaim = GetClaimValueByType("CompanyId").FirstOrDefault();
_companyId = companyIdClaim != null ? companyIdClaim.ObjToString() : "东胜软件";
}
return _companyId;
}
set
{
_companyId = value;
}
} }
// public string OrgId => GetClaimValueByType("OrgId").FirstOrDefault().ObjToString();
private long _orgId;
public long OrgId
{
get
{
if (_orgId == 0)
{
var orgIdClaim = GetClaimValueByType("OrgId").FirstOrDefault();
_orgId = orgIdClaim != null ? long.Parse(orgIdClaim) : GetOrgId();
}
return _orgId;
}
set
{
_orgId = value;
}
}
public UserInfo GetUserInfo()
{
var user = _accessor.HttpContext?.User;
if (user == null || !user.Claims.Any())
{
return null;
// return GetDefaultUserInfo();
}
var token = GetToken();
if (string.IsNullOrEmpty(token))
{
return null;
// return GetDefaultUserInfo();
}
var jwtHandler = new JwtSecurityTokenHandler();
if (!jwtHandler.CanReadToken(token))
{
return null;
// return GetDefaultUserInfo();
}
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
var userInfoJson = jwtToken.Claims.First().Value;
var userInfo = JsonConvert.DeserializeObject<UserInfo>(userInfoJson);
return userInfo ?? null;
}
public string GetToken() public string GetToken()
{ {
if (_accessor == null || _accessor.HttpContext == null) var token = _accessor.HttpContext?.Request?.Headers["Authorization"].ObjToString().Replace("Bearer ", "");
{ if (!string.IsNullOrWhiteSpace(token))
return "东胜软件";
}
var request = _accessor.HttpContext.Request;
var authorizationHeader = request.Headers["Authorization"].FirstOrDefault();
if (!string.IsNullOrEmpty(authorizationHeader))
{
return authorizationHeader.Split(" ").Last();
}
return request.Headers["X-Token"].FirstOrDefault()
?? request.Query["Token"].FirstOrDefault()
?? request.Cookies["Token"]
?? "东胜软件";
}
#region 优化前
//public string GetToken()
//{
// var headers = _accessor.HttpContext?.Request?.Headers;
// if (headers != null && headers.ContainsKey("Authorization"))
// {
// return headers["Authorization"].ToString().Replace("Bearer ", "");
// }
// return null;
//}
//public UserInfo GetUserInfo()
//{
// if (_accessor.HttpContext.User.Claims == null)
// {
// return new UserInfo()
// {
// CompanyId = "1",
// CompanyName = "初始化",
// Token = "初始化",
// UserCode = "初始化",
// UserId = "00000000",
// UserName = "初始化",
// };
// }
// //var json = _accessor.HttpContext.User.Claims;
// //获取上传token可自定义扩展
// var httphedad = _accessor.HttpContext.Request;
// var token = httphedad.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last()
// ?? httphedad.Headers["X-Token"].FirstOrDefault()
// ?? httphedad.Query["Token"].FirstOrDefault()
// ?? httphedad.Cookies["Token"];
// // token校验
// var jwtHandler = new JwtSecurityTokenHandler();
// var userInfo = new UserInfo();
// if (!token.IsNullOrEmpty() && jwtHandler.CanReadToken(token))
// {
// JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
// var UserId = jwtToken.Claims.First().Value;
// // userInfo = db.Queryable<SysUser>()
// // .Where(a =>
// // a.Deleted == false && a.Id == user.Id)
// // .Select(a => new UserInfo
// // {
// // UserId = a.Id, UserCode = a.UserCode, UserName = a.NickName,
// // // OrgId = a.OrgId.ToString(), CompanyName = a.CustomerName
// // }).First();
// // var t1 = JsonConvert.DeserializeObject<UserInfo>(temp);
// userInfo = JsonConvert.DeserializeObject<UserInfo>(jwtToken.Claims.First().Value);
// }
// return userInfo;
//}
//public IEnumerable<Claim> GetClaimsIdentity()
//{
// var claims = _accessor.HttpContext.User.Claims.ToList();
// var headers = _accessor.HttpContext.Request.Headers;
// foreach (var header in headers)
// {
// claims.Add(new Claim(header.Key, header.Value));
// }
// return claims;
//}
#endregion 优化前
/// <summary>
/// 保持在请求上下文中的所有声明 不为空
/// </summary>
/// <returns></returns>
public IEnumerable<Claim> GetClaimsIdentity()
{
var claims = new List<Claim>();
var user = _accessor.HttpContext?.User;
if (user != null)
{ {
claims.AddRange(user.Claims); return token;
} }
return "IUser通过GetToken()获取Token意外为空";
var headers = _accessor.HttpContext?.Request?.Headers; //有需要再返回
if (headers != null) //return _accessor.HttpContext?.Request.Headers["X-Token"].FirstOrDefault()
{ // ?? _accessor.HttpContext?.Request.Query["Token"].FirstOrDefault()
foreach (var header in headers) // ?? _accessor.HttpContext?.Request.Cookies["Token"]
{ // ?? "东胜软件";
foreach (var value in header.Value)
{
if (!string.IsNullOrEmpty(value))
{
claims.Add(new Claim(header.Key, value));
}
}
}
}
return claims;
}
#region 键值对获取相应的内容 如果内容不存在则返回默认值 GetClaimValueByType
/// <summary>
/// 键值对获取相应的内容 如果内容不存在则返回默认值
/// </summary>
/// <param name="ClaimType"></param>
/// <returns></returns>
public List<string> GetClaimValueByType(string ClaimType)
{
var claimsIdentity = GetClaimsIdentity();
// if (claimsIdentity == null || !claimsIdentity.Any(item => item.Type == ClaimType))
// {
// return new List<string> { "jti", "TenantId", "CompanyId", "OrgId" }; // 返回包含默认参数的列表
// }
return claimsIdentity.Where(item => item.Type == ClaimType).Select(item => item.Value).ToList();
} }
#endregion 键值对获取相应的内容 如果内容不存在则返回默认值 GetClaimValueByType
} }

@ -1,5 +1,4 @@
using DS.Module.Core; 
namespace DS.Module.UserModule; namespace DS.Module.UserModule;
/// <summary> /// <summary>
@ -7,57 +6,41 @@ namespace DS.Module.UserModule;
/// </summary> /// </summary>
public interface IUser public interface IUser
{ {
/// <summary>
/// 获取用户信息
/// </summary>
UserInfo UserInfo { get; }
/// <summary> /// <summary>
/// 获取用户ID /// 获取用户ID
/// </summary> /// </summary>
string UserId { get; } string UserId { get; }
/// <summary> /// <summary>
/// 获取用户名称 /// 获取用户名称
/// </summary> /// </summary>
string UserName { get; } string UserName { get; }
/// <summary>
/// 获取公司ID
/// </summary>
string CompanyId { get; }
/// <summary> /// <summary>
/// 租户ID /// 租户ID
/// </summary> /// </summary>
string TenantId { get; } string TenantId { get; }
/// <summary> /// <summary>
/// 租户名称 /// 租户名称
/// </summary> /// </summary>
string TenantName { get; } string TenantName { get; }
/// <summary> /// <summary>
/// 机构ID /// 机构ID
/// </summary> /// </summary>
long OrgId { get; } long OrgId { get; }
/// <summary> /// <summary>
/// 获取机构ID /// 返回Token
/// </summary>
long GetOrgId();
/// <summary>
/// 获取公司ID
/// </summary> /// </summary>
string GetCompanyId(); string GetToken();
/// <summary> /// <summary>
/// 获取租户ID /// 根据Claim类型返回Claim的值
/// </summary> /// </summary>
long GetTenantId(); string? GetClaimValueByType(string claimType);
/// <summary> /// <summary>
/// 获取Token /// 返回当前用户是否已经过认证
/// </summary> /// </summary>
/// <returns></returns> bool IsAuthenticated();
string GetToken();
} }

@ -17,6 +17,7 @@ public static class UserModuleInstall
if (services == null) throw new ArgumentNullException(nameof(services)); if (services == null) throw new ArgumentNullException(nameof(services));
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
//services.AddTransient<IUser, AspNetUser>();
services.AddScoped<IUser, AspNetUser>(); services.AddScoped<IUser, AspNetUser>();
} }
} }

@ -64,7 +64,7 @@ public class CodeFormCopyService : IFormCopyService
if (req.Id == 0) if (req.Id == 0)
{ {
if (tenantDb.Queryable<CodeFormCopy>() if (tenantDb.Queryable<CodeFormCopy>()
.Where(x => x.OrgId == user.GetOrgId() && x.PermissionId == req.PermissionId && x.CreateBy == long.Parse(user.UserId)).Any()) .Where(x => x.OrgId == user.OrgId && x.PermissionId == req.PermissionId && x.CreateBy == long.Parse(user.UserId)).Any())
{ {
return DataResult.Failed("表单复制字段设置已存在!", MultiLanguageConst.FormCopyExist); return DataResult.Failed("表单复制字段设置已存在!", MultiLanguageConst.FormCopyExist);
} }

@ -65,7 +65,7 @@ public class CodeFormSetService : IFormSetService
if (req.Id == 0) if (req.Id == 0)
{ {
if (tenantDb.Queryable<CodeFormSet>() if (tenantDb.Queryable<CodeFormSet>()
.Where(x => x.OrgId == user.GetOrgId() && x.PermissionId == req.PermissionId && x.FormNo == req.FormNo).Any()) .Where(x => x.OrgId == user.OrgId && x.PermissionId == req.PermissionId && x.FormNo == req.FormNo).Any())
{ {
return DataResult.Failed("表单设置已存在!", MultiLanguageConst.FormSetExist); return DataResult.Failed("表单设置已存在!", MultiLanguageConst.FormSetExist);
} }

@ -65,7 +65,7 @@ public class CodeQuerySetService : IQuerySetService
if (req.Id == 0) if (req.Id == 0)
{ {
if (tenantDb.Queryable<CodeQuerySet>() if (tenantDb.Queryable<CodeQuerySet>()
.Where(x => x.OrgId == user.GetOrgId() && x.PermissionId == req.PermissionId && x.TagNo == req.TagNo).Any()) .Where(x => x.OrgId == user.OrgId && x.PermissionId == req.PermissionId && x.TagNo == req.TagNo).Any())
{ {
return DataResult.Failed("查询条件设置已存在!", MultiLanguageConst.QuerySetExist); return DataResult.Failed("查询条件设置已存在!", MultiLanguageConst.QuerySetExist);
} }

@ -57,7 +57,7 @@ public class CodeSequenceService : ICodeSequenceService
if (req.Id == 0) if (req.Id == 0)
{ {
if (tenantDb.Queryable<CodeSequence>().Where(x => x.PermissionId == req.PermissionId && x.OrderNo == req.OrderNo).Any()) if (tenantDb.Queryable<CodeSequence>().Where(x => x.PermissionId == req.PermissionId && x.SequenceName == req.SequenceName).Any())
{ {
return DataResult.Failed("基础编码已存在!", MultiLanguageConst.SequenceExist); return DataResult.Failed("基础编码已存在!", MultiLanguageConst.SequenceExist);
} }

@ -0,0 +1,48 @@
using DS.Module.Core;
using DS.Module.UserModule;
using DS.WMS.Core.Op.Entity;
using SqlSugar;
namespace DS.WMS.Core.Fee.Dtos
{
/// <summary>
/// 报表生成上下文
/// </summary>
public class ReportContext
{
/// <summary>
/// 服务提供程序
/// </summary>
public IServiceProvider ServiceProvider { get; internal set; }
/// <summary>
/// 获取主库访问对象
/// </summary>
public ISqlSugarClient Db { get; internal set; }
/// <summary>
/// 获取租户库访问对象
/// </summary>
public ISqlSugarClient TenantDb { get; internal set; }
/// <summary>
/// 请求用户
/// </summary>
public IUser User { get; internal set; }
/// <summary>
/// 操作结果,用于记录错误信息
/// </summary>
public DataResult? ErrorResult { get; set; }
/// <summary>
/// 业务类型
/// </summary>
public BusinessType BusinessType { get; set; } = BusinessType.OceanShippingExport;
/// <summary>
/// 业务ID
/// </summary>
public long[] Ids { get; set; } = [];
}
}

@ -96,12 +96,13 @@ public interface IFeeRecordService
Task WriteBackStatusAsync(long businessId, BusinessType businessType); Task WriteBackStatusAsync(long businessId, BusinessType businessType);
/// <summary> /// <summary>
/// 获取费用核算单打印信息 /// 获取费用打印信息
/// </summary> /// </summary>
/// <param name="providerName">数据提供程序</param>
/// <param name="businessType">业务类型</param> /// <param name="businessType">业务类型</param>
/// <param name="idArray">费用记录ID</param> /// <param name="idArray">费用记录ID</param>
/// <returns></returns> /// <returns></returns>
Task<DataResult<CostAccountingForm>> GetPrintInfoAsync(BusinessType businessType, params long[] idArray); Task<DataResult<dynamic>> GetPrintInfoAsync(string providerName, BusinessType businessType, params long[] idArray);
/// <summary> /// <summary>
/// 设置发票启用状态 /// 设置发票启用状态

@ -0,0 +1,17 @@
using DS.WMS.Core.Fee.Dtos;
namespace DS.WMS.Core.Fee.Interface
{
/// <summary>
/// 用于输出报表的数据提供程序
/// </summary>
public interface IReportProvider
{
/// <summary>
/// 返回所需的JSON格式的数据
/// </summary>
/// <param name="context">报表输出上下文</param>
/// <returns></returns>
Task<dynamic?> GetDataAsync(ReportContext context);
}
}

@ -222,7 +222,7 @@ namespace DS.WMS.Core.Fee.Method
item.Quantity = ctn == null ? 0 : ctn.CtnNum.GetValueOrDefault(); item.Quantity = ctn == null ? 0 : ctn.CtnNum.GetValueOrDefault();
break; break;
} }
} }
//计算税费 //计算税费
item.SetTax(); item.SetTax();
@ -927,110 +927,33 @@ namespace DS.WMS.Core.Fee.Method
} }
/// <summary> /// <summary>
/// 获取费用核算单打印信息 /// 获取费用打印信息
/// </summary> /// </summary>
/// <param name="providerName"></param>
/// <param name="businessType">业务类型</param> /// <param name="businessType">业务类型</param>
/// <param name="idArray">费用记录ID</param> /// <param name="idArray">费用记录ID</param>
/// <returns></returns> /// <returns></returns>
public async Task<DataResult<CostAccountingForm>> GetPrintInfoAsync(BusinessType businessType, params long[] idArray) public async Task<DataResult<dynamic>> GetPrintInfoAsync(string providerName, BusinessType businessType, params long[] idArray)
{
CostAccountingForm form = null;
switch (businessType)
{
case BusinessType.OceanShippingExport:
form = await GetOceanShippingExportAsync(idArray);
break;
case BusinessType.OceanShippingImport:
break;
default:
return DataResult<CostAccountingForm>.Failed(string.Format(
MultiLanguageConst.BusinessNotSupported, businessType.GetDescription()));
}
if (form != null)
{
long UserId = long.Parse(User.UserId);
form.Creator = Db.Queryable<SysUser>().Where(x => x.Id == UserId).Select(x => x.UserName).First();
form.ReceivableRMB = form.Details.FindAll(x => x.Type == FeeType.Receivable && x.Currency == FeeCurrency.RMB_CODE).Sum(x => x.Amount);
form.PayableRMB = form.Details.FindAll(x => x.Type == FeeType.Payable && x.Currency == FeeCurrency.RMB_CODE).Sum(x => x.Amount);
form.ReceivableUSD = form.Details.FindAll(x => x.Type == FeeType.Receivable && x.Currency == FeeCurrency.USD_CODE).Sum(x => x.Amount);
form.PayableUSD = form.Details.FindAll(x => x.Type == FeeType.Payable && x.Currency == FeeCurrency.USD_CODE).Sum(x => x.Amount);
form.ReceivableOther = form.Details.FindAll(x => x.Type == FeeType.Receivable && (x.Currency != FeeCurrency.RMB_CODE && x.Currency != FeeCurrency.USD_CODE)).Sum(x => x.Amount);
form.PayableOther = form.Details.FindAll(x => x.Type == FeeType.Payable && (x.Currency == FeeCurrency.RMB_CODE && x.Currency != FeeCurrency.USD_CODE)).Sum(x => x.Amount);
//获取美元汇率
var fees = new List<FeeRecord> {
new FeeRecord { Currency = FeeCurrency.USD_CODE, FeeType = FeeType.Receivable },
new FeeRecord { Currency = FeeCurrency.USD_CODE, FeeType = FeeType.Payable }
};
await FetchExchangeRateAsync(fees);
form.ExchangeRate = fees[0].ExchangeRate.HasValue ? fees[0].ExchangeRate.Value : 1;
form.TotalReceivable = Math.Round(form.ReceivableUSD * form.ExchangeRate, 4, MidpointRounding.ToEven) + form.ReceivableRMB + form.ReceivableOther;
form.TotalPayable = Math.Round(form.PayableUSD * form.ExchangeRate, 4, MidpointRounding.ToEven) + form.PayableRMB + form.PayableOther;
}
return DataResult<CostAccountingForm>.Success(form);
}
//获取海运出口打印数据
async Task<CostAccountingForm> GetOceanShippingExportAsync(params long[] idArray)
{ {
CostAccountingForm form = null; Type type = Type.GetType(providerName, false);
var list = await TenantDb.Queryable<FeeRecord>().InnerJoin<SeaExport>((x, y) => x.BusinessId == y.Id) if (type == null)
.Where((x, y) => idArray.Contains(x.Id) return DataResult<dynamic>.Failed("未能找到数据提供程序");
//&& x.FeeStatus == FeeStatus.SettlementCompleted
).Select((x, y) => new
{
x.FeeType,
x.FeeName,
x.Currency,
x.ExchangeRate,
x.Amount,
x.CustomerName,
y.CustomerNo, //业务编号
y.AccountDate, //会计期间
y.ETA,
y.ETD,
y.Voyno,
y.MBLNO,
y.Carrier,
y.LoadPort,
y.DischargePort,
y.CntrTotal, //Volume
y.IssueType //放单方式
}).ToListAsync();
if (list.Count == 0)
return form;
var item = list[0]; var provider = Fasterflect.ConstructorExtensions.CreateInstance(type) as IReportProvider;
form = new CostAccountingForm var context = new ReportContext
{ {
BusinessNo = item.CustomerNo, BusinessType = businessType,
AccountingPeriod = item.AccountDate, Ids = idArray,
ETA = item.ETA, Db = Db,
ETD = item.ETD, TenantDb = TenantDb,
Voy = item.Voyno, User = User,
MBLNo = item.MBLNO, ServiceProvider = ServiceProvider
Carrier = item.Carrier,
POL = item.LoadPort,
POD = item.DischargePort,
Volume = item.CntrTotal,
ReleaseType = item.IssueType,
PrintTime = DateTime.Now,
Details = list.Select(x => new CostAccountingDetail
{
Amount = x.Amount,
Currency = x.Currency,
CustomerName = x.CustomerName,
FeeName = x.FeeName,
Type = x.FeeType
}).ToList()
}; };
var data = provider.GetDataAsync(context);
if (context.ErrorResult == null)
return DataResult<dynamic>.Success(data);
return form; return DataResult<dynamic>.Failed(context.ErrorResult.Message, context.ErrorResult.MultiCode);
} }
/// <summary> /// <summary>

@ -0,0 +1,123 @@
using DS.Module.Core;
using DS.WMS.Core.Fee.Dtos;
using DS.WMS.Core.Fee.Entity;
using DS.WMS.Core.Fee.Interface;
using DS.WMS.Core.Op.Entity;
using DS.WMS.Core.Sys.Entity;
using Masuit.Tools.Systems;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
namespace DS.WMS.Core.Fee.Method.ReportProviders
{
/// <summary>
/// 费用核算单
/// </summary>
public class CostAccountingReport : IReportProvider
{
public async Task<dynamic?> GetDataAsync(ReportContext context)
{
CostAccountingForm? form = null;
switch (context.BusinessType)
{
case BusinessType.OceanShippingExport:
form = await GetOceanShippingExportAsync(context.TenantDb, context.Ids);
break;
case BusinessType.OceanShippingImport:
break;
default:
context.ErrorResult = DataResult.Failed(string.Format(MultiLanguageConst.GetDescription(
MultiLanguageConst.BusinessNotSupported), context.BusinessType.GetDescription()));
break;
}
if (form != null)
{
long UserId = long.Parse(context.User.UserId);
form.Creator = context.Db.Queryable<SysUser>().Where(x => x.Id == UserId).Select(x => x.UserName).First();
form.ReceivableRMB = form.Details.FindAll(x => x.Type == FeeType.Receivable && x.Currency == FeeCurrency.RMB_CODE).Sum(x => x.Amount);
form.PayableRMB = form.Details.FindAll(x => x.Type == FeeType.Payable && x.Currency == FeeCurrency.RMB_CODE).Sum(x => x.Amount);
form.ReceivableUSD = form.Details.FindAll(x => x.Type == FeeType.Receivable && x.Currency == FeeCurrency.USD_CODE).Sum(x => x.Amount);
form.PayableUSD = form.Details.FindAll(x => x.Type == FeeType.Payable && x.Currency == FeeCurrency.USD_CODE).Sum(x => x.Amount);
form.ReceivableOther = form.Details.FindAll(x => x.Type == FeeType.Receivable && (x.Currency != FeeCurrency.RMB_CODE && x.Currency != FeeCurrency.USD_CODE)).Sum(x => x.Amount);
form.PayableOther = form.Details.FindAll(x => x.Type == FeeType.Payable && (x.Currency == FeeCurrency.RMB_CODE && x.Currency != FeeCurrency.USD_CODE)).Sum(x => x.Amount);
//获取美元汇率
var currencyService = context.ServiceProvider.GetRequiredService<IFeeCurrencyExchangeService>();
var exchange = new ExchangeRate
{
CurrencyFrom = FeeCurrency.USD_CODE,
CurrencyTo = FeeCurrency.RMB_CODE
};
exchange = (await currencyService.GetExchangeRateAsync(exchange))?.Data;
form.ExchangeRate = exchange.Rate;
form.TotalReceivable = Math.Round(form.ReceivableUSD * form.ExchangeRate, 4, MidpointRounding.ToEven) + form.ReceivableRMB + form.ReceivableOther;
form.TotalPayable = Math.Round(form.PayableUSD * form.ExchangeRate, 4, MidpointRounding.ToEven) + form.PayableRMB + form.PayableOther;
}
return form;
}
//获取海运出口打印数据
static async Task<CostAccountingForm> GetOceanShippingExportAsync(ISqlSugarClient tenantDb, params long[] idArray)
{
CostAccountingForm form = null;
var list = await tenantDb.Queryable<FeeRecord>().InnerJoin<SeaExport>((x, y) => x.BusinessId == y.Id)
.Where((x, y) => idArray.Contains(x.Id)
//&& x.FeeStatus == FeeStatus.SettlementCompleted
).Select((x, y) => new
{
x.FeeType,
x.FeeName,
x.Currency,
x.ExchangeRate,
x.Amount,
x.CustomerName,
y.CustomerNo, //业务编号
y.AccountDate, //会计期间
y.ETA,
y.ETD,
y.Voyno,
y.MBLNO,
y.Carrier,
y.LoadPort,
y.DischargePort,
y.CntrTotal, //Volume
y.IssueType //放单方式
}).ToListAsync();
if (list.Count == 0)
return form;
var item = list[0];
form = new CostAccountingForm
{
BusinessNo = item.CustomerNo,
AccountingPeriod = item.AccountDate,
ETA = item.ETA,
ETD = item.ETD,
Voy = item.Voyno,
MBLNo = item.MBLNO,
Carrier = item.Carrier,
POL = item.LoadPort,
POD = item.DischargePort,
Volume = item.CntrTotal,
ReleaseType = item.IssueType,
PrintTime = DateTime.Now,
Details = list.Select(x => new CostAccountingDetail
{
Amount = x.Amount,
Currency = x.Currency,
CustomerName = x.CustomerName,
FeeName = x.FeeName,
Type = x.FeeType
}).ToList()
};
return form;
}
}
}

@ -463,7 +463,7 @@ namespace DS.WMS.Core.Op.Method.TaskInteraction
{ {
BusinessTask task = await GetQuery(request.BusinessId, request.BusinessType, request.TaskType).FirstAsync(); BusinessTask task = await GetQuery(request.BusinessId, request.BusinessType, request.TaskType).FirstAsync();
if (task == null) if (task == null)
return DataResult.FailedWithDesc(nameof(MultiLanguageConst.EmptyData)); return DataResult.FailedWithDesc(nameof(MultiLanguageConst.TaskNotExists));
if (task.TaskStatus == TaskStatusEnum.Complete) if (task.TaskStatus == TaskStatusEnum.Complete)
return DataResult.FailedWithDesc(nameof(MultiLanguageConst.TaskCompleted)); return DataResult.FailedWithDesc(nameof(MultiLanguageConst.TaskCompleted));
//if (task.TaskStatus == TaskStatusEnum.Cancel) //if (task.TaskStatus == TaskStatusEnum.Cancel)
@ -869,16 +869,20 @@ namespace DS.WMS.Core.Op.Method.TaskInteraction
if (callback.FlowStatus == FlowStatusEnum.Reject) if (callback.FlowStatus == FlowStatusEnum.Reject)
{ {
var task = await GetQuery(callback.BusinessId, callback.BusinessType, callback.AuditType.Value).FirstAsync(); var task = await GetQuery(callback.BusinessId, callback.BusinessType, callback.AuditType.Value).FirstAsync();
//创建驳回任务以进行通知 var request = new TaskCreationRequest
await CreateTaskAsync(new TaskCreationRequest
{ {
BusinessId = callback.BusinessId, BusinessId = callback.BusinessId,
BusinessType = callback.BusinessType, BusinessType = callback.BusinessType,
TaskTypeName = GetRejectedType(callback.AuditType.Value).ToString(), TaskTypeName = GetRejectedType(callback.AuditType.Value).ToString(),
RecvUserIdList = [task.CreateBy] //通知任务发起人 RecvUserIdList = [task.CreateBy] //通知任务发起人
}); };
//创建驳回任务以进行通知
await CreateTaskAsync(request);
//更新任务描述为驳回原因
await SetTaskBaseDescription(callback.BusinessId, request.TaskType, callback.RejectReason);
remark += ";驳回理由:" + callback.RejectReason; remark += ";驳回原因" + callback.RejectReason;
} }
long userId = long.Parse(User.UserId); long userId = long.Parse(User.UserId);

@ -104,7 +104,7 @@ public class CommonService : ICommonService
public DataResult<CurrentUserViewModel> GetUserInfo() public DataResult<CurrentUserViewModel> GetUserInfo()
{ {
var userId = long.Parse(user.UserId); var userId = long.Parse(user.UserId);
var tenantId = user.GetTenantId(); var tenantId = long.Parse(user.TenantId);
var tokenModel = new JwtHelper.JwtTokenModel var tokenModel = new JwtHelper.JwtTokenModel
{ {
Uid = user.UserId, Uid = user.UserId,
@ -292,7 +292,7 @@ public class CommonService : ICommonService
} }
var userId = long.Parse(user.UserId); var userId = long.Parse(user.UserId);
var tenantId = user.GetTenantId(); var tenantId = long.Parse(user.TenantId);
var tokenModel = new JwtHelper.JwtTokenModel var tokenModel = new JwtHelper.JwtTokenModel
{ {
@ -507,7 +507,7 @@ public class CommonService : ICommonService
public async Task<DataResult<CurrentUserViewModel>> GetClientUserInfo() public async Task<DataResult<CurrentUserViewModel>> GetClientUserInfo()
{ {
var userId = long.Parse(user.UserId); var userId = long.Parse(user.UserId);
var tenantId = user.GetTenantId(); var tenantId = long.Parse(user.TenantId);
//取第一个机构 //取第一个机构
var orgRelations = await db.Queryable<SysOrgUser>().Filter(null, true) var orgRelations = await db.Queryable<SysOrgUser>().Filter(null, true)
.LeftJoin<SysOrg>((a, b) => a.OrgId == b.Id) .LeftJoin<SysOrg>((a, b) => a.OrgId == b.Id)
@ -526,7 +526,7 @@ public class CommonService : ICommonService
{ {
Uid = user.UserId, Uid = user.UserId,
Name = userInfo.UserName, Name = userInfo.UserName,
OrgId = user.GetOrgId().ToString(), OrgId = user.OrgId.ToString(),
TenantId = tenantId.ToString(), TenantId = tenantId.ToString(),
TenantName = tenant.Name TenantName = tenant.Name
}; };
@ -544,7 +544,7 @@ public class CommonService : ICommonService
// ClientId = a.ClientId, // ClientId = a.ClientId,
IsUseSystem = a.IsUseSystem, IsUseSystem = a.IsUseSystem,
RefreshToken = refreshToken, RefreshToken = refreshToken,
OrgId = user.GetOrgId().ToString(), OrgId = user.OrgId.ToString(),
Tel = a.Tel, Tel = a.Tel,
Email = a.Email, Email = a.Email,
Phone = a.Phone, Phone = a.Phone,
@ -575,7 +575,7 @@ public class CommonService : ICommonService
public DataResult<RefreshTokenRes> ChangeOrg(string id) public DataResult<RefreshTokenRes> ChangeOrg(string id)
{ {
var userId = user.UserId; var userId = user.UserId;
var tenantId = user.GetTenantId(); var tenantId = long.Parse(user.TenantId);
var sysUser = db.Queryable<SysUser>().First(x => x.Id == long.Parse(userId)); var sysUser = db.Queryable<SysUser>().First(x => x.Id == long.Parse(userId));
if (sysUser.IsNull()) if (sysUser.IsNull())
{ {
@ -614,7 +614,7 @@ public class CommonService : ICommonService
public async Task<DataResult<List<RouteItem>>> GetClientUserPermissionByToken() public async Task<DataResult<List<RouteItem>>> GetClientUserPermissionByToken()
{ {
List<RouteItem> list = new List<RouteItem>(); List<RouteItem> list = new List<RouteItem>();
_logger.LogInformation("GetClientUserPermissionByToken临时日志user.UserId={userId},user.TenantId={TenantId},user.GetTenantId={GetTenantId}", user.UserId, user.TenantId, user.GetTenantId()); _logger.LogInformation("GetClientUserPermissionByToken临时日志user.UserId={userId},user.TenantId={TenantId}", user.UserId, user.TenantId);
var userId = long.Parse(user.UserId); var userId = long.Parse(user.UserId);

@ -260,14 +260,14 @@ namespace DS.WMS.Core.TaskPlat.Method
logger.LogInformation("批次={no} 接收到创建任务报文 报文={msg}", batchNo, JsonConvert.SerializeObject(info)); logger.LogInformation("批次={no} 接收到创建任务报文 报文={msg}", batchNo, JsonConvert.SerializeObject(info));
SqlSugarScopeProvider tenantDb = saasDbService.GetBizDbScopeById(user.TenantId); SqlSugarScopeProvider tenantDb = saasDbService.GetBizDbScopeById(user.TenantId);
//var sql = tenantDb.Queryable<SeaExport>().Where(x => x.Id > 232 ).ToSqlString();
//var a = user.UserId; // 人员信息测试用
//var aa = user.TenantId; //var a1 = user.UserId;
//var a343 = user.GetTenantId(); //var b1 = user.UserName;
//var sfdfd = user.TenantName; //var c1 = user.TenantId;
//var b = user.GetOrgId(); //var d1 = user.TenantName;
//var b232 = user.OrgId; //var e1 = user.OrgId;
//var sql = tenantDb.Queryable<SeaExport>().Where(x => x.Id > 232).ToSqlString();
TaskBaseInfo taskInfo = null; TaskBaseInfo taskInfo = null;
@ -3105,7 +3105,19 @@ namespace DS.WMS.Core.TaskPlat.Method
/// </summary> /// </summary>
public async Task<DataResult> TestTaskFlow(string taskType, long taskId, int testType) public async Task<DataResult> TestTaskFlow(string taskType, long taskId, int testType)
{ {
var tenantDb = saasDbService.GetBizDbScopeById(user.TenantId); var tenantDb = saasDbService.GetBizDbScopeById(user.TenantId);
// 人员信息测试用
var a1 = user.UserId;
var b1 = user.UserName;
var c1 = user.TenantId;
var d1 = user.TenantName;
var e1 = user.OrgId;
var sql = tenantDb.Queryable<SeaExport>().Where(x => x.Id > 232).ToSqlString();
var t11 = tenantDb.ContextID; var t11 = tenantDb.ContextID;
switch (testType) switch (testType)
{ {

@ -3,6 +3,7 @@ using DS.Module.Core.Data;
using DS.WMS.Core.Fee.Dtos; using DS.WMS.Core.Fee.Dtos;
using DS.WMS.Core.Fee.Entity; using DS.WMS.Core.Fee.Entity;
using DS.WMS.Core.Fee.Interface; using DS.WMS.Core.Fee.Interface;
using DS.WMS.Core.Fee.Method.ReportProviders;
using DS.WMS.Core.Op.Entity; using DS.WMS.Core.Op.Entity;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
@ -204,12 +205,16 @@ namespace DS.WMS.FeeApi.Controllers
/// <param name="model">费用记录ID</param> /// <param name="model">费用记录ID</param>
/// <returns></returns> /// <returns></returns>
[HttpPost, Route("GetPrintInfo")] [HttpPost, Route("GetPrintInfo")]
public async Task<DataResult<CostAccountingForm>> GetPrintInfoAsync(IdModel model) public async Task<DataResult<dynamic>> GetPrintInfoAsync(IdModel model)
{ {
if (model == null || model.Ids?.Length == 0) if (model == null || model.Ids?.Length == 0)
return DataResult<CostAccountingForm>.Failed("参数无效", MultiLanguageConst.IllegalRequest); return DataResult<dynamic>.Failed("参数无效", MultiLanguageConst.IllegalRequest);
return await _feeService.GetPrintInfoAsync((BusinessType)model.BusinessType.Value, model.Ids); string providerName = model.Value?.ToString();
if (string.IsNullOrEmpty(providerName))
providerName = typeof(CostAccountingReport).AssemblyQualifiedName;
return await _feeService.GetPrintInfoAsync(providerName, (BusinessType)model.BusinessType.Value, model.Ids);
} }
/// <summary> /// <summary>

Loading…
Cancel
Save