Forráskód Böngészése

Merge branch 'fixed/task' into test

xf 1 hete
szülő
commit
d8c82c5e9c

+ 5 - 7
src/Hotline.Application/Jobs/ApptaskJob.cs

@@ -4,10 +4,9 @@ using Quartz;
 using Hotline.Share.Enums.BatchTask;
 using Microsoft.Extensions.DependencyInjection;
 using Hotline.EventBus;
-using Hotline.Share.Dtos.Order.OrderVisit;
-using Hotline.Share.Dtos.Order.OrderDelay;
 using Hotline.Application.OrderApp.OrderDelayApp;
 using Hotline.Application.OrderApp.OrderVisitApp;
+using Microsoft.AspNetCore.Http;
 
 namespace Hotline.Application.Jobs
 {
@@ -32,6 +31,8 @@ namespace Hotline.Application.Jobs
             //Console.WriteLine($"执行ApptaskJob: {DateTime.Now}");
             var task = await _apptaskDomainService.GetWaitingTaskAsync(context.CancellationToken);
             if (task is null) return;
+            var httpContextAccessor = _serviceProvider.GetRequiredService<IHttpContextAccessor>();
+            httpContextAccessor.HttpContext ??= new DefaultHttpContext();
             ApptaskExecuteResult? result = null;
             switch (task.TaskType)
             {
@@ -59,7 +60,7 @@ namespace Hotline.Application.Jobs
                     //todo check if task is all complete
                     //pub all complete
                     var isCompleted = await _apptaskDomainService.IsCompletedAsync(task.ApptaskId, context.CancellationToken);
-                    if (isCompleted) 
+                    if (isCompleted)
                         await _publisher.PublishAsync(new ApptaskCompletedNotify(task), PublishStrategy.Async, context.CancellationToken);
                 }
                 else
@@ -67,7 +68,6 @@ namespace Hotline.Application.Jobs
                     //todo pub single complete fail
                     await _publisher.PublishAsync(new ApptaskFailNotify(task), PublishStrategy.Async, context.CancellationToken);
                 }
-
             }
         }
 
@@ -76,7 +76,5 @@ namespace Hotline.Application.Jobs
         {
             GC.SuppressFinalize(this);
         }
-
-
     }
-}
+}

+ 1 - 1
src/Hotline.Application/OrderApp/OrderDelayApp/OrderDelayApplication.cs

@@ -189,7 +189,7 @@ public class OrderDelayApplication : IOrderDelayApplication, IScopeDependency
         var apptaskItems = new List<AddApptaskItemRequest>();
         var req = new OrderDelayReviewWithSessionRequest
         {
-            SessionContext = _sessionContext,
+            SessionContext = (FakeSessionContext)_sessionContext,
             IsPass = request.IsPass,
             NextWorkflow = request.NextWorkflow
         };

+ 2 - 2
src/Hotline.Application/OrderApp/OrderDelayApp/OrderDelayReviewTaskExecutor.cs

@@ -5,7 +5,7 @@ using XF.Domain.Dependency;
 
 namespace Hotline.Application.OrderApp.OrderDelayApp;
 
-public class OrderDelayReviewTaskExecutor : IApptaskExecutor<OrderDelayReviewRequest>, IScopeDependency
+public class OrderDelayReviewTaskExecutor : IApptaskExecutor<OrderDelayReviewWithSessionRequest>, IScopeDependency
 {
     private readonly IOrderDelayApplication _orderDelayApplication;
 
@@ -20,7 +20,7 @@ public class OrderDelayReviewTaskExecutor : IApptaskExecutor<OrderDelayReviewReq
     /// <param name="request"></param>
     /// <param name="cancellation"></param>
     /// <returns>是否成功执行</returns>
-    public async Task<ApptaskExecuteResult> ExecuteAsync(OrderDelayReviewRequest? request, CancellationToken cancellation)
+    public async Task<ApptaskExecuteResult> ExecuteAsync(OrderDelayReviewWithSessionRequest? request, CancellationToken cancellation)
     {
         if (request == null)
             return ApptaskExecuteResult.Fail("请求参数为空");

+ 2 - 7
src/Hotline.Application/OrderApp/OrderDelayApp/OrderDelayReviewWithSessionRequest.cs

@@ -1,16 +1,11 @@
 using Hotline.Share.Dtos.Order.OrderDelay;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
 using Hotline.BatchTask;
-using XF.Domain.Authentications;
+using Hotline.Authentications;
 
 namespace Hotline.Application.OrderApp.OrderDelayApp
 {
     public class OrderDelayReviewWithSessionRequest : OrderDelayReviewRequest, IApptaskRequest
     {
-        public ISessionContext SessionContext { get; set; }
+        public FakeSessionContext SessionContext { get; set; }
     }
 }

+ 2 - 2
src/Hotline.Application/OrderApp/OrderVisitApp/VoiceVisitTaskExecutor.cs

@@ -11,7 +11,7 @@ using Hotline.Share.Dtos.Order.OrderVisit;
 
 namespace Hotline.Application.OrderApp.OrderVisitApp
 {
-    public class VoiceVisitTaskExecutor : IApptaskExecutor<VoiceVisitRequest>, IScopeDependency
+    public class VoiceVisitTaskExecutor : IApptaskExecutor<VoiceVisitWithSessionRequest>, IScopeDependency
     {
         private readonly IHttpClientFactory _httpClientFactory;
         private readonly IOptionsSnapshot<CallCenterConfiguration> _callcenterOptions;
@@ -30,7 +30,7 @@ namespace Hotline.Application.OrderApp.OrderVisitApp
         /// <param name="request"></param>
         /// <param name="cancellation"></param>
         /// <returns>是否成功执行</returns>
-        public async Task<ApptaskExecuteResult> ExecuteAsync(VoiceVisitRequest? request, CancellationToken cancellation)
+        public async Task<ApptaskExecuteResult> ExecuteAsync(VoiceVisitWithSessionRequest? request, CancellationToken cancellation)
         {
             Console.WriteLine($"执行vv: {DateTime.Now}");
             if (request == null)

+ 2 - 1
src/Hotline.Application/OrderApp/OrderVisitApp/VoiceVisitWithSessionRequest.cs

@@ -6,11 +6,12 @@ using System.Text;
 using System.Threading.Tasks;
 using Hotline.BatchTask;
 using XF.Domain.Authentications;
+using Hotline.Authentications;
 
 namespace Hotline.Application.OrderApp.OrderVisitApp
 {
     public class VoiceVisitWithSessionRequest : VoiceVisitRequest, IApptaskRequest
     {
-        public ISessionContext SessionContext { get; set; }
+        public FakeSessionContext SessionContext { get; set; }
     }
 }

+ 0 - 15
src/Hotline/Authentications/FakeSessionContext.cs

@@ -50,20 +50,5 @@ namespace Hotline.Authentications
         /// 例如: 微信的OpenId
         /// </summary>
         public string? OpenId { get; init; }
-
-        public void ChangeSession(string id)
-        {
-            throw new NotImplementedException();
-        }
-
-        public async Task ChangeSessionAsync(string userId, CancellationToken cancellation)
-        {
-            throw new NotImplementedException();
-        }
-
-        public void ChangeSession(string userId, string username, string orgId, string orgname, int orgLevel)
-        {
-            throw new NotImplementedException();
-        }
     }
 }

+ 56 - 19
src/Hotline/Authentications/SessionContextManager.cs

@@ -22,6 +22,8 @@ public interface ISessionContextManager
     /// 依据source创建对应Session
     /// </summary>
     void ChangeSessionContext(string source);
+
+    void ChangeSessionContext(ISessionContext sessionContext);
 }
 
 public class SessionContextManager : ISessionContextManager, IScopeDependency
@@ -49,22 +51,32 @@ public class SessionContextManager : ISessionContextManager, IScopeDependency
             .Includes(d => d.Roles)
             .FirstAsync(d => d.Id == userId, cancellation);
 
-        List<Claim> userClaims =
-        [
-            new(JwtClaimTypes.Subject, account.Id),
-            new(JwtClaimTypes.PhoneNumber, account.PhoneNo ?? string.Empty),
-            new(ClaimTypes.NameIdentifier, account.Id),
-            new(AppClaimTypes.UserDisplayName, account.Name),
-            new(AppClaimTypes.DepartmentId, account.User?.OrgId ?? string.Empty),
-            new(AppClaimTypes.DepartmentIsCenter, account.User?.Organization?.IsCenter.ToString() ?? string.Empty),
-            new(AppClaimTypes.DepartmentName, account.User?.Organization?.Name ?? string.Empty),
-            new(AppClaimTypes.DepartmentAreaCode, account.User?.Organization?.AreaCode ?? string.Empty),
-            new(AppClaimTypes.DepartmentAreaName, account.User?.Organization?.AreaName ?? string.Empty),
-            new(AppClaimTypes.DepartmentLevel, account.User?.Organization?.Level.ToString() ?? string.Empty),
-            new(AppClaimTypes.AreaId, account.User?.OrgId?.GetHigherOrgId() ?? string.Empty),
-        ];
-        userClaims.AddRange(account.Roles.Select(d => new Claim(JwtClaimTypes.Role, d.Name)));
-        httpContextAccessor.HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity(userClaims));
+        ChangeSession(account.Id, account.Name,
+            account.User?.OrgId, account.User?.Organization?.Name,
+            account.User?.Organization?.Level,
+            account.User?.Organization?.IsCenter,
+            account.PhoneNo,
+            account.User?.Organization?.AreaCode,
+            account.User?.Organization?.AreaName,
+            account.Roles.Select(d=>d.Name).ToList()
+        );
+        //
+        // List<Claim> userClaims =
+        // [
+        //     new(JwtClaimTypes.Subject, account.Id),
+        //     new(JwtClaimTypes.PhoneNumber, account.PhoneNo ?? string.Empty),
+        //     new(ClaimTypes.NameIdentifier, account.Id),
+        //     new(AppClaimTypes.UserDisplayName, account.Name),
+        //     new(AppClaimTypes.DepartmentId, account.User?.OrgId ?? string.Empty),
+        //     new(AppClaimTypes.DepartmentIsCenter, account.User?.Organization?.IsCenter.ToString() ?? string.Empty),
+        //     new(AppClaimTypes.DepartmentName, account.User?.Organization?.Name ?? string.Empty),
+        //     new(AppClaimTypes.DepartmentAreaCode, account.User?.Organization?.AreaCode ?? string.Empty),
+        //     new(AppClaimTypes.DepartmentAreaName, account.User?.Organization?.AreaName ?? string.Empty),
+        //     new(AppClaimTypes.DepartmentLevel, account.User?.Organization?.Level.ToString() ?? string.Empty),
+        //     new(AppClaimTypes.AreaId, account.User?.OrgId?.GetHigherOrgId() ?? string.Empty),
+        // ];
+        // userClaims.AddRange(account.Roles.Select(d => new Claim(JwtClaimTypes.Role, d.Name)));
+        // httpContextAccessor.HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity(userClaims));
     }
 
     /// <summary>
@@ -86,9 +98,27 @@ public class SessionContextManager : ISessionContextManager, IScopeDependency
         ChangeSession(config.UserId, config.UserName, config.OrgId, config.OrgName, config.OrgId.CalcOrgLevel());
     }
 
+    public void ChangeSessionContext(ISessionContext sessionContext)
+    {
+        ChangeSession(sessionContext.UserId, sessionContext.UserName,
+            sessionContext.OrgId, sessionContext.OrgName,
+            sessionContext.OrgLevel, sessionContext.OrgIsCenter,
+            sessionContext.Phone,
+            sessionContext.OrgAreaCode, sessionContext.OrgAreaName,
+            sessionContext.Roles.ToList());
+    }
+
     #region private
 
-    private void ChangeSession(string userId, string username, string orgId, string orgname, int orgLevel)
+    private void ChangeSession(
+        string userId, string username,
+        string orgId, string orgname,
+        int? orgLevel, 
+        bool? isCenter = null,
+        string? phoneNo = null,
+        string? orgAreaCode = null,
+        string? orgAreaName = null,
+        List<string>? roles = null)
     {
         var httpContextAccessor = _serviceProvider.GetRequiredService<IHttpContextAccessor>();
         if (httpContextAccessor.HttpContext == null)
@@ -99,12 +129,19 @@ public class SessionContextManager : ISessionContextManager, IScopeDependency
             new(JwtClaimTypes.Subject, userId),
             new(ClaimTypes.NameIdentifier, userId),
             new(AppClaimTypes.UserDisplayName, username),
+            new(JwtClaimTypes.PhoneNumber, phoneNo ?? string.Empty),
             new(AppClaimTypes.DepartmentId, orgId ?? string.Empty),
-            new(AppClaimTypes.DepartmentIsCenter, orgId?.IsCenter().ToString() ?? string.Empty),
             new(AppClaimTypes.DepartmentName, orgname ?? string.Empty),
-            new(AppClaimTypes.DepartmentLevel, orgLevel.ToString() ?? string.Empty),
+            new(AppClaimTypes.DepartmentIsCenter, isCenter.HasValue 
+                ? isCenter.Value.ToString() 
+                : (orgId?.IsCenter().ToString() ?? string.Empty)),
+            new(AppClaimTypes.DepartmentAreaCode, orgAreaCode ?? string.Empty),
+            new(AppClaimTypes.DepartmentAreaName, orgAreaName ?? string.Empty),
+            new(AppClaimTypes.DepartmentLevel, orgLevel?.ToString() ?? string.Empty),
             new(AppClaimTypes.AreaId, orgId?.GetHigherOrgId() ?? string.Empty),
         ];
+        if (roles != null && roles.Count > 0)
+            userClaims.AddRange(roles.Select(d => new Claim(JwtClaimTypes.Role, d)));
         httpContextAccessor.HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity(userClaims));
     }
 

+ 4 - 2
src/Hotline/Authentications/SessionContextProvider.cs

@@ -84,7 +84,7 @@ public class SessionContextProvider : ISessionContextProvider, IScopeDependency
         httpContext.User = new ClaimsPrincipal(new ClaimsIdentity(userClaims));
     }
 
-    public void ChangeSession(string userId, string username, string orgId, string orgname, int orgLevel, string orgAreaCode, string orgAreaName)
+    public void ChangeSession(string userId, string username, string orgId, string orgname, int orgLevel, string orgAreaCode, string orgAreaName, string[] roles)
     {
         var httpContext = _serviceProvider.GetRequiredService<IHttpContextAccessor>().HttpContext;
         httpContext ??= new DefaultHttpContext();
@@ -102,6 +102,7 @@ public class SessionContextProvider : ISessionContextProvider, IScopeDependency
             new(AppClaimTypes.DepartmentLevel, orgLevel.ToString() ?? string.Empty),
             new(AppClaimTypes.AreaId, orgId?.GetHigherOrgId() ?? string.Empty),
         ];
+        userClaims.AddRange(roles.Select(d => new Claim(JwtClaimTypes.Role, d)));
         httpContext.User = new ClaimsPrincipal(new ClaimsIdentity(userClaims));
     }
 
@@ -113,6 +114,7 @@ public class SessionContextProvider : ISessionContextProvider, IScopeDependency
             sessionContext.OrgName,
             sessionContext.OrgLevel,
             sessionContext.OrgAreaCode,
-            sessionContext.OrgAreaName
+            sessionContext.OrgAreaName,
+            sessionContext.Roles
         );
 }

+ 10 - 4
src/Hotline/BatchTask/ApptaskDomainService.cs

@@ -1,8 +1,10 @@
 using FluentValidation;
+using Hotline.Authentications;
 using Hotline.Share.Dtos.BatchTask;
 using Hotline.Share.Enums.BatchTask;
 using Hotline.Validators.BatchTask;
 using MapsterMapper;
+using Microsoft.AspNetCore.Http;
 using Microsoft.Extensions.Logging;
 using XF.Domain.Authentications;
 using XF.Domain.Dependency;
@@ -15,20 +17,20 @@ public class ApptaskDomainService : IApptaskDomainService, IScopeDependency
 {
     private readonly IRepository<Apptask> _apptaskRepository;
     private readonly IRepository<ApptaskItem> _apptaskItemRepository;
-    private readonly ISessionContextProvider _sessionContextProvider;
+    private readonly ISessionContextManager _sessionContextManager;
     private readonly IMapper _mapper;
     private readonly ILogger<ApptaskDomainService> _logger;
 
     public ApptaskDomainService(
         IRepository<Apptask> apptaskRepository,
         IRepository<ApptaskItem> apptaskItemRepository,
-        ISessionContextProvider sessionContextProvider,
+        ISessionContextManager sessionContextManager,
         IMapper mapper,
         ILogger<ApptaskDomainService> logger)
     {
         _apptaskRepository = apptaskRepository;
         _apptaskItemRepository = apptaskItemRepository;
-        _sessionContextProvider = sessionContextProvider;
+        _sessionContextManager = sessionContextManager;
         _mapper = mapper;
         _logger = logger;
     }
@@ -175,7 +177,11 @@ public class ApptaskDomainService : IApptaskDomainService, IScopeDependency
             var request = System.Text.Json.JsonSerializer.Deserialize<TRequest>(apptaskItem.TaskParams);
             if (request is null)
                 throw new UserFriendlyException($"任务参数反序列化失败, taskItemId: {apptaskItem.Id}");
-            _sessionContextProvider.ChangeSession(request.SessionContext);
+
+            _sessionContextManager.ChangeSessionContext(request.SessionContext);
+            
+            //if (request is IApptaskRequest reqWithSession)
+            //    _sessionContextProvider.ChangeSession(reqWithSession.SessionContext);
             var result = await executor.ExecuteAsync(request, cancellation);
             apptaskItem.TaskStatus = result.IsSuccess ? ETaskStatus.Succeeded : ETaskStatus.Failed;
             apptaskItem.Message = result.Message;

+ 2 - 1
src/Hotline/BatchTask/IApptaskRequest.cs

@@ -3,12 +3,13 @@ using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
+using Hotline.Authentications;
 using XF.Domain.Authentications;
 
 namespace Hotline.BatchTask
 {
     public interface IApptaskRequest
     {
-        public ISessionContext SessionContext { get; set; }
+        public FakeSessionContext SessionContext { get; set; }
     }
 }

+ 1 - 1
src/XF.Domain/Authentications/ISessionContextProvider.cs

@@ -15,7 +15,7 @@ namespace XF.Domain.Authentications
 
         HttpContext ChangeSessionByUserId(string id, HttpContext httpContext);
         Task ChangeSessionByUserIdAsync(string userId, CancellationToken cancellation);
-        void ChangeSession(string userId, string username, string orgId, string orgname, int orgLevel, string orgAreaCode, string orgAreaName);
+        void ChangeSession(string userId, string username, string orgId, string orgname, int orgLevel, string orgAreaCode, string orgAreaName, string[] roles);
         void ChangeSession(ISessionContext sessionContext);
     }
 }

+ 5 - 0
test/Hotline.Tests/Controller/TestSessionContextManager.cs

@@ -85,6 +85,11 @@ public class TestSessionContextManager : ISessionContextManager, IScopeDependenc
         ChangeSession(config.UserId, config.UserName, config.OrgId, config.OrgName, config.OrgId.CalcOrgLevel());
     }
 
+    public void ChangeSessionContext(ISessionContext sessionContext)
+    {
+        throw new NotImplementedException();
+    }
+
     #region private
 
     private void ChangeSession(string userId, string username, string orgId, string orgname, int orgLevel)