Browse Source

推送数据到天阙

qinchaoyue 4 months ago
parent
commit
eb7551be0b

+ 14 - 1
src/Hotline.Application.Tests/Application/SnapshotApplicationTest.cs

@@ -38,8 +38,9 @@ public class SnapshotApplicationTest : TestBase
     private readonly IOrderRepository _orderRepository;
     private readonly IOrderSnapshotRepository _orderSnapshotRepository;
     private readonly ISessionContext _sessionContext;
+    private readonly IGuiderSystemService _guiderSystemService;
 
-    public SnapshotApplicationTest(IAccountRepository accountRepository, IRepository<Role> roleRepository, UserController userController, IServiceScopeFactory scopeFactory, IRepository<User> userRepository, IHttpContextAccessor httpContextAccessor, ISnapshotApplication snapshotApplication, IIdentityAppService identityAppService, IRepository<RedPackRecord> redPackRecordRepository, IIndustryApplication industryApplication, IIndustryRepository industryRepository, IFileRepository fileRepository, OrderServiceMock orderServiceMock, IOrderRepository orderRepository, IOrderSnapshotRepository orderSnapshotRepository, IThirdIdentiyService thirdService, IThirdAccountRepository thirdAccount, ISessionContext sessionContext) : base(accountRepository, roleRepository, userController, scopeFactory, userRepository, httpContextAccessor, thirdService, thirdAccount)
+    public SnapshotApplicationTest(IAccountRepository accountRepository, IRepository<Role> roleRepository, UserController userController, IServiceScopeFactory scopeFactory, IRepository<User> userRepository, IHttpContextAccessor httpContextAccessor, ISnapshotApplication snapshotApplication, IIdentityAppService identityAppService, IRepository<RedPackRecord> redPackRecordRepository, IIndustryApplication industryApplication, IIndustryRepository industryRepository, IFileRepository fileRepository, OrderServiceMock orderServiceMock, IOrderRepository orderRepository, IOrderSnapshotRepository orderSnapshotRepository, IThirdIdentiyService thirdService, IThirdAccountRepository thirdAccount, ISessionContext sessionContext, IGuiderSystemService guiderSystemService) : base(accountRepository, roleRepository, userController, scopeFactory, userRepository, httpContextAccessor, thirdService, thirdAccount)
     {
         _snapshotApplication = snapshotApplication;
         _identityAppService = identityAppService;
@@ -52,6 +53,7 @@ public class SnapshotApplicationTest : TestBase
         _orderSnapshotRepository = orderSnapshotRepository;
         SetWeiXin();
         _sessionContext = sessionContext;
+        _guiderSystemService = guiderSystemService;
     }
 
     [Fact]
@@ -262,6 +264,17 @@ public class SnapshotApplicationTest : TestBase
         third.InvitationCode.ShouldBe(code);
     }
 
+    [Fact]
+    public async Task PostOrder_Test()
+    {
+        var orderSnapshot = await _orderSnapshotRepository.Queryable()
+            .OrderByDescending(m => m.CreationTime).FirstAsync();
+        var order = await _orderRepository.GetAsync(orderSnapshot.Id);
+        var token = new ThirdTokenDto { AppId = "TAjYAYuA", Secret = "c01eb299b9d784bf55681af4da86bab6ba428101" };
+        var result = await _guiderSystemService.PostOrder(order, orderSnapshot, token);
+        result.ShouldNotBeNull();
+    }
+
     [Fact]
     public async Task GetPractitionerItems_Test()
     {

+ 5 - 5
src/Hotline.Application.Tests/Infrastructure/TianQueTest.cs

@@ -24,13 +24,13 @@ public class TianQueTest
     public async Task PostAcceptInfo_Test()
     {
         // Arrange
-        var tiqnQueService = new TiqnQueService();
+        //var tiqnQueService = new TiqnQueService();
 
-        // Act
-        var result = await tiqnQueService.PostAcceptInfo();
+        //// Act
+        //var result = await tiqnQueService.PostAcceptInfo();
 
-        // Assert
-        Assert.Equal("ok", result);
+        //// Assert
+        //Assert.Equal("ok", result);
     }
 
 }

+ 3 - 0
src/Hotline.Application.Tests/Startup.cs

@@ -59,6 +59,8 @@ using Hotline.Application.Tests.SqlSuger;
 using Microsoft.AspNetCore.Http;
 using Hotline.WeChat;
 using Hotline.Api.Controllers.Snapshot;
+using Hotline.Snapshot.Interfaces;
+using TianQue.Sdk;
 
 namespace Hotline.Application.Tests;
 public class Startup
@@ -181,6 +183,7 @@ public class Startup
             services.AddScoped<KnowledgeServiceMock>();
             services.AddScoped<XingTangCallsSyncJob>();
             services.AddXingTangDb(callCenterConfiguration.XingTang);
+            services.AddScoped<IGuiderSystemService, TiqnQueService>();
             //ServiceLocator.Instance = services.BuildServiceProvider();
         }
 

+ 4 - 4
src/Hotline.Share/Enums/Snapshot/EReadPackUserType.cs

@@ -3,8 +3,8 @@ namespace Hotline.Share.Enums.Snapshot;
 
 /// <summary>
 /// 红包领取人类型;
-/// 0: 市民;
-/// 1: 网格员;
+/// 1: 市民;
+/// 2: 网格员;
 /// </summary>
 public enum EReadPackUserType
 {
@@ -12,11 +12,11 @@ public enum EReadPackUserType
     /// 市民
     /// </summary>
     [Description("市民")]
-    Citizen = 0,
+    Citizen = 1,
 
     /// <summary>
     /// 网络员
     /// </summary>
     [Description("网络员")]
-    Guider = 1
+    Guider = 2
 }

+ 2 - 1
src/Hotline/Snapshot/Interfaces/IGuiderSystemService.cs

@@ -1,4 +1,5 @@
 using Hotline.Orders;
+using Hotline.Share.Dtos.Snapshot;
 using System;
 using System.Collections.Generic;
 using System.Linq;
@@ -12,6 +13,6 @@ namespace Hotline.Snapshot.Interfaces;
 /// </summary>
 public interface IGuiderSystemService
 {
-   Task<string> PostOrder(Order order, OrderSnapshot orderSnapshot);
+   Task<string> PostOrder(Order order, OrderSnapshot orderSnapshot, ThirdTokenDto tokenDto);
 }
 

+ 31 - 0
src/TianQue.Sdk/Models/ApiReponse.cs

@@ -0,0 +1,31 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace TianQue.Sdk.Models;
+public class ApiReponse<T>
+{
+    // {"code":400,"success":false,"data":{},"msg":"detailContent:不能为空"}
+
+    /// <summary>
+    /// Code
+    /// </summary>
+    public int Code { get; set; }
+
+    /// <summary>
+    /// 是否成功
+    /// </summary>
+    public bool Success { get; set; }
+
+    /// <summary>
+    /// 数据
+    /// </summary>
+    public T Data { get; set; }
+
+    /// <summary>
+    /// 信息
+    /// </summary>
+    public string Msg { get; set; }
+}

+ 109 - 0
src/TianQue.Sdk/TQHttpClient.cs

@@ -0,0 +1,109 @@
+using Hotline.Share.Dtos.Snapshot;
+using Hotline.Share.Tools;
+using Microsoft.Extensions.Logging;
+using Newtonsoft.Json;
+using Newtonsoft.Json.Serialization;
+using Renci.SshNet;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net.Http.Headers;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace TianQue.Sdk;
+public class TQHttpClient
+{
+    private readonly string AppSecret;
+    private readonly string AppKey;
+
+    /// <summary>
+    /// ssh服务器ip
+    /// </summary>
+    private readonly string SSHHost;
+
+    /// <summary>
+    /// ssh服务器端口
+    /// </summary>
+    private readonly int SSHPort;
+
+    /// <summary>
+    /// ssh账号
+    /// </summary>
+    private readonly string SSHUserName;
+
+    /// <summary>
+    /// ssh密码
+    /// </summary>
+    private readonly string SSHPassword;
+
+    private readonly SshClient _sshClient;
+
+    private readonly ILogger<TQHttpClient> _logger;
+
+    public TQHttpClient(string appSecret, string appKey, ILogger<TQHttpClient> logger)
+    {
+        AppSecret = appSecret;
+        AppKey = appKey;
+        _logger = logger;
+    }
+
+    public TQHttpClient(string appSecret, string appKey, string sshHost, int sshPort, string sshUserName, string sshPassword, ILogger<TQHttpClient> logger)
+    {
+        AppSecret = appSecret;
+        AppKey = appKey;
+        SSHHost = sshHost;
+        SSHPort = sshPort;
+        SSHUserName = sshUserName;
+        SSHPassword = sshPassword;
+        _logger = logger;
+        _sshClient = new SshClient(SSHHost, SSHPort, SSHUserName, SSHPassword);
+    }
+
+    public async Task<T> PostAsync<T>(Uri uri, object data)
+    {
+        try
+        {
+            var headers = new Dictionary<string, object> { { "_timeStamp", DateTime.Now.ToUnixTimeMilliseconds() }, { "_nonce", SignUtils.GenerateNonce() } };
+            var sortedDic = new SortedDictionary<string, object>(data.ToDictionary());
+            var body = sortedDic.ToJson(new JsonSerializerSettings {ContractResolver = new CamelCasePropertyNamesContractResolver()});
+            var postJsonSign = SignUtils.Sign(AppSecret, headers, body);
+            headers.Add("_sign", postJsonSign);
+            headers.Add("_appKey", AppKey);
+
+            if (SSHHost.NotNullOrEmpty() && SSHPort != 0 && SSHUserName.NotNullOrEmpty() && SSHPassword.NotNullOrEmpty())
+            {
+                _sshClient.Connect();
+                var forwardedPort = new ForwardedPortLocal("127.0.0.1", 8090, uri.Host, (uint)uri.Port);
+                _sshClient.AddForwardedPort(forwardedPort);
+                forwardedPort.Start();
+                uri = new Uri("http://127.0.0.1:8090" + uri.AbsolutePath);
+            }
+            // var url = "http://127.0.0.1:8090/api/v1/test/accept/saveAcceptInfoApi";
+
+            var content = new StringContent(body, Encoding.GetEncoding("UTF-8"));
+            content.Headers.ContentType = new MediaTypeHeaderValue("application/json") { CharSet = "UTF-8" };
+            foreach (var header in headers)
+            {
+                content.Headers.Add(header.Key, header.Value.ToString());
+            }
+            var resp = await (new HttpClient()).PostAsync(uri.ToString(), content);
+            resp.EnsureSuccessStatusCode();
+            var result = await resp.Content.ReadAsStringAsync();
+            _logger.LogInformation($"天阙交互; url: {uri.ToString()}, headers: {headers.ToJson()} request: {body}, response: {result}");
+            return result.FromJson<T>();
+        }
+        catch (Exception e)
+        {
+            _logger.LogError(e.Message);
+            throw;
+        }
+        finally
+        {
+            if (_sshClient.IsConnected)
+            {
+                _sshClient.Disconnect();
+            }
+        }
+    }
+}

+ 1 - 0
src/TianQue.Sdk/TianQue.Sdk.csproj

@@ -12,6 +12,7 @@
 
   <ItemGroup>
     <ProjectReference Include="..\Hotline.Share\Hotline.Share.csproj" />
+    <ProjectReference Include="..\Hotline\Hotline.csproj" />
   </ItemGroup>
 
 </Project>

+ 45 - 40
src/TianQue.Sdk/TiqnQueService.cs

@@ -1,24 +1,33 @@
-using Hotline.Share.Tools;
+using Hotline.Orders;
+using Hotline.Share.Dtos.Snapshot;
+using Hotline.Share.Tools;
+using Hotline.Snapshot;
+using Hotline.Snapshot.Interfaces;
+using Mapster;
+using Microsoft.Extensions.Logging;
 using Newtonsoft.Json;
 using Renci.SshNet;
 using System.Net.Http.Headers;
 using System.Text;
+using TianQue.Sdk.Models;
+using XF.Domain.Dependency;
 
 namespace TianQue.Sdk;
 
-public class TiqnQueService
+public class TiqnQueService : IGuiderSystemService, IScopeDependency
 {
     private readonly string appSecret = "c01eb299b9d784bf55681af4da86bab6ba428101";
     private readonly string appKey = "TAjYAYuA";
+    private readonly ILogger<TQHttpClient> _logger;
+    private readonly string _url = "http://10.0.188.11:6090/api/v1/test/accept/saveAcceptInfoApi";
 
+    public TiqnQueService(ILogger<TQHttpClient> logger)
+    {
+        _logger = logger;
+    }
 
     public async Task<string> PostAcceptInfo()
     {
-        var headers = new Dictionary<string, object>
-        {
-            { "_timeStamp", DateTime.Now.ToUnixTimeMilliseconds() },
-            { "_nonce", SignUtils.GenerateNonce() }
-        };
 
         var bodyDic = new SortedDictionary<string, object>
         {
@@ -26,42 +35,38 @@ public class TiqnQueService
             { "p1", "p1"}
         };
 
-        var body = bodyDic.ToJson(new JsonSerializerSettings {
-            StringEscapeHandling = StringEscapeHandling.Default,
-        });
-
-        var postJsonSign = SignUtils.Sign(appSecret, headers, body);
-        headers.Add("_sign", postJsonSign);
-        headers.Add("_appKey", appKey);
-
 
-        string sshHost = "171.94.154.2";
-        int sshPort = 22;
-        string sshUsername = "root";
-        string sshPassword = "ZGbyy@2024!";
-        string targetHost = "10.0.188.11";
-        uint targetPort = 6090;
-
-        // 创建 SSH 隧道
-        var sshClient = new SshClient(sshHost, sshPort, sshUsername, sshPassword);
-        sshClient.Connect();
-
-        // 创建一个转发的端口(本地端口,目标主机,目标端口)
-        var forwardedPort = new ForwardedPortLocal("127.0.0.1", 8090, targetHost,  targetPort);
-        sshClient.AddForwardedPort(forwardedPort);
-        forwardedPort.Start();
+        return "ok";
+    }
 
-        var url = "http://127.0.0.1:8090/api/v1/test/accept/saveAcceptInfoApi";
+    public async Task<string> PostOrder(Order order, OrderSnapshot orderSnapshot, ThirdTokenDto tokenDto)
+    {
+        TQHttpClient httpClient;
+#if DEBUG
+         httpClient = new TQHttpClient(appSecret, appKey, "171.94.154.2", 22, "root" , "ZGbyy@2024!", _logger);
+#else
+         httpClient = new TQHttpClient(appSecret, appKey, _logger);
+#endif
+        var acceptInfo = order.Adapt<AcceptInfo>();
+        acceptInfo.ReplyCode = order.No!; // 唯一标识
+        acceptInfo.OrgId = order.ActualHandleOrgAreaCode.NotNullOrEmpty() ? long.Parse(order.ActualHandleOrgAreaCode) : 0; // 区域Id
+        acceptInfo.DepartmentNo = order.ActualHandleOrgCode!; // 部门编码
+        acceptInfo.TypeName = order.AcceptType!; // 诉求类型名称
+        acceptInfo.OccurDate = order.CreationTime; // 事发时间
+        acceptInfo.DetailAddress = order.FullAddress!; // 详细地址
+        acceptInfo.Topic = order.Title!; // 线索主题
+        acceptInfo.DetailContent = order.Content!; // 详细内容
 
-        var content = new StringContent(body, Encoding.GetEncoding("UTF-8"));
-        content.Headers.ContentType = new MediaTypeHeaderValue("application/json") { CharSet = "UTF-8"};
-        foreach (var header in headers)
+        // 反映人信息
+        acceptInfo.PersonList = new List<PersonInfo>
         {
-            content.Headers.Add(header.Key, header.Value.ToString());
-        }
-        var resp = await (new HttpClient()).PostAsync(url,  content);
-        resp.EnsureSuccessStatusCode();
-        var result = await resp.Content.ReadAsStringAsync();
-        return result;
+            new() {
+                // ReflectCardId = // 反映人身份证号
+                ReflectPhone = order.Contact!,
+                ReflectUserName = order.FromName!,
+            } 
+        };
+        var result = await httpClient.PostAsync<ApiReponse<string>>(new Uri(_url), acceptInfo);
+        return result.ToJson();
     }
 }