Commit 7765af4a by lcx

发送日志方法修改

parent f1f3a48d
...@@ -234,7 +234,7 @@ public ApiResponse NewExtractData([CustomizeValidator, FromBody] ExtractRequest ...@@ -234,7 +234,7 @@ public ApiResponse NewExtractData([CustomizeValidator, FromBody] ExtractRequest
using (var scope = serviceScopeFactory.CreateScope()) using (var scope = serviceScopeFactory.CreateScope())
{ {
var scopedServices = scope.ServiceProvider.GetRequiredService<ExtractService>(); var scopedServices = scope.ServiceProvider.GetRequiredService<ExtractService>();
string extractFilePath = scopedServices.Main(allot.ID, allot.HospitalId, email, "User" + claim.GetUserId(), filePath, isSingle); string extractFilePath = scopedServices.Main(allot.ID, allot.HospitalId, claim.GetUserId(), filePath, true);
} }
}); });
} }
...@@ -254,7 +254,10 @@ public ApiResponse NewExtractData([CustomizeValidator, FromBody] ExtractRequest ...@@ -254,7 +254,10 @@ public ApiResponse NewExtractData([CustomizeValidator, FromBody] ExtractRequest
string json = JsonHelper.Serialize(obj); string json = JsonHelper.Serialize(obj);
logger.LogInformation("提取绩效数据参数:" + json); logger.LogInformation("提取绩效数据参数:" + json);
var parameter = JsonHelper.Deserialize<Dictionary<string, object>>(json); var parameter = JsonHelper.Deserialize<Dictionary<string, object>>(json);
var restRequest = string.IsNullOrEmpty(filePath) ? http.CreatePostRequest(json) : http.CreateFileRequest(new string[] { filePath }, parameter); parameter.Add("Token", claim.GetJwtToken());
var restRequest = string.IsNullOrEmpty(filePath)
? http.CreatePostRequest(json)
: http.CreateFileRequest(new string[] { filePath }, parameter);
Task.Run(() => http.GetResponse(extractUrl, restRequest)); Task.Run(() => http.GetResponse(extractUrl, restRequest));
} }
...@@ -370,13 +373,15 @@ public ApiResponse SaveFile() ...@@ -370,13 +373,15 @@ public ApiResponse SaveFile()
/// <summary> /// <summary>
/// 返回日志 /// 返回日志
/// </summary> /// </summary>
/// <param name="userId"></param>
/// <param name="request"></param> /// <param name="request"></param>
[Route("returnlog")] [Route("returnlog/{userId}")]
[HttpPost] [HttpPost]
public void ReturnLog([FromBody] MessageInfo request) [AllowAnonymous]
public void ReturnLog(int userId, [FromBody] MessageInfo request)
{ {
logger.LogInformation("返回日志:" + JsonHelper.Serialize(request)); logger.LogInformation("返回日志:" + JsonHelper.Serialize(request));
notificationsService.SendMessage(claim.GetUserId(), request); notificationsService.SendMessage(userId, request);
} }
/// <summary> /// <summary>
......
using AutoMapper; using AutoMapper;
using FluentValidation; using FluentValidation;
using FluentValidation.AspNetCore; using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
...@@ -9,6 +10,7 @@ ...@@ -9,6 +10,7 @@
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using NLog.Extensions.Logging; using NLog.Extensions.Logging;
using Performance.DtoModels.AppSettings; using Performance.DtoModels.AppSettings;
using Performance.DtoModels.AutoMapper; using Performance.DtoModels.AutoMapper;
...@@ -23,6 +25,7 @@ ...@@ -23,6 +25,7 @@
using System.IO; using System.IO;
using System.Reflection; using System.Reflection;
using System.Text; using System.Text;
using System.Threading.Tasks;
namespace Performance.Api namespace Performance.Api
{ {
...@@ -140,6 +143,45 @@ public void ConfigureServices(IServiceCollection services) ...@@ -140,6 +143,45 @@ public void ConfigureServices(IServiceCollection services)
#endregion redis #endregion redis
services.AddAuthentication(Options =>
{
Options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
Options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Consts.Secret)),
ValidIssuer = Consts.Issuer,
ValidAudience = Consts.Audience,
ValidateIssuer = false,
ValidateAudience = false
};
x.Events = new JwtBearerEvents
{
OnMessageReceived = (context) =>
{
if (!context.HttpContext.Request.Path.HasValue)
return Task.CompletedTask;
//重点在于这里;判断是Signalr的路径
var accessToken = context.HttpContext.Request.Query["access_token"];
var path = context.HttpContext.Request.Path;
if (!(string.IsNullOrWhiteSpace(accessToken)) && path.StartsWithSegments("/performance/allotLogHub"))
{
context.Token = accessToken;
return Task.CompletedTask;
}
return Task.CompletedTask;
}
};
});
services.AddMemoryCache(); services.AddMemoryCache();
services.AddHostedService<QueuedHostedService>(); services.AddHostedService<QueuedHostedService>();
......
...@@ -2148,11 +2148,6 @@ ...@@ -2148,11 +2148,6 @@
邮箱 邮箱
</summary> </summary>
</member> </member>
<member name="P:Performance.DtoModels.ExtractRequest.GroupName">
<summary>
Signalr分组名称
</summary>
</member>
<member name="P:Performance.DtoModels.ExtractRequest.UserId"> <member name="P:Performance.DtoModels.ExtractRequest.UserId">
<summary> <summary>
用户Id 用户Id
......
...@@ -3613,6 +3613,61 @@ ...@@ -3613,6 +3613,61 @@
1、绩效生成日志 2、绩效提取日志 3、绩效提取进度 1、绩效生成日志 2、绩效提取日志 3、绩效提取进度
</summary> </summary>
</member> </member>
<member name="T:Performance.EntityModels.log_signalr">
<summary>
</summary>
</member>
<member name="P:Performance.EntityModels.log_signalr.Id">
<summary>
</summary>
</member>
<member name="P:Performance.EntityModels.log_signalr.HospitalId">
<summary>
</summary>
</member>
<member name="P:Performance.EntityModels.log_signalr.AllotId">
<summary>
</summary>
</member>
<member name="P:Performance.EntityModels.log_signalr.Classify">
<summary>
分类
</summary>
</member>
<member name="P:Performance.EntityModels.log_signalr.TypeValue">
<summary>
类型值
</summary>
</member>
<member name="P:Performance.EntityModels.log_signalr.Type">
<summary>
类型
</summary>
</member>
<member name="P:Performance.EntityModels.log_signalr.Title">
<summary>
标题
</summary>
</member>
<member name="P:Performance.EntityModels.log_signalr.Message">
<summary>
消息
</summary>
</member>
<member name="P:Performance.EntityModels.log_signalr.Percentage">
<summary>
百分比
</summary>
</member>
<member name="P:Performance.EntityModels.log_signalr.CreateTime">
<summary>
</summary>
</member>
<member name="T:Performance.EntityModels.mod_dic"> <member name="T:Performance.EntityModels.mod_dic">
<summary> <summary>
部分公共数据抽取SQL 部分公共数据抽取SQL
......
...@@ -10,14 +10,17 @@ public class SingleData ...@@ -10,14 +10,17 @@ public class SingleData
public int UserId { get; set; } public int UserId { get; set; }
public bool IsSingle { get; set; } = false;
public SingleData() public SingleData()
{ {
} }
public SingleData(string uuid, int userId) public SingleData(string uuid, int userId, bool isSingle = false)
{ {
Uuid = uuid; Uuid = uuid;
UserId = userId; UserId = userId;
IsSingle = isSingle;
} }
} }
} }
...@@ -28,11 +28,6 @@ public class ExtractRequest ...@@ -28,11 +28,6 @@ public class ExtractRequest
public string Email { get; set; } public string Email { get; set; }
/// <summary> /// <summary>
/// Signalr分组名称
/// </summary>
public string GroupName { get; set; }
/// <summary>
/// 用户Id /// 用户Id
/// </summary> /// </summary>
public int UserId { get; set; } public int UserId { get; set; }
......
...@@ -49,7 +49,7 @@ public void ExtractData() ...@@ -49,7 +49,7 @@ public void ExtractData()
var request = JsonHelper.Deserialize<ExtractRequest>(json); var request = JsonHelper.Deserialize<ExtractRequest>(json);
if (request == null || request.AllotId == 0 || request.HospitalId == 0) if (request == null || request.AllotId == 0 || request.HospitalId == 0 || request.UserId == 0)
return; return;
var path = string.Empty; var path = string.Empty;
...@@ -58,7 +58,7 @@ public void ExtractData() ...@@ -58,7 +58,7 @@ public void ExtractData()
else else
path = SaveFileAsTemplate(Request.Form.Files[0], request.HospitalId); path = SaveFileAsTemplate(Request.Form.Files[0], request.HospitalId);
string filePath = extractService1.Main(request.AllotId, request.HospitalId, request.Email, "User" + request.UserId, path); string filePath = extractService1.Main(request.AllotId, request.HospitalId, request.UserId, path);
logger.LogInformation($"抽取的文件地址: {filePath}"); logger.LogInformation($"抽取的文件地址: {filePath}");
......
...@@ -15,7 +15,7 @@ public class DictionaryService : IAutoInjection ...@@ -15,7 +15,7 @@ public class DictionaryService : IAutoInjection
{ {
private readonly ILogger<DictionaryService> logger; private readonly ILogger<DictionaryService> logger;
private readonly QueryService queryService; private readonly QueryService queryService;
private readonly LogManageService logService; private readonly NotificationsService notificationsService;
private readonly PerforPeremployeeRepository peremployeeRepository; private readonly PerforPeremployeeRepository peremployeeRepository;
private readonly PerforHospitalconfigRepository hospitalconfigRepository; private readonly PerforHospitalconfigRepository hospitalconfigRepository;
private readonly PerforExtypeRepository extypeRepository; private readonly PerforExtypeRepository extypeRepository;
...@@ -26,7 +26,7 @@ public class DictionaryService : IAutoInjection ...@@ -26,7 +26,7 @@ public class DictionaryService : IAutoInjection
public DictionaryService( public DictionaryService(
ILogger<DictionaryService> logger, ILogger<DictionaryService> logger,
QueryService queryService, QueryService queryService,
LogManageService logService, NotificationsService notificationsService,
PerforPeremployeeRepository peremployeeRepository, PerforPeremployeeRepository peremployeeRepository,
PerforHospitalconfigRepository hospitalconfigRepository, PerforHospitalconfigRepository hospitalconfigRepository,
PerforExtypeRepository extypeRepository, PerforExtypeRepository extypeRepository,
...@@ -37,7 +37,7 @@ PerforHisscriptRepository hisscriptRepository ...@@ -37,7 +37,7 @@ PerforHisscriptRepository hisscriptRepository
{ {
this.logger = logger; this.logger = logger;
this.queryService = queryService; this.queryService = queryService;
this.logService = logService; this.notificationsService = notificationsService;
this.peremployeeRepository = peremployeeRepository; this.peremployeeRepository = peremployeeRepository;
this.hospitalconfigRepository = hospitalconfigRepository; this.hospitalconfigRepository = hospitalconfigRepository;
this.extypeRepository = extypeRepository; this.extypeRepository = extypeRepository;
...@@ -46,7 +46,7 @@ PerforHisscriptRepository hisscriptRepository ...@@ -46,7 +46,7 @@ PerforHisscriptRepository hisscriptRepository
this.hisscriptRepository = hisscriptRepository; this.hisscriptRepository = hisscriptRepository;
} }
public void Handler(int hospitalId, per_allot allot, string groupName, bool isSingle) public void Handler(int hospitalId, per_allot allot)
{ {
try try
{ {
...@@ -56,7 +56,7 @@ public void Handler(int hospitalId, per_allot allot, string groupName, bool isSi ...@@ -56,7 +56,7 @@ public void Handler(int hospitalId, per_allot allot, string groupName, bool isSi
var types = extypeRepository.GetEntities(t => t.HospitalId == hospitalId && new int[] { 2 }.Contains(t.Source)); var types = extypeRepository.GetEntities(t => t.HospitalId == hospitalId && new int[] { 2 }.Contains(t.Source));
if (types != null && types.Any()) if (types != null && types.Any())
{ {
logService.ReturnTheLog(allot.ID, groupName, 2, "提取数据", $"提取人员信息数据", isSingle: isSingle); notificationsService.SendExtractMessage(allot.ID, "提取数据:提取人员信息数据。");
var scripts = exscriptRepository.GetEntities(t => types.Select(s => s.Id).Contains(t.TypeId) && t.IsEnable == 1); var scripts = exscriptRepository.GetEntities(t => types.Select(s => s.Id).Contains(t.TypeId) && t.IsEnable == 1);
if (scripts != null && scripts.Any()) if (scripts != null && scripts.Any())
{ {
......
...@@ -54,17 +54,19 @@ PerforPerdeptdicRepository perdeptdicRepository ...@@ -54,17 +54,19 @@ PerforPerdeptdicRepository perdeptdicRepository
/// </summary> /// </summary>
/// <param name="allotId">抽取绩效Id</param> /// <param name="allotId">抽取绩效Id</param>
/// <param name="hospitalId">医院Id</param> /// <param name="hospitalId">医院Id</param>
/// <param name="email">邮箱地址</param> /// <param name="userId">用户Id</param>
/// <param name="groupName">即时日志分组名称</param>
/// <param name="filePath">历史提交文件地址</param> /// <param name="filePath">历史提交文件地址</param>
/// <param name="isSingle">抽取是否在同一项目</param> /// <param name="isSingle">抽取是否在同一项目</param>
public string Main(int allotId, int hospitalId, string email, string groupName, string filePath = null, bool isSingle = false) public string Main(int allotId, int hospitalId, int userId, string filePath = null, bool isSingle = false)
{ {
string extractFilePath = ""; string extractFilePath = "";
per_allot allot = null; per_allot allot = null;
IWorkbook workbook = null; IWorkbook workbook = null;
try try
{ {
string key = NotificationsService.AllotExtractKeyPrefix + allot.ID;
notificationsService.SetCache(key, new SingleData(Guid.NewGuid().ToString("N"), userId, isSingle));
notificationsService.SendExtractMessage(allotId, "等待提取:确认配置信息是否可完成数据提取..."); notificationsService.SendExtractMessage(allotId, "等待提取:确认配置信息是否可完成数据提取...");
//logService.ClearExtractLog(allotId); //logService.ClearExtractLog(allotId);
...@@ -76,8 +78,8 @@ public string Main(int allotId, int hospitalId, string email, string groupName, ...@@ -76,8 +78,8 @@ public string Main(int allotId, int hospitalId, string email, string groupName,
var dict = new Dictionary<ExDataDict, object>(); var dict = new Dictionary<ExDataDict, object>();
notificationsService.SendExtractProgress(allotId, 5); notificationsService.SendExtractProgress(allotId, 5);
dictionaryService.Handler(hospitalId, allot, groupName, isSingle); dictionaryService.Handler(hospitalId, allot);
var data = queryService.Handler(hospitalId, allot, groupName, isSingle, ref dict); var data = queryService.Handler(hospitalId, allot, ref dict);
var standData = StandDataFormat(hospitalId, data); var standData = StandDataFormat(hospitalId, data);
var statesArray = new int[] { (int)AllotStates.GenerateSucceed, (int)AllotStates.Archive }; var statesArray = new int[] { (int)AllotStates.GenerateSucceed, (int)AllotStates.Archive };
...@@ -90,7 +92,7 @@ public string Main(int allotId, int hospitalId, string email, string groupName, ...@@ -90,7 +92,7 @@ public string Main(int allotId, int hospitalId, string email, string groupName,
workbook = ExcelHelper.GetWorkbook(templateFilePath); workbook = ExcelHelper.GetWorkbook(templateFilePath);
if (workbook == null) throw new PerformanceException("文件读取失败"); if (workbook == null) throw new PerformanceException("文件读取失败");
WriteDataToFile(workbook, allot, dict, standData, groupName, isSingle); WriteDataToFile(workbook, allot, dict, standData);
allot.IsExtracting = isSingle ? 2 : 0; allot.IsExtracting = isSingle ? 2 : 0;
allot.ExtractPath = extractFilePath; allot.ExtractPath = extractFilePath;
...@@ -126,7 +128,7 @@ public string Main(int allotId, int hospitalId, string email, string groupName, ...@@ -126,7 +128,7 @@ public string Main(int allotId, int hospitalId, string email, string groupName,
/// <param name="extractDto"></param> /// <param name="extractDto"></param>
/// <param name="groupName"></param> /// <param name="groupName"></param>
/// <param name="isSingle"></param> /// <param name="isSingle"></param>
private void WriteDataToFile(IWorkbook workbook, per_allot allot, Dictionary<ExDataDict, object> exdict, List<ExtractTransDto> extractDto, string groupName, bool isSingle) private void WriteDataToFile(IWorkbook workbook, per_allot allot, Dictionary<ExDataDict, object> exdict, List<ExtractTransDto> extractDto)
{ {
ExcelStyle style = new ExcelStyle(workbook); ExcelStyle style = new ExcelStyle(workbook);
......
using Microsoft.AspNetCore.SignalR; using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Performance.DtoModels; using Performance.DtoModels;
using Performance.EntityModels; using Performance.DtoModels.AppSettings;
using Performance.Infrastructure; using Performance.Infrastructure;
using Performance.Repository; using Performance.Repository;
using System; using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Performance.Services namespace Performance.Services
...@@ -17,22 +16,28 @@ public class NotificationsService : IAutoInjection ...@@ -17,22 +16,28 @@ public class NotificationsService : IAutoInjection
private readonly ILogger logger; private readonly ILogger logger;
private readonly IMemoryCache cache; private readonly IMemoryCache cache;
private readonly IHubContext<AllotLogHub> hubContext; private readonly IHubContext<AllotLogHub> hubContext;
private readonly WebapiUrl url;
private readonly PerforLogdsignalrRepository repository; private readonly PerforLogdsignalrRepository repository;
public NotificationsService( public NotificationsService(
ILogger<NotificationsService> logger, ILogger<NotificationsService> logger,
IMemoryCache cache, IMemoryCache cache,
IHubContext<AllotLogHub> hubContext, IHubContext<AllotLogHub> hubContext,
IOptions<WebapiUrl> url,
PerforLogdsignalrRepository repository PerforLogdsignalrRepository repository
) )
{ {
this.logger = logger; this.logger = logger;
this.cache = cache; this.cache = cache;
this.hubContext = hubContext; this.hubContext = hubContext;
this.url = url.Value;
this.repository = repository; this.repository = repository;
} }
/// <summary> 绩效生成 </summary>
public const string AllotGenerateKeyPrefix = "Allot-Generate-"; public const string AllotGenerateKeyPrefix = "Allot-Generate-";
/// <summary> 绩效提取 </summary>
public const string AllotExtractKeyPrefix = "Allot-Extract-"; public const string AllotExtractKeyPrefix = "Allot-Extract-";
public void SendGenerateMessage(int allotId, string message, ComponentType type = ComponentType.info) public void SendGenerateMessage(int allotId, string message, ComponentType type = ComponentType.info)
...@@ -52,7 +57,9 @@ public void SendExtractMessage(int allotId, string message, ComponentType type = ...@@ -52,7 +57,9 @@ public void SendExtractMessage(int allotId, string message, ComponentType type =
return; return;
var info = new MessageInfo(data.Uuid, allotId, "提取数据", message, Component.Notification, type); var info = new MessageInfo(data.Uuid, allotId, "提取数据", message, Component.Notification, type);
SendMessage(data.UserId, info);
if (data.IsSingle) SendMessage(data.UserId, info);
else SendMessageToSite(data.UserId, info);
} }
public void SendExtractProgress(int allotId, decimal percentage, ComponentType type = ComponentType.info) public void SendExtractProgress(int allotId, decimal percentage, ComponentType type = ComponentType.info)
...@@ -61,12 +68,13 @@ public void SendExtractProgress(int allotId, decimal percentage, ComponentType t ...@@ -61,12 +68,13 @@ public void SendExtractProgress(int allotId, decimal percentage, ComponentType t
if (data == null || data.UserId == 0) if (data == null || data.UserId == 0)
return; return;
percentage = type == ComponentType.success percentage = type == ComponentType.success ? 100
? 100
: (type != ComponentType.success && percentage >= 100) ? 99 : percentage; : (type != ComponentType.success && percentage >= 100) ? 99 : percentage;
var info = new MessageInfo(data.Uuid, allotId, "数据提取进度", percentage.ToString(), Component.Progress, type); var info = new MessageInfo(data.Uuid, allotId, "数据提取进度", percentage.ToString(), Component.Progress, type);
SendMessage(data.UserId, info);
if (data.IsSingle) SendMessage(data.UserId, info);
else SendMessageToSite(data.UserId, info);
} }
public void SendMessage(int userId, MessageInfo data) public void SendMessage(int userId, MessageInfo data)
...@@ -74,11 +82,8 @@ public void SendMessage(int userId, MessageInfo data) ...@@ -74,11 +82,8 @@ public void SendMessage(int userId, MessageInfo data)
string key = userId.ToString(); string key = userId.ToString();
if (cache.TryGetValue(key, out string connectionId) && !string.IsNullOrEmpty(connectionId)) if (cache.TryGetValue(key, out string connectionId) && !string.IsNullOrEmpty(connectionId))
{ {
if (data.Component == Component.Progress) string method = data.Component == Component.Notification ? "ReceiveMessage" : "ReceiveProgress";
{ SendMessageToClient(connectionId, data, method);
var percentage = ConvertHelper.To<decimal>(data.Message);
}
SendMessageToClient(connectionId, data);
} }
} }
...@@ -87,9 +92,26 @@ private void SaveLogToDataBase() ...@@ -87,9 +92,26 @@ private void SaveLogToDataBase()
} }
private void SendMessageToClient(string connectionId, MessageInfo data, string method = "ReceiveMessage") private void SendMessageToClient(string connectionId, MessageInfo info, string method)
{ {
hubContext.Clients.Client(connectionId).SendAsync(method, data.Title, data); hubContext.Clients.Client(connectionId).SendAsync(method, info.Title, info);
}
private void SendMessageToSite(int userId, MessageInfo info)
{
try
{
var http = new RestSharpHelper();
var importUrl = http.SetUrl(url.ImportFile, "template/returnlog/" + userId);
string json = JsonHelper.Serialize(info);
var request = http.CreatePostRequest(json);
Task.Run(() => http.GetResponse(importUrl, request));
}
catch (Exception ex)
{
logger.LogError("发送日志至绩效站点时发生异常:" + ex.Message);
}
} }
#region 缓存 #region 缓存
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment