diff --git a/Src/Dlhis.Canteen/Order/Controllers/OrdersController.cs b/Src/Dlhis.Canteen/Order/Controllers/OrdersController.cs index 1949cb5b..ba3482cd 100644 --- a/Src/Dlhis.Canteen/Order/Controllers/OrdersController.cs +++ b/Src/Dlhis.Canteen/Order/Controllers/OrdersController.cs @@ -1,5 +1,4 @@ -using Dlhis.Canteen.Dishes.Request; -using Dlhis.Canteen.Order.Request; +using Dlhis.Canteen.Order.Request; using Dlhis.Canteen.Order.Response; using Dlhis.Canteen.Order.Services; using Kurisu.AspNetCore.DataAccess.Dto; @@ -35,8 +34,7 @@ public class OrdersController : ControllerBase [IgnoreTenant] public async Task> AddAsync(OrderAddRequest request) { - var result = await _orderService.AddAsync(request); - return result.Response; + return await _orderService.AddAsync(request); } /// @@ -49,8 +47,7 @@ public class OrdersController : ControllerBase [IgnoreTenant] public async Task> DeviceConsume(OrderAddRequest request) { - var result = await _orderService.AddAsync(request); - return result.Response; + return await _orderService.AddAsync(request); } /// diff --git a/Src/Dlhis.Canteen/Order/Repository/Implements/BalanceRepository.cs b/Src/Dlhis.Canteen/Order/Repository/Implements/BalanceRepository.cs index 5de3e2f9..f1d60d9e 100644 --- a/Src/Dlhis.Canteen/Order/Repository/Implements/BalanceRepository.cs +++ b/Src/Dlhis.Canteen/Order/Repository/Implements/BalanceRepository.cs @@ -16,15 +16,18 @@ public class BalanceRepository : IBalanceRepository public async Task GetBalanceAsync(string userCode, string factory) { - var factories = await GetWalletFactoriesAsync(factory); - - return await _dbContext.Queryable() + var queryable = _dbContext.Queryable() .Where(x => x.UserCode == userCode && x.Status == BalanceRecordStatusEnumType.Valid) - .Where(x => factories.Contains(x.TenantId)) - .Where(x => x.Source != BalanceRecordSourceEnumType.EMealVoucher) - .SumAsync(x => x.Amount); - } + .Where(x => x.Source != BalanceRecordSourceEnumType.EMealVoucher); + if (!factory.IsPresent()) + { + return await queryable.SumAsync(x => x.Amount); + } + + var factories = await GetWalletFactoriesAsync(factory); + return await queryable.Where(x => factories.Contains(x.TenantId)).SumAsync(x => x.Amount); + } public async Task> GetBalanceRecordsAsync(string userCode, string factory, DateTime startTime, DateTime endTime) { diff --git a/Src/Dlhis.Canteen/Order/Response/OrderResultResponse.cs b/Src/Dlhis.Canteen/Order/Response/OrderResultResponse.cs index d564e96b..a1472e19 100644 --- a/Src/Dlhis.Canteen/Order/Response/OrderResultResponse.cs +++ b/Src/Dlhis.Canteen/Order/Response/OrderResultResponse.cs @@ -32,4 +32,13 @@ public class OrderResultResponse /// 余额 /// public string Balance => CurrentBalance.ToString("f2"); -} + + + [JsonIgnore] + public decimal CurrentTotalBalance { get; set; } + + /// + /// 总余额 + /// + public string TotalBalance => CurrentTotalBalance.ToString("f2"); +} \ No newline at end of file diff --git a/Src/Dlhis.Canteen/Order/Services/IOrderService.cs b/Src/Dlhis.Canteen/Order/Services/IOrderService.cs index a956a361..a738db3f 100644 --- a/Src/Dlhis.Canteen/Order/Services/IOrderService.cs +++ b/Src/Dlhis.Canteen/Order/Services/IOrderService.cs @@ -1,19 +1,20 @@ using Dlhis.Canteen.Order.Request; using Dlhis.Canteen.Order.Response; using Kurisu.AspNetCore.DataAccess.Dto; +using Kurisu.AspNetCore.UnifyResultAndValidation; namespace Dlhis.Canteen.Order.Services; public interface IOrderService : IScopeDependency { - Task AddAsync(OrderAddRequest request); + Task> AddAsync(OrderAddRequest request); /// /// 设备消费 /// /// /// - Task DeviceConsume(OrderAddRequest request); + Task> DeviceConsume(OrderAddRequest request); Task> GetOrdersAggregationAsync(PageDto page); } \ No newline at end of file diff --git a/Src/Dlhis.Canteen/Order/Services/Implements/OrderService.cs b/Src/Dlhis.Canteen/Order/Services/Implements/OrderService.cs index 22c6c78d..ff0362d8 100644 --- a/Src/Dlhis.Canteen/Order/Services/Implements/OrderService.cs +++ b/Src/Dlhis.Canteen/Order/Services/Implements/OrderService.cs @@ -57,7 +57,7 @@ public class OrderService : IOrderService /// /// /// - public async Task DeviceConsume(OrderAddRequest request) + public async Task> DeviceConsume(OrderAddRequest request) { return await AddAsync(request); } @@ -67,7 +67,7 @@ public class OrderService : IOrderService /// /// /// - public async Task AddAsync(OrderAddRequest request) + public async Task> AddAsync(OrderAddRequest request) { await SetDeviceIpInfoAsync(request.DeviceUniqueNo); @@ -75,10 +75,7 @@ public class OrderService : IOrderService handler.Acquired.ThrowIfFalse("请勿频繁消费"); var gainfo = await GetUserAsync(request); - return new OrderResultResponseWithLogs - { - Response = await ToDoAsync(request, gainfo) - }; + return await ToDoAsync(request, gainfo); } @@ -256,7 +253,7 @@ public class OrderService : IOrderService /// /// /// - private async Task HandleOfflineAsync(ConsumeRequest request, GainfoEntity gainfo) + private async Task OfflineHandleAsync(ConsumeRequest request, GainfoEntity gainfo) { var bindingInfo = await _dbContext.Queryable() .LeftJoin((x, b) => x.BusinessPlaceCode == b.Code) @@ -273,11 +270,13 @@ public class OrderService : IOrderService var shifts = await _dbContext.Queryable() .Where(x => x.ShiftCode == bindingInfo.ShiftCode).ToListAsync(); - var shift = shifts.FirstOrDefault(x => new TimePeriod - { - Start = x.Start, - End = x.End - }.IsPresent(request.CostDateTime)); + var shift = shifts.FirstOrDefault(x => + new TimePeriod + { + Start = x.Start, + End = x.End + }.IsPresent(request.CostDateTime) + ); var costDate = await _canteenSettingService.GetCostDateAsync(bindingInfo.Factory, request.CostDateTime); @@ -317,7 +316,7 @@ public class OrderService : IOrderService TenantId = bindingInfo.Factory, }; - await _dbContext.InsertReturnIdentityAsync(order); + await _dbContext.InsertAsync(order); var balanceRecord = order.Adapt(); await _dbContext.InsertAsync(balanceRecord); } @@ -391,16 +390,36 @@ public class OrderService : IOrderService //获取餐券余额 var data = await _dbContext.Queryable() .LeftJoin((x, d) => x.No == d.No) - .LeftJoin((x, d, u) => u.IdNo == d.IdNo) .Where((x, d) => x.No == no && d.IdNo == idNo) - .Select((x, d, u) => new OrderResultResponse + .Select((x, d) => new OrderResultResponse { - UserCode = u.Code, - UserName = u.Name, + UserCode = d.IdNo, + UserName = d.Name, CurrentBalance = d.Balance }) .SingleAsync(); + try + { + var v = data.UserCode ?? string.Empty; + var vc = v.ToCharArray().Reverse().ToList(); + + for (int i = 0; i < vc.Count; i++) + { + if (i + 1 > 4) + { + vc[i] = '*'; + } + } + + vc.Reverse(); + data.UserCode = string.Join("", vc); + } + catch (Exception e) + { + //ignore + } + return new DefaultApiResult { Code = msg.IsPresent() ? ApiStateCode.Error : ApiStateCode.Success, @@ -409,6 +428,30 @@ public class OrderService : IOrderService }; } + + private async Task OfflineConsumeAsync(OrderAddRequest request, GainfoEntity gainfo) + { + try + { + if (request.ThirdNo.IsPresent() && await ToCheckAbleOfflineConsumeAsync(request.ThirdNo)) + { + await using var handler = await _redisCache.LockAsync($"consume:device-offline:{request.ThirdNo}"); + if (handler.Acquired) + { + await OfflineHandleAsync(request.Adapt(), gainfo); + } + } + else + { + await OfflineHandleAsync(request.Adapt(), gainfo); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "离线入库错误: 订单号:{no} .{message}", request.ThirdNo, ex.Message); + } + } + /// /// 分支处理在线/离线消费 /// @@ -423,27 +466,7 @@ public class OrderService : IOrderService return await EMealVoucherConsumeAsync(request, gainfo); if (request.IsOffline) - { - try - { - if (request.ThirdNo.IsPresent() && await ToCheckAbleOfflineConsumeAsync(request.ThirdNo)) - { - await using var handler = await _redisCache.LockAsync($"consume:device-offline:{request.ThirdNo}"); - if (handler.Acquired) - { - await HandleOfflineAsync(request.Adapt(), gainfo); - } - } - else - { - await HandleOfflineAsync(request.Adapt(), gainfo); - } - } - catch (Exception ex) - { - _logger.LogError(ex, "离线入库错误: 订单号:{no} .{message}", request.ThirdNo, ex.Message); - } - } + await OfflineConsumeAsync(request, gainfo); else { try @@ -454,52 +477,17 @@ public class OrderService : IOrderService { message = ex.Message; } - - //获取餐券余额 - var data = await DbContext.Queryable() - .LeftJoin((x, d) => x.No == d.No) - .Where((x, d) => x.No == no && d.IdNo == idNo) - .Select((x, d) => new OrderResultResponse - { - UserCode = d.IdNo, - UserName = d.Name, - CurrentBalance = d.Balance - }) - .SingleAsync(); - - try - { - var v = data.UserCode ?? string.Empty; - var vc = v.ToCharArray().Reverse().ToList(); - - for (int i = 0; i < vc.Count; i++) - { - if (i + 1 > 4) - { - vc[i] = '*'; - } - } - - vc.Reverse(); - data.UserCode = string.Join("", vc); - } - catch (Exception e) - { - - } - - return new DefaultApiResult - { - Code = message.IsPresent() ? ApiStateCode.Error : ApiStateCode.Success, - Data = data, - Msg = message - }; } - var currentFactory = await _dbContext.Queryable().Where(x => x.UniqueNo == request.DeviceUniqueNo).Select(x => x.TenantId).SingleAsync(); - var balance = await _balanceRepository.GetBalanceAsync(gainfo.Code, currentFactory); + //获取人员信息 + var currentFactory = await _dbContext.Queryable() + .Where(x => x.UniqueNo == request.DeviceUniqueNo) + .Select(x => x.TenantId) + .SingleAsync(); + + var balance = await _balanceRepository.GetBalanceAsync(gainfo.Code, currentFactory); + var totalBalance = await _balanceRepository.GetBalanceAsync(gainfo.Code, string.Empty); - //获取人员余额 var data = await _dbContext.Queryable() .LeftJoin((x, department) => x.DepartmentNo == department.No) .Where(x => x.Code == gainfo.Code) @@ -509,7 +497,9 @@ public class OrderService : IOrderService UserName = x.Name, DepartmentNo = x.DepartmentNo, DepartmentName = department.Name, - CurrentBalance = balance + + CurrentBalance = balance, + CurrentTotalBalance = totalBalance }) .SingleAsync(); @@ -555,6 +545,7 @@ public class OrderService : IOrderService (nowDate >= current.Start && nowDate <= current.End).ThrowIfFalse("餐券已过期"); + var eMealVoucher = await _dbContext.Queryable().Where(x => x.No == no).SingleAsync(); var checkData = await PreCheckAsync(request.DeviceUniqueNo, request.CostDateTime); diff --git a/Src/Dlhis.Canteen/Setting/Services/ICanteenSettingService.cs b/Src/Dlhis.Canteen/Setting/Services/ICanteenSettingService.cs index 2376b87c..9c4c6b36 100644 --- a/Src/Dlhis.Canteen/Setting/Services/ICanteenSettingService.cs +++ b/Src/Dlhis.Canteen/Setting/Services/ICanteenSettingService.cs @@ -44,7 +44,13 @@ public interface ICanteenSettingService : IScopeDependency Task GetBusinessSwitchTimeAsync(string tenantId); - Task GetSettingAsync(CanteenSettingItemEnumType item, string factory, string userNo , T defaultValue = default); + Task GetSettingAsync(CanteenSettingItemEnumType item, string factory, string userNo, T defaultValue = default); + /// + /// 获取消费日期 + /// + /// + /// + /// Task GetCostDateAsync(string factory, DateTime costDateTime); } \ No newline at end of file diff --git a/Src/Dlhis.Middle/Api/FaceBearerTokenHandler.cs b/Src/Dlhis.Middle/Api/FaceBearerTokenHandler.cs deleted file mode 100644 index a0e806ff..00000000 --- a/Src/Dlhis.Middle/Api/FaceBearerTokenHandler.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System.Text; -using Dlhis.Middle.Response; -using Kurisu.AspNetCore.UnifyResultAndValidation; -using Kurisu.RemoteCall.Abstractions; -using Microsoft.Extensions.Caching.Memory; -using Newtonsoft.Json; - -namespace Dlhis.Middle.Api -{ - public class FaceBearerTokenHandler : IAuthTokenHandler - { - /// - public string GetToken(IServiceProvider serviceProvider) - { - var cache = serviceProvider.GetService(); - if (cache.TryGetValue("token", out string token)) return "Bearer " + token; - - var httpClient = serviceProvider.GetService().CreateClient("face"); - var hostName = serviceProvider.GetService().GetSection("HostName").Value; - - var tokenResponse = httpClient.PostAsync($"https://{hostName}/api/user/oauth2/clientgrant", new StringContent(JsonConvert.SerializeObject(new - { - ClientId = "e509c2aaa98e300c", - ClientSecret = "6184d8979fc48105" - }), Encoding.UTF8, "application/json")).GetAwaiter().GetResult(); - - var tokenJson = tokenResponse.Content.ReadAsStringAsync().GetAwaiter().GetResult(); - var tokenInfo = JsonConvert.DeserializeObject>(tokenJson); - - token = tokenInfo.Data.AccessToken; - - cache.Set("token", token, TimeSpan.FromSeconds(tokenInfo.Data.Expires)); - - return token; - } - } -} \ No newline at end of file diff --git a/Src/Dlhis.Middle/Apis/Handlers/ClientHandler.cs b/Src/Dlhis.Middle/Apis/Handlers/ClientHandler.cs new file mode 100644 index 00000000..fa3b1694 --- /dev/null +++ b/Src/Dlhis.Middle/Apis/Handlers/ClientHandler.cs @@ -0,0 +1,23 @@ +using Kurisu.RemoteCall.Abstractions; + +namespace Dlhis.Middle.Apis.Handlers; + +public class ClientHandler : IHttpRemoteCallPolicyHandler +{ + /// + public IHttpClientBuilder ConfigureHttpClient(IHttpClientBuilder builder) + { + builder.ConfigureHttpClient(client => { client.Timeout = TimeSpan.FromSeconds(10); }).ConfigurePrimaryHttpMessageHandler(() => + { + var handler = new HttpClientHandler + { + ClientCertificateOptions = ClientCertificateOption.Manual, + ServerCertificateCustomValidationCallback = (_, _, _, _) => true + }; + + return handler; + }); + + return builder; + } +} \ No newline at end of file diff --git a/Src/Dlhis.Middle/Apis/Handlers/FaceBearerTokenHandler.cs b/Src/Dlhis.Middle/Apis/Handlers/FaceBearerTokenHandler.cs new file mode 100644 index 00000000..37c409a2 --- /dev/null +++ b/Src/Dlhis.Middle/Apis/Handlers/FaceBearerTokenHandler.cs @@ -0,0 +1,14 @@ +using Dlhis.Middle.Services; +using Kurisu.RemoteCall.Abstractions; + +namespace Dlhis.Middle.Apis.Handlers; + +public class FaceBearerTokenHandler : IAsyncAuthTokenHandler +{ + /// + public async Task GetTokenAsync(IServiceProvider serviceProvider) + { + var tokenService = serviceProvider.GetService(); + return await tokenService.AuthAsync(); + } +} \ No newline at end of file diff --git a/Src/Dlhis.Middle/Api/IAssignmentDeviceTaskApi.cs b/Src/Dlhis.Middle/Apis/IAssignmentDeviceTaskApi.cs similarity index 69% rename from Src/Dlhis.Middle/Api/IAssignmentDeviceTaskApi.cs rename to Src/Dlhis.Middle/Apis/IAssignmentDeviceTaskApi.cs index 8c856a82..d15f6f0f 100644 --- a/Src/Dlhis.Middle/Api/IAssignmentDeviceTaskApi.cs +++ b/Src/Dlhis.Middle/Apis/IAssignmentDeviceTaskApi.cs @@ -1,11 +1,13 @@ +using Dlhis.Middle.Apis.Handlers; using Dlhis.Middle.Request; using Dlhis.Middle.Response; using Kurisu.AspNetCore.UnifyResultAndValidation; using Kurisu.RemoteCall.Attributes; -namespace Dlhis.Middle.Api; +namespace Dlhis.Middle.Apis; -[EnableRemoteClient(Name = "face-service", BaseUrl = "${Authority}")] +[RequestLog] +[EnableRemoteClient(Name = "face-service", BaseUrl = "${BaseUrl}", PolicyHandler = typeof(ClientHandler))] public interface IAssignmentDeviceTaskApi { [Auth(TokenHandler = typeof(FaceBearerTokenHandler))] diff --git a/Src/Dlhis.Middle/Api/ICanteenApi.cs b/Src/Dlhis.Middle/Apis/ICanteenApi.cs similarity index 67% rename from Src/Dlhis.Middle/Api/ICanteenApi.cs rename to Src/Dlhis.Middle/Apis/ICanteenApi.cs index 84a4d7e9..bbc2c1eb 100644 --- a/Src/Dlhis.Middle/Api/ICanteenApi.cs +++ b/Src/Dlhis.Middle/Apis/ICanteenApi.cs @@ -1,26 +1,29 @@ +using Dlhis.Middle.Apis.Handlers; +using Dlhis.Middle.Entities; using Dlhis.Middle.Request; using Dlhis.Middle.Response; using Kurisu.AspNetCore.DataAccess.Dto; using Kurisu.AspNetCore.UnifyResultAndValidation; using Kurisu.RemoteCall.Attributes; -namespace Dlhis.Middle.Api; +namespace Dlhis.Middle.Apis; -[EnableRemoteClient(Name = "face-service", BaseUrl = "${Authority}")] +[RequestLog] +[EnableRemoteClient(Name = "face-service", BaseUrl = "${BaseUrl}", PolicyHandler = typeof(ClientHandler))] public interface ICanteenApi { - [Auth(TokenHandler = typeof(FaceBearerTokenHandler))] [Post("/api/canteen/orders")] Task> AddAsync(OrderAddRequest request); - - - + + [Auth(TokenHandler = typeof(FaceBearerTokenHandler))] + [Post("/api/canteen/middle/upload")] + Task> UploadAsync(LocalBalanceRecordEntity entity); + [Auth(TokenHandler = typeof(FaceBearerTokenHandler))] [Post("/api/canteen/balances/device/page")] Task>> GetPageByDeviceUniqueNoAsync(BalanceRecordPageByDeviceUniqueNoRequest request); - - + [Auth(TokenHandler = typeof(FaceBearerTokenHandler))] [Post("/api/canteen/balances/refund")] Task> RefundAsync(BalanceRecordRefundRequest request); diff --git a/Src/Dlhis.Middle/Apis/ICommonApi.cs b/Src/Dlhis.Middle/Apis/ICommonApi.cs new file mode 100644 index 00000000..b44214fc --- /dev/null +++ b/Src/Dlhis.Middle/Apis/ICommonApi.cs @@ -0,0 +1,22 @@ +using Dlhis.Middle.Apis.Handlers; +using Dlhis.Middle.Request; +using Dlhis.Middle.Response; +using Kurisu.AspNetCore.UnifyResultAndValidation; +using Kurisu.RemoteCall.Attributes; + +namespace Dlhis.Middle.Apis; + +[EnableRemoteClient(Name = "face-service", BaseUrl = "${BaseUrl}", PolicyHandler = typeof(ClientHandler))] +public interface ICommonApi +{ + [Post("/api/user/oauth2/clientgrant")] + public Task> AuthAsync(object request); + + [Auth(TokenHandler = typeof(FaceBearerTokenHandler))] + [Post("/api/common/middles/healthz")] + public Task CheckHealthAsync(HealthCheckRequest request); + + [Auth(TokenHandler = typeof(FaceBearerTokenHandler))] + [Get("/api/common/SysData/download")] + public Task>> DownloadAsync(string factory, string tableName); +} \ No newline at end of file diff --git a/Src/Dlhis.Middle/Services/Implements/BalanceRecordCheckBackgroundService.cs b/Src/Dlhis.Middle/BackgroundServices/BalanceRecordUploadBackgroundService.cs similarity index 60% rename from Src/Dlhis.Middle/Services/Implements/BalanceRecordCheckBackgroundService.cs rename to Src/Dlhis.Middle/BackgroundServices/BalanceRecordUploadBackgroundService.cs index a117b24b..f0f441a0 100644 --- a/Src/Dlhis.Middle/Services/Implements/BalanceRecordCheckBackgroundService.cs +++ b/Src/Dlhis.Middle/BackgroundServices/BalanceRecordUploadBackgroundService.cs @@ -1,46 +1,43 @@ -using System.Net.Http.Headers; +using System.Net.Http.Headers; using System.Text; +using Dlhis.Middle.Apis; using Dlhis.Middle.Entities; using Dlhis.Middle.Response; +using Dlhis.Middle.Services; using Kurisu.AspNetCore.DataAccess.SqlSugar.Services; using Kurisu.AspNetCore.UnifyResultAndValidation; using Kurisu.AspNetCore.Utils.Extensions; -using Microsoft.Extensions.Caching.Memory; -using Newtonsoft.Json; -namespace Dlhis.Middle.Services.Implements; +namespace Dlhis.Middle.BackgroundServices; -public class BalanceRecordCheckBackgroundService : BackgroundService +public class BalanceRecordUploadBackgroundService : BackgroundService { private readonly IServiceProvider _serviceProvider; - private readonly ILogger _logger; - private readonly IMemoryCache _memoryCache; - private readonly IHttpClientFactory _httpClientFactory; + private readonly ILogger _logger; + private readonly IWebHostEnvironment _environment; + private readonly ISettingService _settingService; + private readonly ICanteenApi _canteenApi; private readonly IHealthCheckService _healthCheckService; - private readonly string _factory; - private readonly string _hostName; - - public BalanceRecordCheckBackgroundService(IServiceProvider serviceProvider, - ILogger logger, - IMemoryCache memoryCache, - IHttpClientFactory httpClientFactory, - IHealthCheckService healthCheckService, - IConfiguration configuration) + public BalanceRecordUploadBackgroundService(IServiceProvider serviceProvider, + ILogger logger, + IWebHostEnvironment environment, + ISettingService settingService, + ICanteenApi canteenApi, + IHealthCheckService healthCheckService) { _serviceProvider = serviceProvider; _logger = logger; - _memoryCache = memoryCache; - _httpClientFactory = httpClientFactory; + _environment = environment; + _settingService = settingService; + _canteenApi = canteenApi; _healthCheckService = healthCheckService; - _factory = configuration.GetSection("Factory").Value; - _hostName = configuration.GetSection("HostName").Value; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { - while (!stoppingToken.IsCancellationRequested) + while (!stoppingToken.IsCancellationRequested && _environment.IsProduction()) { if (!_healthCheckService.GetIsOffline()) { @@ -50,7 +47,8 @@ public class BalanceRecordCheckBackgroundService : BackgroundService var db = scope.ServiceProvider.GetService(); var ds = scope.ServiceProvider.GetService(); - foreach (var factory in _factory.Split(',')) + var factories = _settingService.GetFactories(); + foreach (var factory in factories) { try { @@ -64,7 +62,7 @@ public class BalanceRecordCheckBackgroundService : BackgroundService await db.Client.Ado.BeginTranAsync(); try { - var r = await UploadAsync(balanceRecord); + var r = await _canteenApi.UploadAsync(balanceRecord); if (r.Code != ApiStateCode.Success) { throw new Exception(r.Msg); @@ -108,62 +106,23 @@ public class BalanceRecordCheckBackgroundService : BackgroundService && !_healthCheckService.GetIsOffline() && !await db.Queryable().Where(x => !x.IsSync).AnyAsync()) { - await ds.InitAsync(_factory); + await ds.InitAsync(factories); } else if (now is { Hour: 15, Minute: 1 } && !_healthCheckService.GetIsOffline() && !await db.Queryable().Where(x => !x.IsSync).AnyAsync()) { - await ds.InitAsync(_factory); + await ds.InitAsync(factories); } else if (now is { Hour: 20, Minute: 1 } && !_healthCheckService.GetIsOffline() && !await db.Queryable().Where(x => !x.IsSync).AnyAsync()) { - await ds.InitAsync(_factory); + await ds.InitAsync(factories); } } await Task.Delay(60 * 1000, stoppingToken); } } - - public async Task> UploadAsync(LocalBalanceRecordEntity entity) - { - var token = await AuthAsync(); - - var httpClient = _httpClientFactory.CreateClient("face"); - httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); - - var url = $"https://{_hostName}/api/canteen/middle/upload"; - - var json = entity.ToJson(); - var content = new StringContent(json, Encoding.UTF8, "application/json"); - - var response = await httpClient.PostAsync(url, content); - var responseJson = await response.Content.ReadAsStringAsync(); - return responseJson.ToObject>(); - } - - private async Task AuthAsync() - { - var httpClient = _httpClientFactory.CreateClient("face"); - - if (_memoryCache.TryGetValue("token", out string token)) return token; - - var tokenResponse = await httpClient.PostAsync($"https://{_hostName}/api/User/OAuth2/clientgrant", new StringContent(JsonConvert.SerializeObject(new - { - ClientId = "e509c2aaa98e300c", - ClientSecret = "6184d8979fc48105" - }), Encoding.UTF8, "application/json")); - - var tokenJson = await tokenResponse.Content.ReadAsStringAsync(); - var tokenInfo = JsonConvert.DeserializeObject>(tokenJson); - - token = tokenInfo.Data.AccessToken; - - _memoryCache.Set("token", token, TimeSpan.FromSeconds(tokenInfo.Data.Expires)); - - return token; - } } \ No newline at end of file diff --git a/Src/Dlhis.Middle/Services/Implements/HealthCheckBackgroundService.cs b/Src/Dlhis.Middle/BackgroundServices/HealthCheckBackgroundService.cs similarity index 87% rename from Src/Dlhis.Middle/Services/Implements/HealthCheckBackgroundService.cs rename to Src/Dlhis.Middle/BackgroundServices/HealthCheckBackgroundService.cs index bc658f64..a765b742 100644 --- a/Src/Dlhis.Middle/Services/Implements/HealthCheckBackgroundService.cs +++ b/Src/Dlhis.Middle/BackgroundServices/HealthCheckBackgroundService.cs @@ -1,4 +1,6 @@ -namespace Dlhis.Middle.Services.Implements; +using Dlhis.Middle.Services; + +namespace Dlhis.Middle.BackgroundServices; public class HealthCheckBackgroundService : BackgroundService { diff --git a/Src/Dlhis.Middle/Controllers/AssignmentsController.cs b/Src/Dlhis.Middle/Controllers/AssignmentsController.cs index 5dfaa784..8238041f 100644 --- a/Src/Dlhis.Middle/Controllers/AssignmentsController.cs +++ b/Src/Dlhis.Middle/Controllers/AssignmentsController.cs @@ -1,5 +1,5 @@ using Dlhis.Entity.Device.Enums; -using Dlhis.Middle.Api; +using Dlhis.Middle.Apis; using Dlhis.Middle.Request; using Dlhis.Middle.Response; using Dlhis.Middle.Services; diff --git a/Src/Dlhis.Middle/Controllers/BalancesController.cs b/Src/Dlhis.Middle/Controllers/BalancesController.cs index 04749614..31444388 100644 --- a/Src/Dlhis.Middle/Controllers/BalancesController.cs +++ b/Src/Dlhis.Middle/Controllers/BalancesController.cs @@ -1,4 +1,4 @@ -using Dlhis.Middle.Api; +using Dlhis.Middle.Apis; using Dlhis.Middle.Request; using Dlhis.Middle.Response; using Dlhis.Middle.Services; diff --git a/Src/Dlhis.Middle/Controllers/GainfosController.cs b/Src/Dlhis.Middle/Controllers/GainfosController.cs index a8f72fa6..6fc33430 100644 --- a/Src/Dlhis.Middle/Controllers/GainfosController.cs +++ b/Src/Dlhis.Middle/Controllers/GainfosController.cs @@ -1,4 +1,5 @@ using Dlhis.Middle.Filters; +using Dlhis.Middle.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; @@ -12,14 +13,13 @@ namespace Dlhis.Middle.Controllers; public class GainfosController : ControllerBase { private readonly IHttpClientFactory _httpClientFactory; - private readonly IConfiguration _configuration; - private readonly ILogger _logger; + private readonly ISettingService _settingService; - public GainfosController(IHttpClientFactory httpClientFactory, IConfiguration configuration, ILogger logger) + public GainfosController(IHttpClientFactory httpClientFactory, + ISettingService settingService) { _httpClientFactory = httpClientFactory; - _configuration = configuration; - _logger = logger; + _settingService = settingService; } /// @@ -32,14 +32,11 @@ public class GainfosController : ControllerBase [HttpGet("face")] public async Task GetFaceAsync(string token) { - var hostName = _configuration.GetSection("HostName").Value; - var httpClient = _httpClientFactory.CreateClient("face"); - - _logger.LogInformation("token:{token}", token); + var httpClient = _httpClientFactory.CreateClient(); try { - var faceBytes = await httpClient.GetByteArrayAsync($"https://{hostName}/api/basic/gainfos/face?token={token}"); + var faceBytes = await httpClient.GetByteArrayAsync($"{_settingService.GetBaseUrl()}/api/basic/gainfos/face?token={token}"); if (faceBytes.Length == 0) { diff --git a/Src/Dlhis.Middle/Controllers/OAuth2Controller.cs b/Src/Dlhis.Middle/Controllers/OAuth2Controller.cs index 5b448c0d..f6b8624e 100644 --- a/Src/Dlhis.Middle/Controllers/OAuth2Controller.cs +++ b/Src/Dlhis.Middle/Controllers/OAuth2Controller.cs @@ -1,4 +1,5 @@ using System.Text; +using Dlhis.Middle.Apis; using Dlhis.Middle.Request; using Dlhis.Middle.Services; using Microsoft.AspNetCore.Mvc; @@ -13,23 +14,20 @@ namespace Dlhis.Middle.Controllers; [ApiController] public class OAuth2Controller : ControllerBase { - private readonly IHttpClientFactory _httpClientFactory; - private readonly IConfiguration _configuration; + private readonly ICommonApi _commonApi; private readonly IHealthCheckService _healthCheckService; - public OAuth2Controller(IHttpClientFactory httpClientFactory, IConfiguration configuration, IHealthCheckService healthCheckService) + public OAuth2Controller( + ICommonApi commonApi, + IHealthCheckService healthCheckService) { - _httpClientFactory = httpClientFactory; - _configuration = configuration; + _commonApi = commonApi; _healthCheckService = healthCheckService; } [HttpPost("clientgrant")] public async Task ClientGrant(ClientGrantRequest request) { - var authority = _configuration.GetSection("Authority").Value; - var httpClient = _httpClientFactory.CreateClient("face"); - if (_healthCheckService.GetIsOffline()) { return new @@ -41,9 +39,12 @@ public class OAuth2Controller : ControllerBase }; } - var content = new StringContent($"grant_type=client_credentials&client_id={request.ClientId}&client_secret={request.ClientSecret}&scope={request.Scope}", Encoding.UTF8, "application/x-www-form-urlencoded"); - var response = await httpClient.PostAsync($"{authority}/oauth2/connect/token", content); - var result = await response.Content.ReadAsStringAsync(); - return JObject.Parse(result); + var r = await _commonApi.AuthAsync(new + { + request.ClientId, + request.ClientSecret + }); + + return r.Data; } } \ No newline at end of file diff --git a/Src/Dlhis.Middle/Dlhis.Middle.csproj b/Src/Dlhis.Middle/Dlhis.Middle.csproj index accf19a9..07f7413e 100644 --- a/Src/Dlhis.Middle/Dlhis.Middle.csproj +++ b/Src/Dlhis.Middle/Dlhis.Middle.csproj @@ -17,10 +17,23 @@ - + + + + appsettings.json + + + + + + + + + + diff --git a/Src/Dlhis.Middle/Entities/LocalGainfoMealEntity.cs b/Src/Dlhis.Middle/Entities/LocalGainfoMealEntity.cs index bb9809ff..322272aa 100644 --- a/Src/Dlhis.Middle/Entities/LocalGainfoMealEntity.cs +++ b/Src/Dlhis.Middle/Entities/LocalGainfoMealEntity.cs @@ -1,4 +1,3 @@ -using Dlhis.Entity.Basic.Entity; using Kurisu.AspNetCore.DataAccess.Entity; using Kurisu.AspNetCore.DataAccess.SqlSugar; using SqlSugar; @@ -12,7 +11,7 @@ namespace Dlhis.Middle.Entities /// - /// 就餐人员 + /// 就餐人员 /// [SugarTable(TableName = "GainfoMeal", TableDescription = "就餐人员")] public class GainfoMealEntity : SugarBaseEntity, IVersion @@ -24,25 +23,13 @@ namespace Dlhis.Middle.Entities public string UserCode { get; set; } /// - /// 余额 + /// 余额 /// [SugarColumn(ColumnDescription = "余额")] public decimal Balance { get; set; } - + /// - /// 余额(充值) - /// - [SugarColumn(ColumnDescription = "余额(充值)")] - public decimal BalanceOfRecharge { get; set; } - - /// - /// 余额(餐补) - /// - [SugarColumn(ColumnDescription = "余额(餐补)")] - public decimal BalanceOfSubsidies { get; set; } - - /// - /// 版本号 + /// 版本号 /// [SugarColumn(ColumnDescription = "版本号")] public int Version { get; set; } diff --git a/Src/Dlhis.Middle/Program.cs b/Src/Dlhis.Middle/Program.cs index 99f6c4a6..7558c266 100644 --- a/Src/Dlhis.Middle/Program.cs +++ b/Src/Dlhis.Middle/Program.cs @@ -1,5 +1,5 @@ +using Dlhis.Middle.BackgroundServices; using Dlhis.Middle.Services; -using Dlhis.Middle.Services.Implements; using Kurisu.AspNetCore; using Kurisu.AspNetCore.Startup; using Microsoft.IdentityModel.Logging; @@ -24,20 +24,11 @@ public class Startup : DefaultStartup public override void ConfigureServices(IServiceCollection services) { base.ConfigureServices(services); + + services.AddHostedService(); + services.AddHostedService(); services.AddRemoteCall(App.ActiveTypes); - services.AddHttpClient("face", client => { client.Timeout = TimeSpan.FromSeconds(30); }).ConfigurePrimaryHttpMessageHandler(() => - { - var handler = new HttpClientHandler - { - ClientCertificateOptions = ClientCertificateOption.Manual, - ServerCertificateCustomValidationCallback = (_, _, _, _) => true - }; - - return handler; - }); - services.AddHostedService(); - services.AddHostedService(); services.AddMemoryCache(); } @@ -49,10 +40,9 @@ public class Startup : DefaultStartup if (Configuration.GetSection("Download").Value == "1") { using var scope = app.ApplicationServices.CreateScope(); - var factory = Configuration.GetSection("Factory").Value; - + var factories = scope.ServiceProvider.GetService().GetFactories(); var ds = scope.ServiceProvider.GetService(); - ds.InitAsync(factory).Wait(); + ds.InitAsync(factories).Wait(); } } } \ No newline at end of file diff --git a/Src/Dlhis.Middle/Request/HealthCheckRequest.cs b/Src/Dlhis.Middle/Request/HealthCheckRequest.cs new file mode 100644 index 00000000..e783dc81 --- /dev/null +++ b/Src/Dlhis.Middle/Request/HealthCheckRequest.cs @@ -0,0 +1,6 @@ +namespace Dlhis.Middle.Request; + +public class HealthCheckRequest +{ + public List Factories { get; set; } +} \ No newline at end of file diff --git a/Src/Dlhis.Middle/Response/OrderResultResponse.cs b/Src/Dlhis.Middle/Response/OrderResultResponse.cs index 65b07959..eaf00498 100644 --- a/Src/Dlhis.Middle/Response/OrderResultResponse.cs +++ b/Src/Dlhis.Middle/Response/OrderResultResponse.cs @@ -28,4 +28,7 @@ public class OrderResultResponse /// 余额 /// public decimal Balance { get; set; } + + + public decimal TotalBalance { get; set; } } \ No newline at end of file diff --git a/Src/Dlhis.Middle/Services/IDataDownloadService.cs b/Src/Dlhis.Middle/Services/IDataDownloadService.cs index 0efb64d4..eccedb1c 100644 --- a/Src/Dlhis.Middle/Services/IDataDownloadService.cs +++ b/Src/Dlhis.Middle/Services/IDataDownloadService.cs @@ -2,9 +2,7 @@ namespace Dlhis.Middle.Services; public interface IDataDownloadService : IScopeDependency { - Task InitAsync(string factory); + Task InitAsync(string[] factories); Task DownloadAsync(string factory) where T : class, new(); - - Task TruncateAsync(); } \ No newline at end of file diff --git a/Src/Dlhis.Middle/Services/IRemoteOrderService.cs b/Src/Dlhis.Middle/Services/IRemoteOrderService.cs index e161d9ad..e5f6dfc0 100644 --- a/Src/Dlhis.Middle/Services/IRemoteOrderService.cs +++ b/Src/Dlhis.Middle/Services/IRemoteOrderService.cs @@ -1,12 +1,8 @@ -using Dlhis.Middle.Request; -using Dlhis.Middle.Response; -using Kurisu.AspNetCore.UnifyResultAndValidation; - namespace Dlhis.Middle.Services; public interface IRemoteOrderService : IScopeDependency { - Task> AddAsync(OrderAddRequest request); + //Task> AddAsync(OrderAddRequest request); Task AbleRemoteCallAsync(); } \ No newline at end of file diff --git a/Src/Dlhis.Middle/Services/ISettingService.cs b/Src/Dlhis.Middle/Services/ISettingService.cs new file mode 100644 index 00000000..b7946df7 --- /dev/null +++ b/Src/Dlhis.Middle/Services/ISettingService.cs @@ -0,0 +1,8 @@ +namespace Dlhis.Middle.Services; + +public interface ISettingService : ISingletonDependency +{ + string[] GetFactories(); + + string GetBaseUrl(); +} \ No newline at end of file diff --git a/Src/Dlhis.Middle/Services/ITokenService.cs b/Src/Dlhis.Middle/Services/ITokenService.cs new file mode 100644 index 00000000..d4dffabe --- /dev/null +++ b/Src/Dlhis.Middle/Services/ITokenService.cs @@ -0,0 +1,6 @@ +namespace Dlhis.Middle.Services; + +public interface ITokenService : ISingletonDependency +{ + Task AuthAsync(); +} \ No newline at end of file diff --git a/Src/Dlhis.Middle/Services/Implements/DataDownloadService.cs b/Src/Dlhis.Middle/Services/Implements/DataDownloadService.cs index c9498000..9f1e83bd 100644 --- a/Src/Dlhis.Middle/Services/Implements/DataDownloadService.cs +++ b/Src/Dlhis.Middle/Services/Implements/DataDownloadService.cs @@ -1,43 +1,32 @@ -using System.Net.Http.Headers; using System.Reflection; -using System.Text; +using Dlhis.Middle.Apis; using Dlhis.Middle.Entities; -using Dlhis.Middle.Response; using Kurisu.AspNetCore.DataAccess.SqlSugar.Services; -using Kurisu.AspNetCore.UnifyResultAndValidation; -using Kurisu.AspNetCore.Utils.Extensions; -using Microsoft.AspNetCore.WebUtilities; -using Microsoft.Extensions.Caching.Memory; -using Newtonsoft.Json; using SqlSugar; namespace Dlhis.Middle.Services.Implements; public class DataDownloadService : IDataDownloadService { - private readonly IHttpClientFactory _httpClientFactory; - private readonly IMemoryCache _memoryCache; private readonly IDbContext _dbContext; + private readonly ICommonApi _commonApi; private readonly ILogger _logger; - private readonly string _hostName; - public DataDownloadService(IHttpClientFactory httpClientFactory, IMemoryCache memoryCache, IConfiguration configuration, IDbContext dbContext, ILogger logger) + public DataDownloadService( + IDbContext dbContext, + ICommonApi commonApi, + ILogger logger) { - _httpClientFactory = httpClientFactory; - _memoryCache = memoryCache; _dbContext = dbContext; + _commonApi = commonApi; _logger = logger; - _hostName = configuration.GetSection("HostName").Value; } - public async Task InitAsync(string factory) + public async Task InitAsync(string[] factories) { + //需要上传完记录才可下载 if (await _dbContext.Queryable().Where(x => x.IsSync == false).AnyAsync()) - { return; - } - - var factories = factory.Split(','); await _dbContext.Client.Ado.BeginTranAsync(); try @@ -84,9 +73,10 @@ public class DataDownloadService : IDataDownloadService _logger.LogInformation("档案{count}", await _dbContext.Queryable().CountAsync()); _logger.LogInformation("余额{count}", await _dbContext.Queryable().CountAsync()); _logger.LogInformation("下载完成"); + await _dbContext.Client.Ado.CommitTranAsync(); } - catch (Exception e) + catch (Exception) { await _dbContext.Client.Ado.RollbackTranAsync(); throw; @@ -95,27 +85,11 @@ public class DataDownloadService : IDataDownloadService public async Task DownloadAsync(string factory) where T : class, new() { - var token = await AuthAsync(); - - var httpClient = _httpClientFactory.CreateClient("face"); - httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); - - var url = $"https://{_hostName}/api/common/SysData/download"; - - var requestUrl = QueryHelpers.AddQueryString(url, new Dictionary - { - ["factory"] = factory, - ["tableName"] = typeof(T).GetCustomAttribute()!.TableName - }); - - var response = await httpClient.GetStringAsync(requestUrl); - var pack = response.ToObject>>(); - + var pack = await _commonApi.DownloadAsync(factory, typeof(T).GetCustomAttribute()!.TableName); await _dbContext.InsertAsync(pack.Data); } - /// - public async Task TruncateAsync() + private async Task TruncateAsync() { await _dbContext.Client.Deleteable().ExecuteCommandAsync(); await _dbContext.Client.Deleteable().ExecuteCommandAsync(); @@ -128,26 +102,4 @@ public class DataDownloadService : IDataDownloadService await _dbContext.Client.Deleteable().ExecuteCommandAsync(); await _dbContext.Client.Deleteable().ExecuteCommandAsync(); } - - private async Task AuthAsync() - { - var httpClient = _httpClientFactory.CreateClient("face"); - - if (_memoryCache.TryGetValue("token", out string token)) return token; - - var tokenResponse = await httpClient.PostAsync($"https://{_hostName}/api/User/OAuth2/clientgrant", new StringContent(JsonConvert.SerializeObject(new - { - ClientId = "e509c2aaa98e300c", - ClientSecret = "6184d8979fc48105" - }), Encoding.UTF8, "application/json")); - - var tokenJson = await tokenResponse.Content.ReadAsStringAsync(); - var tokenInfo = JsonConvert.DeserializeObject>(tokenJson); - - token = tokenInfo.Data.AccessToken; - - _memoryCache.Set("token", token, TimeSpan.FromSeconds(tokenInfo.Data.Expires)); - - return token; - } } \ No newline at end of file diff --git a/Src/Dlhis.Middle/Services/Implements/HealthcheckService.cs b/Src/Dlhis.Middle/Services/Implements/HealthcheckService.cs index 2c01192a..a254668d 100644 --- a/Src/Dlhis.Middle/Services/Implements/HealthcheckService.cs +++ b/Src/Dlhis.Middle/Services/Implements/HealthcheckService.cs @@ -1,19 +1,26 @@ -using System.Net.Sockets; +using Dlhis.Middle.Apis; +using Dlhis.Middle.Request; +using Kurisu.AspNetCore.UnifyResultAndValidation; namespace Dlhis.Middle.Services.Implements; public class HealthCheckService : IHealthCheckService { private bool _isOffline; - private readonly string _hostName; private readonly ILogger _logger; - private int _successRetry; - private int _retry; + private readonly ISettingService _settingService; + private readonly ICommonApi _healthCheckApi; + private int _attempted; - public HealthCheckService(ILogger logger, IConfiguration configuration) + private bool _isBegin; + + public HealthCheckService(ILogger logger, + ISettingService settingService, + ICommonApi healthCheckApi) { _logger = logger; - _hostName = configuration.GetSection("HostName").Value; + _settingService = settingService; + _healthCheckApi = healthCheckApi; } public bool GetIsOffline() @@ -23,44 +30,44 @@ public class HealthCheckService : IHealthCheckService public async Task DoHealthCheckAsync() { - var cancellationTokenSource = new CancellationTokenSource(5000); - var tcpClient = new TcpClient(); - try { - _logger.LogDebug("tcp connecting {host} {port}", _hostName, 443); - await tcpClient.ConnectAsync(_hostName, 443, cancellationTokenSource.Token); - _retry++; - _logger.LogDebug("retry {retry}", _retry); - if (tcpClient.Connected) + var factories = _settingService.GetFactories(); + + var response = await _healthCheckApi.CheckHealthAsync(new HealthCheckRequest { Factories = factories.ToList() }); + if (response.Code == ApiStateCode.Success) { - _successRetry++; - _logger.LogDebug("success connected {count}", _successRetry); - if (_successRetry == 4) + _attempted++; + if (_attempted == 5) { _isOffline = false; - _successRetry = 0; - _retry = 0; - _logger.LogInformation("current is {status}", "healthy"); + _attempted = 0; } - else + + if (!_isBegin) { - _logger.LogDebug("wait next check in {waitTime}", _successRetry * 1000); - await Task.Delay(_successRetry * 1000, cancellationTokenSource.Token); + _isOffline = false; + _isBegin = true; } + + if (_isOffline == false) + { + _logger.LogInformation("Health"); + } + + await Task.Delay(_attempted * 1000); } else { - _successRetry = 0; _isOffline = true; - _logger.LogDebug("current is {status}", "unavailable"); - await Task.Delay(500); + _logger.LogInformation("Error {message}", response.Msg); } } catch (Exception ex) { - _logger.LogError("fail cause :{reason}", ex.Message); + _logger.LogError("Failed cause :{reason}", ex.Message); _isOffline = true; + await Task.Delay(5000); } } } \ No newline at end of file diff --git a/Src/Dlhis.Middle/Services/Implements/OrderService.cs b/Src/Dlhis.Middle/Services/Implements/OrderService.cs index 919663c6..fadb172f 100644 --- a/Src/Dlhis.Middle/Services/Implements/OrderService.cs +++ b/Src/Dlhis.Middle/Services/Implements/OrderService.cs @@ -1,5 +1,6 @@ using System.Diagnostics; using Dlhis.Entity.Canteen.Enums; +using Dlhis.Middle.Apis; using Dlhis.Middle.Entities; using Kurisu.AspNetCore.Utils; using Kurisu.AspNetCore.Utils.Extensions; @@ -17,6 +18,7 @@ public class OrderService : IOrderService { private readonly ICanteenSettingService _canteenSettingService; private readonly IRemoteOrderService _remoteOrderService; + private readonly ICanteenApi _canteenApi; private readonly ILogger _logger; private readonly string _factory; private readonly IDbContext _dbContext; @@ -24,14 +26,16 @@ public class OrderService : IOrderService public OrderService(ICanteenSettingService canteenSettingService, IRemoteOrderService remoteOrderService, - IConfiguration configuration, + ISettingService settingService, + ICanteenApi canteenApi, ILogger logger, IDbContext dbContext) { _canteenSettingService = canteenSettingService; _remoteOrderService = remoteOrderService; + _canteenApi = canteenApi; _logger = logger; - _factory = configuration.GetSection("Factory").Value; + _factory = settingService.GetFactories().Join(","); _dbContext = dbContext; } @@ -43,12 +47,12 @@ public class OrderService : IOrderService { if (await _remoteOrderService.AbleRemoteCallAsync()) { - var remoteResult = await _remoteOrderService.AddAsync(request); + var remoteResult = await _canteenApi.AddAsync(request); if (remoteResult.Code == ApiStateCode.Success) { var d = remoteResult.Data; await _dbContext.Updateable() - .SetColumns(x => x.Balance == d.Balance) + .SetColumns(x => x.Balance == d.TotalBalance) .Where(x => x.UserCode == d.UserCode) .ExecuteCommandAsync(); } diff --git a/Src/Dlhis.Middle/Services/Implements/RemoteOrderService.cs b/Src/Dlhis.Middle/Services/Implements/RemoteOrderService.cs index 05d84b14..707e7338 100644 --- a/Src/Dlhis.Middle/Services/Implements/RemoteOrderService.cs +++ b/Src/Dlhis.Middle/Services/Implements/RemoteOrderService.cs @@ -1,54 +1,37 @@ -using System.Net.Http.Headers; -using System.Text; using Dlhis.Middle.Entities; -using Dlhis.Middle.Request; -using Dlhis.Middle.Response; using Kurisu.AspNetCore.DataAccess.SqlSugar.Services; -using Kurisu.AspNetCore.UnifyResultAndValidation; -using Kurisu.AspNetCore.Utils.Extensions; -using Microsoft.Extensions.Caching.Memory; -using Newtonsoft.Json; namespace Dlhis.Middle.Services.Implements; public class RemoteOrderService : IRemoteOrderService { - private readonly string _hostName; - private readonly IHttpClientFactory _httpClientFactory; - private readonly IMemoryCache _memoryCache; private readonly IHealthCheckService _healthCheckService; private readonly IDbContext _dbContext; - public RemoteOrderService(IHttpClientFactory httpClientFactory, - IMemoryCache memoryCache, - IConfiguration configuration, + public RemoteOrderService( IHealthCheckService healthCheckService, IDbContext dbContext) { - _httpClientFactory = httpClientFactory; - _memoryCache = memoryCache; - _hostName = configuration.GetSection("hostName").Value; _healthCheckService = healthCheckService; _dbContext = dbContext; } - - /// - public async Task> AddAsync(OrderAddRequest request) - { - var token = await AuthAsync(); - - var httpClient = _httpClientFactory.CreateClient("face"); - httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); - - var content = new StringContent(request.ToJson(), Encoding.UTF8, "application/json"); - - var response = await httpClient.PostAsync($"https://{_hostName}/api/canteen/orders", content); - - var responseJson = await response.Content.ReadAsStringAsync(); - return responseJson.ToObject>(); - } + ///// + // public async Task> AddAsync(OrderAddRequest request) + // { + // var token = await _tokenService.AuthAsync(); + // + // var httpClient = _httpClientFactory.CreateClient("face"); + // httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + // + // var content = new StringContent(request.ToJson(), Encoding.UTF8, "application/json"); + // + // var response = await httpClient.PostAsync($"{_settingService.GetBaseUrl()}/api/canteen/orders", content); + // + // var responseJson = await response.Content.ReadAsStringAsync(); + // return responseJson.ToObject>(); + // } /// public async Task AbleRemoteCallAsync() @@ -60,28 +43,4 @@ public class RemoteOrderService : IRemoteOrderService return !_healthCheckService.GetIsOffline(); } - - - - private async Task AuthAsync() - { - var httpClient = _httpClientFactory.CreateClient("face"); - - if (_memoryCache.TryGetValue("token", out string token)) return token; - - var tokenResponse = await httpClient.PostAsync($"https://{_hostName}/api/User/OAuth2/clientgrant", new StringContent(JsonConvert.SerializeObject(new - { - ClientId = "e509c2aaa98e300c", - ClientSecret = "6184d8979fc48105" - }), Encoding.UTF8, "application/json")); - - var tokenJson = await tokenResponse.Content.ReadAsStringAsync(); - var tokenInfo = JsonConvert.DeserializeObject>(tokenJson); - - token = tokenInfo.Data.AccessToken; - - _memoryCache.Set("token", token, TimeSpan.FromSeconds(tokenInfo.Data.Expires)); - - return token; - } } \ No newline at end of file diff --git a/Src/Dlhis.Middle/Services/Implements/SettingService.cs b/Src/Dlhis.Middle/Services/Implements/SettingService.cs new file mode 100644 index 00000000..b583f924 --- /dev/null +++ b/Src/Dlhis.Middle/Services/Implements/SettingService.cs @@ -0,0 +1,23 @@ +namespace Dlhis.Middle.Services.Implements; + +public class SettingService : ISettingService +{ + private readonly IConfiguration _configuration; + + public SettingService(IConfiguration configuration) + { + _configuration = configuration; + } + + /// + public string[] GetFactories() + { + return _configuration.GetSection("Factory").Value.Split(","); + } + + /// + public string GetBaseUrl() + { + return _configuration.GetSection("BaseUrl").Value; + } +} \ No newline at end of file diff --git a/Src/Dlhis.Middle/Services/Implements/TokenService.cs b/Src/Dlhis.Middle/Services/Implements/TokenService.cs new file mode 100644 index 00000000..226a9de0 --- /dev/null +++ b/Src/Dlhis.Middle/Services/Implements/TokenService.cs @@ -0,0 +1,43 @@ +using Dlhis.Middle.Apis; +using Microsoft.Extensions.Caching.Memory; + +namespace Dlhis.Middle.Services.Implements; + +public class TokenService : ITokenService +{ + private readonly IMemoryCache _memoryCache; + private readonly ICommonApi _commonApi; + + public TokenService(IMemoryCache memoryCache, ICommonApi commonApi) + { + _memoryCache = memoryCache; + _commonApi = commonApi; + } + + /// + public async Task AuthAsync() + { + var exists = _memoryCache.TryGetValue("token", out string token); + try + { + if (!exists) + { + var tokenInfo = await _commonApi.AuthAsync(new + { + ClientId = "e509c2aaa98e300c", + ClientSecret = "6184d8979fc48105" + }); + + token = tokenInfo.Data.AccessToken; + + _memoryCache.Set("token", token, TimeSpan.FromSeconds(tokenInfo.Data.Expires)); + } + } + finally + { + token = "Bearer " + token; + } + + return token; + } +} \ No newline at end of file diff --git a/Src/Dlhis.Middle/appsettings.Development.json b/Src/Dlhis.Middle/appsettings.Development.json index efb527ae..1339edac 100644 --- a/Src/Dlhis.Middle/appsettings.Development.json +++ b/Src/Dlhis.Middle/appsettings.Development.json @@ -5,8 +5,7 @@ "Microsoft.AspNetCore": "Warning" } }, - "Authority": "https://face.jinkosolar.com", - "Factory": "1201", - "HostName": "face.jinkosolar.com", + "BaseUrl": "https://yikatong.isawesome.cn", + "Factory": "1234", "Download":1 } diff --git a/Src/Dlhis.Middle/appsettings.json b/Src/Dlhis.Middle/appsettings.json index f85ae1ef..b6e736e0 100644 --- a/Src/Dlhis.Middle/appsettings.json +++ b/Src/Dlhis.Middle/appsettings.json @@ -12,9 +12,6 @@ "SlowSqlTime": 1, "EnableSqlLog": false }, - "Authority": "https://face.jinkosolar.com", - "Factory": "", - "HostName": "face.jinkosolar.com", "AllowedHosts": "*", "SwaggerOptions": { "Enable": true, diff --git a/Src/Dlhis.Middle/local.db-journal b/Src/Dlhis.Middle/local.db-journal new file mode 100644 index 00000000..750c5ab6 Binary files /dev/null and b/Src/Dlhis.Middle/local.db-journal differ