Рефакторинг

1. Два хаба избыточно, объеденил всё в один хаб
2. Уведомление клиенту будет отправляться только при обновлении кэша в сервисе WellInfoService
3. В WellInfoService теперь формируется статистика по всем скважинам, а не только по активным
4. Небольшой рефакторинг
This commit is contained in:
Степанов Дмитрий 2023-08-24 10:50:34 +05:00
parent 54aebabdde
commit e0d3187ef2
10 changed files with 34 additions and 104 deletions

View File

@ -21,11 +21,6 @@ namespace AsbCloudApp.Data
/// </summary> /// </summary>
public string? Cluster { get; set; } public string? Cluster { get; set; }
/// <summary>
/// Название секции
/// </summary>
public string? Section { get; set; }
/// <summary> /// <summary>
/// Название месторождения /// Название месторождения
/// </summary> /// </summary>

View File

@ -51,6 +51,11 @@ namespace AsbCloudApp.Data
/// </summary> /// </summary>
public int IdState { get; set; } public int IdState { get; set; }
/// <summary>
/// Название текущей секции
/// </summary>
public string? Section { get; set; }
/// <summary> /// <summary>
/// Коэф-т использования автоподачи долота (суммарный ротор + слайд) /// Коэф-т использования автоподачи долота (суммарный ротор + слайд)
/// </summary> /// </summary>

View File

@ -1,9 +0,0 @@
using AsbCloudApp.IntegrationEvents.Interfaces;
namespace AsbCloudApp.IntegrationEvents;
/// <summary>
/// Обновление информации о скважине
/// </summary>
/// <param name="IdWell"></param>
public record UpdateWellEvent(int IdWell) : IIntegrationEvent;

View File

@ -6,7 +6,6 @@ using AsbCloudApp.Repositories;
using AsbCloudApp.Requests; using AsbCloudApp.Requests;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudApp.Services.Subsystems; using AsbCloudApp.Services.Subsystems;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Background; using AsbCloudInfrastructure.Background;
using AsbCloudInfrastructure.Services.SAUB; using AsbCloudInfrastructure.Services.SAUB;
using Mapster; using Mapster;
@ -65,7 +64,6 @@ namespace AsbCloudInfrastructure.Services
private static async Task WorkAction(string workName, IServiceProvider serviceProvider, CancellationToken token) private static async Task WorkAction(string workName, IServiceProvider serviceProvider, CancellationToken token)
{ {
var db = serviceProvider.GetRequiredService<IAsbCloudDbContext>();
var wellService = serviceProvider.GetRequiredService<IWellService>(); var wellService = serviceProvider.GetRequiredService<IWellService>();
var operationsStatService = serviceProvider.GetRequiredService<IOperationsStatService>(); var operationsStatService = serviceProvider.GetRequiredService<IOperationsStatService>();
var processMapRepository = serviceProvider.GetRequiredService<IProcessMapPlanRepository>(); var processMapRepository = serviceProvider.GetRequiredService<IProcessMapPlanRepository>();
@ -73,16 +71,11 @@ namespace AsbCloudInfrastructure.Services
var telemetryDataSaubCache = serviceProvider.GetRequiredService<TelemetryDataCache<TelemetryDataSaubDto>>(); var telemetryDataSaubCache = serviceProvider.GetRequiredService<TelemetryDataCache<TelemetryDataSaubDto>>();
var messageHub = serviceProvider.GetRequiredService<IIntegrationEventHandler<UpdateWellInfoEvent>>(); var messageHub = serviceProvider.GetRequiredService<IIntegrationEventHandler<UpdateWellInfoEvent>>();
var activeWells = await wellService.GetAsync(new() {IdState = 1}, token); var wells = await wellService.GetAllAsync(token);
IEnumerable<int> activeWellsIds = activeWells var wellsIds = wells.Select(w => w.Id);
.Select(w => w.Id);
var idTelemetries = activeWells var processMapRequests = wellsIds.Select(id => new ProcessMapRequest { IdWell = id });
.Where(w => w.IdTelemetry != null)
.Select(t => t.IdTelemetry);
var processMapRequests = activeWellsIds.Select(id => new ProcessMapRequest { IdWell = id });
var processMaps = await processMapRepository.GetProcessMapAsync(processMapRequests, token); var processMaps = await processMapRepository.GetProcessMapAsync(processMapRequests, token);
var wellDepthByProcessMap = processMaps var wellDepthByProcessMap = processMaps
@ -93,11 +86,12 @@ namespace AsbCloudInfrastructure.Services
DepthEnd = g.Max(p => p.DepthEnd) DepthEnd = g.Max(p => p.DepthEnd)
}); });
var operationsStat = await operationsStatService.GetWellsStatAsync(activeWellsIds, token); var operationsStat = await operationsStatService.GetWellsStatAsync(wellsIds, token);
var subsystemStat = await subsystemOperationTimeService.GetStatByActiveWells(activeWellsIds, token); var subsystemStat = await subsystemOperationTimeService
.GetStatByActiveWells(wellsIds, token);
WellMapInfo = activeWells.Select(well => { WellMapInfo = wells.Select(well => {
var wellMapInfo = well.Adapt<WellMapInfoWithComanies>(); var wellMapInfo = well.Adapt<WellMapInfoWithComanies>();
wellMapInfo.IdState = well.IdState; wellMapInfo.IdState = well.IdState;
@ -133,13 +127,14 @@ namespace AsbCloudInfrastructure.Services
else if(currentDepth.HasValue) else if(currentDepth.HasValue)
{ {
wellProcessMap = wellProcessMaps.FirstOrDefault(p => p.DepthStart <= currentDepth.Value && p.DepthEnd >= currentDepth.Value); wellProcessMap = wellProcessMaps.FirstOrDefault(p => p.DepthStart <= currentDepth.Value && p.DepthEnd >= currentDepth.Value);
idSection ??= wellProcessMap?.IdWellSectionType;
} }
double? planTotalDepth = null; double? planTotalDepth = null;
planTotalDepth = wellDepthByProcessMap.FirstOrDefault(p => p.Id == well.Id)?.DepthEnd; planTotalDepth = wellDepthByProcessMap.FirstOrDefault(p => p.Id == well.Id)?.DepthEnd;
planTotalDepth ??= wellOperationsStat?.Total.Plan?.WellDepthEnd; planTotalDepth ??= wellOperationsStat?.Total.Plan?.WellDepthEnd;
wellMapInfo.Section = wellLastFactSection?.Caption;
wellMapInfo.FirstFactOperationDateStart = wellOperationsStat?.Total.Fact?.Start wellMapInfo.FirstFactOperationDateStart = wellOperationsStat?.Total.Fact?.Start
?? wellOperationsStat?.Total.Plan?.Start; ?? wellOperationsStat?.Total.Plan?.Start;
@ -199,8 +194,9 @@ namespace AsbCloudInfrastructure.Services
return wellMapInfo; return wellMapInfo;
}).ToArray(); }).ToArray();
var updateWellInfoEventTasks = activeWellsIds var updateWellInfoEventTasks = wellsIds.Select(idWell =>
.Select(idWell => messageHub.HandleAsync(new UpdateWellInfoEvent(idWell), token)); messageHub.HandleAsync(new UpdateWellInfoEvent(idWell), token));
await Task.WhenAll(updateWellInfoEventTasks); await Task.WhenAll(updateWellInfoEventTasks);
} }

View File

@ -92,7 +92,7 @@ namespace AsbCloudInfrastructure.Services
Longitude = gCluster.Key.Longitude ?? gDeposit.Key.Longitude, Longitude = gCluster.Key.Longitude ?? gDeposit.Key.Longitude,
Wells = gCluster.Select(well => Wells = gCluster.Select(well =>
{ {
var dto = wellInfoService.FirstOrDefault(w => w.Id == well.Id); var dto = wellInfoService.FirstOrDefault(w => w.Id == well.Id && well.IdState == 1);
dto ??= well.Adapt<WellMapInfoWithTelemetryStat>(); dto ??= well.Adapt<WellMapInfoWithTelemetryStat>();
dto.Latitude ??= gCluster.Key.Latitude ?? gDeposit.Key.Latitude; dto.Latitude ??= gCluster.Key.Latitude ?? gDeposit.Key.Latitude;
dto.Longitude ??= gCluster.Key.Longitude ?? gDeposit.Key.Longitude; dto.Longitude ??= gCluster.Key.Longitude ?? gDeposit.Key.Longitude;

View File

@ -11,8 +11,6 @@ using System.ComponentModel.DataAnnotations;
using System.IO; using System.IO;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using AsbCloudApp.IntegrationEvents;
using AsbCloudApp.IntegrationEvents.Interfaces;
namespace AsbCloudWebApi.Controllers namespace AsbCloudWebApi.Controllers
{ {
@ -25,17 +23,14 @@ namespace AsbCloudWebApi.Controllers
[Authorize] [Authorize]
public class WellOperationController : ControllerBase public class WellOperationController : ControllerBase
{ {
private readonly IIntegrationEventHandler<UpdateWellEvent> eventHandler;
private readonly IWellOperationRepository operationRepository; private readonly IWellOperationRepository operationRepository;
private readonly IWellService wellService; private readonly IWellService wellService;
private readonly IWellOperationImportService wellOperationImportService; private readonly IWellOperationImportService wellOperationImportService;
public WellOperationController(IIntegrationEventHandler<UpdateWellEvent> eventHandler, public WellOperationController(IWellOperationRepository operationRepository,
IWellOperationRepository operationRepository,
IWellService wellService, IWellService wellService,
IWellOperationImportService wellOperationImportService) IWellOperationImportService wellOperationImportService)
{ {
this.eventHandler = eventHandler;
this.operationRepository = operationRepository; this.operationRepository = operationRepository;
this.wellService = wellService; this.wellService = wellService;
this.wellOperationImportService = wellOperationImportService; this.wellOperationImportService = wellOperationImportService;
@ -219,8 +214,6 @@ namespace AsbCloudWebApi.Controllers
var result = await operationRepository.InsertRangeAsync(values, token) var result = await operationRepository.InsertRangeAsync(values, token)
.ConfigureAwait(false); .ConfigureAwait(false);
await eventHandler.HandleAsync(new UpdateWellEvent(idWell), token);
return Ok(result); return Ok(result);
} }
@ -316,8 +309,6 @@ namespace AsbCloudWebApi.Controllers
return BadRequest(ex.Message); return BadRequest(ex.Message);
} }
await eventHandler.HandleAsync(new UpdateWellEvent(idWell), token);
return Ok(); return Ok();
} }

View File

@ -145,7 +145,6 @@ namespace AsbCloudWebApi
} }
public static void AddIntegrationEvents(this IServiceCollection services) => services public static void AddIntegrationEvents(this IServiceCollection services) => services
.AddTransient<IIntegrationEventHandler<UpdateWellInfoEvent>, WellInfoHub>() .AddTransient<IIntegrationEventHandler<UpdateWellInfoEvent>, WellInfoHub>();
.AddTransient<IIntegrationEventHandler<UpdateWellEvent>, WellHub>();
} }
} }

View File

@ -1,56 +0,0 @@
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.IntegrationEvents;
using AsbCloudApp.IntegrationEvents.Interfaces;
using AsbCloudApp.Repositories;
using AsbCloudApp.Requests;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using Microsoft.AspNetCore.SignalR;
namespace AsbCloudWebApi.SignalR;
public class WellHub : BaseHub, IIntegrationEventHandler<UpdateWellEvent>
{
private readonly IHubContext<WellHub> hubContext;
private readonly IWellService wellService;
private readonly IWellOperationRepository wellOperationRepository;
public WellHub(IHubContext<WellHub> hubContext,
IWellService wellService,
IWellOperationRepository wellOperationRepository)
{
this.hubContext = hubContext;
this.wellService = wellService;
this.wellOperationRepository = wellOperationRepository;
}
public override async Task AddToGroup(string groupName)
{
var idWell = int.Parse(groupName.Split('_')[1]);
await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
await HandleAsync(new UpdateWellEvent(idWell), CancellationToken.None);
}
public async Task HandleAsync(UpdateWellEvent integrationEvent, CancellationToken cancellationToken)
{
const string method = "update_well";
var well = await wellService.GetOrDefaultAsync(integrationEvent.IdWell, cancellationToken);
if(well is null)
return;
well.Section = (await wellOperationRepository.GetAsync(new WellOperationRequest
{
IdWell = integrationEvent.IdWell,
OperationType = WellOperation.IdOperationTypeFact
}, cancellationToken)).MaxBy(o => o.DateStart)?.WellSectionTypeName;
await hubContext.Clients.Group($"well_{integrationEvent.IdWell}")
.SendAsync(method, new object[] { well }, cancellationToken);
}
}

View File

@ -2,6 +2,7 @@ using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using AsbCloudApp.IntegrationEvents; using AsbCloudApp.IntegrationEvents;
using AsbCloudApp.IntegrationEvents.Interfaces; using AsbCloudApp.IntegrationEvents.Interfaces;
using AsbCloudApp.Services;
using AsbCloudInfrastructure.Services; using AsbCloudInfrastructure.Services;
using Microsoft.AspNetCore.SignalR; using Microsoft.AspNetCore.SignalR;
@ -10,12 +11,15 @@ namespace AsbCloudWebApi.SignalR;
public class WellInfoHub : BaseHub, IIntegrationEventHandler<UpdateWellInfoEvent> public class WellInfoHub : BaseHub, IIntegrationEventHandler<UpdateWellInfoEvent>
{ {
private readonly IHubContext<WellInfoHub> hubContext; private readonly IHubContext<WellInfoHub> hubContext;
private readonly IWellService wellService;
private readonly WellInfoService wellInfoService; private readonly WellInfoService wellInfoService;
public WellInfoHub(IHubContext<WellInfoHub> hubContext, public WellInfoHub(IHubContext<WellInfoHub> hubContext,
IWellService wellService,
WellInfoService wellInfoService) WellInfoService wellInfoService)
{ {
this.hubContext = hubContext; this.hubContext = hubContext;
this.wellService = wellService;
this.wellInfoService = wellInfoService; this.wellInfoService = wellInfoService;
} }
@ -32,12 +36,18 @@ public class WellInfoHub : BaseHub, IIntegrationEventHandler<UpdateWellInfoEvent
{ {
const string method = "update_well_info"; const string method = "update_well_info";
var wellInfo = wellInfoService.FirstOrDefault(w => w.Id == integrationEvent.IdWell); var well = await wellService.GetOrDefaultAsync(integrationEvent.IdWell, cancellationToken);
if (wellInfo is null) if(well is null)
return; return;
var wellInfo = wellInfoService.FirstOrDefault(w => w.Id == well.Id);
await hubContext.Clients.Group($"well_info_{integrationEvent.IdWell}") await hubContext.Clients.Group($"well_info_{integrationEvent.IdWell}")
.SendAsync(method, wellInfo, cancellationToken); .SendAsync(method, new
{
Well = well,
WellInfo = wellInfo
}, cancellationToken);
} }
} }

View File

@ -153,7 +153,6 @@ namespace AsbCloudWebApi
app.UseEndpoints(endpoints => app.UseEndpoints(endpoints =>
{ {
endpoints.MapControllers(); endpoints.MapControllers();
endpoints.MapHub<WellHub>("/hubs/well");
endpoints.MapHub<WellInfoHub>("/hubs/wellInfo"); endpoints.MapHub<WellInfoHub>("/hubs/wellInfo");
endpoints.MapHub<NotificationHub>("/hubs/notifications"); endpoints.MapHub<NotificationHub>("/hubs/notifications");
endpoints.MapHub<TelemetryHub>("/hubs/telemetry"); endpoints.MapHub<TelemetryHub>("/hubs/telemetry");