Рефакторинг

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

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

View File

@ -50,6 +50,11 @@ namespace AsbCloudApp.Data
/// 2 - завершена
/// </summary>
public int IdState { get; set; }
/// <summary>
/// Название текущей секции
/// </summary>
public string? Section { get; set; }
/// <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.Services;
using AsbCloudApp.Services.Subsystems;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Background;
using AsbCloudInfrastructure.Services.SAUB;
using Mapster;
@ -65,7 +64,6 @@ namespace AsbCloudInfrastructure.Services
private static async Task WorkAction(string workName, IServiceProvider serviceProvider, CancellationToken token)
{
var db = serviceProvider.GetRequiredService<IAsbCloudDbContext>();
var wellService = serviceProvider.GetRequiredService<IWellService>();
var operationsStatService = serviceProvider.GetRequiredService<IOperationsStatService>();
var processMapRepository = serviceProvider.GetRequiredService<IProcessMapPlanRepository>();
@ -73,16 +71,11 @@ namespace AsbCloudInfrastructure.Services
var telemetryDataSaubCache = serviceProvider.GetRequiredService<TelemetryDataCache<TelemetryDataSaubDto>>();
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
.Select(w => w.Id);
var wellsIds = wells.Select(w => w.Id);
var idTelemetries = activeWells
.Where(w => w.IdTelemetry != null)
.Select(t => t.IdTelemetry);
var processMapRequests = activeWellsIds.Select(id => new ProcessMapRequest { IdWell = id });
var processMapRequests = wellsIds.Select(id => new ProcessMapRequest { IdWell = id });
var processMaps = await processMapRepository.GetProcessMapAsync(processMapRequests, token);
var wellDepthByProcessMap = processMaps
@ -93,11 +86,12 @@ namespace AsbCloudInfrastructure.Services
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>();
wellMapInfo.IdState = well.IdState;
@ -133,13 +127,14 @@ namespace AsbCloudInfrastructure.Services
else if(currentDepth.HasValue)
{
wellProcessMap = wellProcessMaps.FirstOrDefault(p => p.DepthStart <= currentDepth.Value && p.DepthEnd >= currentDepth.Value);
idSection ??= wellProcessMap?.IdWellSectionType;
}
double? planTotalDepth = null;
planTotalDepth = wellDepthByProcessMap.FirstOrDefault(p => p.Id == well.Id)?.DepthEnd;
planTotalDepth ??= wellOperationsStat?.Total.Plan?.WellDepthEnd;
wellMapInfo.Section = wellLastFactSection?.Caption;
wellMapInfo.FirstFactOperationDateStart = wellOperationsStat?.Total.Fact?.Start
?? wellOperationsStat?.Total.Plan?.Start;
@ -199,8 +194,9 @@ namespace AsbCloudInfrastructure.Services
return wellMapInfo;
}).ToArray();
var updateWellInfoEventTasks = activeWellsIds
.Select(idWell => messageHub.HandleAsync(new UpdateWellInfoEvent(idWell), token));
var updateWellInfoEventTasks = wellsIds.Select(idWell =>
messageHub.HandleAsync(new UpdateWellInfoEvent(idWell), token));
await Task.WhenAll(updateWellInfoEventTasks);
}

View File

@ -92,7 +92,7 @@ namespace AsbCloudInfrastructure.Services
Longitude = gCluster.Key.Longitude ?? gDeposit.Key.Longitude,
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.Latitude ??= gCluster.Key.Latitude ?? gDeposit.Key.Latitude;
dto.Longitude ??= gCluster.Key.Longitude ?? gDeposit.Key.Longitude;

View File

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

View File

@ -143,9 +143,8 @@ namespace AsbCloudWebApi
{
services.AddTransient<INotificationTransportService, SignalRNotificationTransportService>();
}
public static void AddIntegrationEvents(this IServiceCollection services) => services
.AddTransient<IIntegrationEventHandler<UpdateWellInfoEvent>, WellInfoHub>()
.AddTransient<IIntegrationEventHandler<UpdateWellEvent>, WellHub>();
.AddTransient<IIntegrationEventHandler<UpdateWellInfoEvent>, WellInfoHub>();
}
}

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 AsbCloudApp.IntegrationEvents;
using AsbCloudApp.IntegrationEvents.Interfaces;
using AsbCloudApp.Services;
using AsbCloudInfrastructure.Services;
using Microsoft.AspNetCore.SignalR;
@ -10,12 +11,15 @@ namespace AsbCloudWebApi.SignalR;
public class WellInfoHub : BaseHub, IIntegrationEventHandler<UpdateWellInfoEvent>
{
private readonly IHubContext<WellInfoHub> hubContext;
private readonly IWellService wellService;
private readonly WellInfoService wellInfoService;
public WellInfoHub(IHubContext<WellInfoHub> hubContext,
IWellService wellService,
WellInfoService wellInfoService)
{
this.hubContext = hubContext;
this.wellService = wellService;
this.wellInfoService = wellInfoService;
}
@ -32,12 +36,18 @@ public class WellInfoHub : BaseHub, IIntegrationEventHandler<UpdateWellInfoEvent
{
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;
var wellInfo = wellInfoService.FirstOrDefault(w => w.Id == well.Id);
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 =>
{
endpoints.MapControllers();
endpoints.MapHub<WellHub>("/hubs/well");
endpoints.MapHub<WellInfoHub>("/hubs/wellInfo");
endpoints.MapHub<NotificationHub>("/hubs/notifications");
endpoints.MapHub<TelemetryHub>("/hubs/telemetry");