IWellService refactor.

- Add #nullable,
- Add WellRequest,
- Remove obsolete method
This commit is contained in:
ngfrolov 2023-02-15 17:57:32 +05:00
parent 40076f0ec2
commit fda5385e46
Signed by untrusted user who does not match committer: ng.frolov
GPG Key ID: E99907A0357B29A7
9 changed files with 144 additions and 58 deletions

View File

@ -0,0 +1,20 @@
namespace AsbCloudApp.Requests
{
#nullable enable
/// <summary>
/// Запрос на получение скважин
/// </summary>
public class WellRequest
{
/// <summary>
/// id компании
/// </summary>
public int? IdCompany { get; set; }
/// <summary>
/// id состояния
/// </summary>
public int? IdState { get; set; }
}
#nullable disable
}

View File

@ -1,11 +1,14 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Requests;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace AsbCloudApp.Services namespace AsbCloudApp.Services
{ {
#nullable enable
/// <summary> /// <summary>
/// сервис скважин /// сервис скважин
/// </summary> /// </summary>
@ -19,10 +22,10 @@ namespace AsbCloudApp.Services
/// <summary> /// <summary>
/// Список скважин доступных компании /// Список скважин доступных компании
/// </summary> /// </summary>
/// <param name="idCompany"></param> /// <param name="request"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
Task<IEnumerable<WellDto>> GetWellsByCompanyAsync(int idCompany, CancellationToken token); Task<IEnumerable<WellDto>> GetAsync(WellRequest request, CancellationToken token);
/// <summary> /// <summary>
/// проверяет доступ к скважине для компании /// проверяет доступ к скважине для компании
@ -33,14 +36,6 @@ namespace AsbCloudApp.Services
/// <returns></returns> /// <returns></returns>
Task<bool> IsCompanyInvolvedInWellAsync(int idCompany, int idWell, CancellationToken token); Task<bool> IsCompanyInvolvedInWellAsync(int idCompany, int idWell, CancellationToken token);
/// <summary>
/// проверяет доступ к скважине для компании
/// </summary>
/// <param name="idCompany"></param>
/// <param name="idWell"></param>
/// <returns></returns>
bool IsCompanyInvolvedInWell(int idCompany, int idWell);
/// <summary> /// <summary>
/// получить название скважины по id /// получить название скважины по id
/// </summary> /// </summary>
@ -101,5 +96,15 @@ namespace AsbCloudApp.Services
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
Task EnshureTimezonesIsSetAsync(CancellationToken token); Task EnshureTimezonesIsSetAsync(CancellationToken token);
/// <summary>
/// ВРЕМЕННЫЙ метод
/// </summary>
/// <param name="idCompany"></param>
/// <param name="token"></param>
/// <returns></returns>
#warning GetWellTreeAsync(..) is dummy. Remove it before pullrequest.
Task<IEnumerable<DepositBranchDto>> GetWellTreeAsync(int idCompany, CancellationToken token);
} }
#nullable disable
} }

View File

@ -75,7 +75,7 @@ namespace AsbCloudInfrastructure.Repository
/// <inheritdoc/> /// <inheritdoc/>
public async Task<IEnumerable<TelemetryWirelineRunOutDto>> GetAllAsync(int idCompany, CancellationToken token) public async Task<IEnumerable<TelemetryWirelineRunOutDto>> GetAllAsync(int idCompany, CancellationToken token)
{ {
var wells = await wellService.GetWellsByCompanyAsync(idCompany, token) var wells = await wellService.GetAsync(new() { IdCompany = idCompany }, token)
.ConfigureAwait(false); .ConfigureAwait(false);
var result = new List<TelemetryWirelineRunOutDto>(wells.Count()); var result = new List<TelemetryWirelineRunOutDto>(wells.Count());

View File

@ -190,7 +190,7 @@ namespace AsbCloudInfrastructure.Services.Subsystems
private async Task<IEnumerable<WellDto>> GetActiveWellsByCompany(int idCompany, CancellationToken token) private async Task<IEnumerable<WellDto>> GetActiveWellsByCompany(int idCompany, CancellationToken token)
{ {
var listWell = await wellService.GetWellsByCompanyAsync(idCompany, token); var listWell = await wellService.GetAsync(new() { IdCompany = idCompany }, token);
var active = listWell.Where(w => w.IdState == 1); var active = listWell.Where(w => w.IdState == 1);
return active; return active;
} }

View File

@ -27,7 +27,7 @@ namespace AsbCloudInfrastructure.Services.WellOperationService
public async Task<StatClusterDto> GetStatClusterAsync(int idCluster, int idCompany, CancellationToken token = default) public async Task<StatClusterDto> GetStatClusterAsync(int idCluster, int idCompany, CancellationToken token = default)
{ {
var allWellsByCompany = await wellService.GetWellsByCompanyAsync(idCompany, token).ConfigureAwait(false); var allWellsByCompany = await wellService.GetAsync(new() { IdCompany = idCompany }, token).ConfigureAwait(false);
var idWellsByCompany = allWellsByCompany.Select(w => w.Id).Distinct(); var idWellsByCompany = allWellsByCompany.Select(w => w.Id).Distinct();

View File

@ -1,6 +1,7 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Exceptions; using AsbCloudApp.Exceptions;
using AsbCloudApp.Repositories; using AsbCloudApp.Repositories;
using AsbCloudApp.Requests;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.EfCache; using AsbCloudInfrastructure.EfCache;
@ -16,6 +17,7 @@ using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services namespace AsbCloudInfrastructure.Services
{ {
#nullable enable
public class WellService : CrudCacheRepositoryBase<WellDto, Well>, IWellService public class WellService : CrudCacheRepositoryBase<WellDto, Well>, IWellService
{ {
private const string relationCompaniesWellsCacheTag = "RelationCompaniesWells"; private const string relationCompaniesWellsCacheTag = "RelationCompaniesWells";
@ -47,12 +49,6 @@ namespace AsbCloudInfrastructure.Services
companyTypesService = new CrudCacheRepositoryBase<CompanyTypeDto, CompanyType>(dbContext, memoryCache); companyTypesService = new CrudCacheRepositoryBase<CompanyTypeDto, CompanyType>(dbContext, memoryCache);
} }
private IEnumerable<RelationCompanyWell> GetCacheRelationCompanyWell()
=> dbContext.RelationCompaniesWells
.Include(r => r.Company)
.Include(r => r.Well)
.FromCache(relationCompaniesWellsCacheTag, relationCompaniesWellsCacheObsolence);
private Task<IEnumerable<RelationCompanyWell>> GetCacheRelationCompanyWellAsync(CancellationToken token) private Task<IEnumerable<RelationCompanyWell>> GetCacheRelationCompanyWellAsync(CancellationToken token)
=> dbContext.RelationCompaniesWells => dbContext.RelationCompaniesWells
.Include(r => r.Company) .Include(r => r.Company)
@ -73,21 +69,67 @@ namespace AsbCloudInfrastructure.Services
return lastTelemetryDate; return lastTelemetryDate;
} }
public async Task<IEnumerable<WellDto>> GetWellsByCompanyAsync(int idCompany, CancellationToken token) #warning GetWellTreeAsync(..) is dummy. Remove it before pullrequest.
public async Task<IEnumerable<DepositBranchDto>> GetWellTreeAsync(int idCompany, CancellationToken token)
{ {
var relationsCache = await GetCacheRelationCompanyWellAsync(token); var wells = await GetEntitiesAsync(new() { IdCompany = idCompany }, token);
var wellsIds = relationsCache var groupedWells = wells
.Where(r => r.IdCompany == idCompany) .GroupBy(w => w.Cluster)
.Select(r => r.IdWell); .GroupBy(g => g.Key.Deposit);
var wellsDtos = (await GetCacheAsync(token)) var depositTree = groupedWells.Select(
.Where(w => wellsIds.Contains(w.Id)) gDeposit => new DepositBranchDto
.Select(Convert); {
Id = gDeposit.Key.Id,
Caption = gDeposit.Key.Caption,
Latitude = gDeposit.Key.Latitude,
Longitude = gDeposit.Key.Longitude,
Clusters = gDeposit.Select(gCluster => new ClusterBranchDto
{
Id = gCluster.Key.Id,
Caption = gCluster.Key.Caption,
Latitude = gCluster.Key.Latitude ?? gDeposit.Key.Latitude,
Longitude = gCluster.Key.Longitude ?? gDeposit.Key.Longitude,
Wells = gCluster.Select(well =>
{
var dto = well.Adapt<WellMapInfoDto>();
if (dto.Latitude is null)
dto.Latitude = gCluster.Key.Latitude ?? gDeposit.Key.Latitude;
if (dto.Longitude is null)
dto.Longitude = gCluster.Key.Longitude ?? gDeposit.Key.Longitude;
if (well.IdTelemetry is not null)
dto.LastTelemetryDate = telemetryService.GetLastTelemetryDate(well.IdTelemetry.Value);
return dto;
}),
}),
});
return depositTree;
}
public async Task<IEnumerable<WellDto>> GetAsync(WellRequest request, CancellationToken token)
{
var wells = await GetEntitiesAsync(request, token);
var wellsDtos = wells.Select(Convert);
return wellsDtos; return wellsDtos;
} }
private async Task<IEnumerable<Well>> GetEntitiesAsync(WellRequest request, CancellationToken token)
{
var wells = await GetCacheAsync(token);
if (request.IdCompany.HasValue)
wells = wells.Where(well => well.RelationCompaniesWells.Any(r => r.IdCompany == request.IdCompany.Value));
if (request.IdState.HasValue)
wells = wells.Where(well => well.IdState == request.IdState.Value);
return wells;
}
public override async Task<int> InsertAsync(WellDto dto, CancellationToken token = default) public override async Task<int> InsertAsync(WellDto dto, CancellationToken token = default)
{ {
if (dto.IdWellType is < 1 or > 2) if (dto.IdWellType is < 1 or > 2)
@ -146,10 +188,6 @@ namespace AsbCloudInfrastructure.Services
return result; return result;
} }
public bool IsCompanyInvolvedInWell(int idCompany, int idWell)
=> GetCacheRelationCompanyWell()
.Any(r => r.IdWell == idWell && r.IdCompany == idCompany);
public async Task<bool> IsCompanyInvolvedInWellAsync(int idCompany, int idWell, CancellationToken token) public async Task<bool> IsCompanyInvolvedInWellAsync(int idCompany, int idWell, CancellationToken token)
=> (await GetCacheRelationCompanyWellAsync(token)) => (await GetCacheRelationCompanyWellAsync(token))
.Any(r => r.IdWell == idWell && r.IdCompany == idCompany); .Any(r => r.IdWell == idWell && r.IdCompany == idCompany);
@ -183,7 +221,7 @@ namespace AsbCloudInfrastructure.Services
var well = await GetOrDefaultAsync(idWell, token); var well = await GetOrDefaultAsync(idWell, token);
if (well is null) if (well is null)
return null; return Enumerable.Empty<int>();
var cache = await GetCacheAsync(token); var cache = await GetCacheAsync(token);
@ -209,9 +247,6 @@ namespace AsbCloudInfrastructure.Services
protected override WellDto Convert(Well entity) protected override WellDto Convert(Well entity)
{ {
if (entity is null)
return null;
var dto = base.Convert(entity); var dto = base.Convert(entity);
if (entity.Timezone is null) if (entity.Timezone is null)
@ -233,7 +268,8 @@ namespace AsbCloudInfrastructure.Services
{ {
var dto = entity.Adapt<CompanyDto>(); var dto = entity.Adapt<CompanyDto>();
dto.CompanyTypeCaption = entity.CompanyType?.Caption dto.CompanyTypeCaption = entity.CompanyType?.Caption
?? companyTypesService.GetOrDefault(entity.IdCompanyType).Caption; ?? companyTypesService.GetOrDefault(entity.IdCompanyType)?.Caption
?? string.Empty;
return dto; return dto;
} }
@ -278,6 +314,9 @@ namespace AsbCloudInfrastructure.Services
} }
var well = GetQuery().FirstOrDefault(w => w.Id == wellDto.Id); var well = GetQuery().FirstOrDefault(w => w.Id == wellDto.Id);
if (well is not null)
{
var point = GetCoordinates(well); var point = GetCoordinates(well);
if (point is not null) if (point is not null)
{ {
@ -288,13 +327,14 @@ namespace AsbCloudInfrastructure.Services
if (point.Latitude is not null & point.Longitude is not null) if (point.Latitude is not null & point.Longitude is not null)
{ {
var timezone = timezoneService.GetByCoordinates((double)point.Latitude, (double)point.Longitude); var timezone = timezoneService.GetByCoordinates(point.Latitude!.Value, point.Longitude!.Value);
if (timezone is not null) if (timezone is not null)
{ {
return timezone; return timezone;
} }
} }
} }
}
throw new Exception($"Can't find timezone for well {wellDto.Caption} id: {wellDto.Id}"); throw new Exception($"Can't find timezone for well {wellDto.Caption} id: {wellDto.Id}");
} }
@ -338,4 +378,5 @@ namespace AsbCloudInfrastructure.Services
return telemetryService.GetDatesRange((int)well.IdTelemetry); return telemetryService.GetDatesRange((int)well.IdTelemetry);
} }
} }
#nullable disable
} }

View File

@ -44,7 +44,7 @@ namespace AsbCloudWebApi.Controllers
if (idCompany is null) if (idCompany is null)
return Forbid(); return Forbid();
var wells = await wellService.GetWellsByCompanyAsync((int)idCompany, token); var wells = await wellService.GetAsync(new() { IdCompany = idCompany }, token);
if (!wells.Any()) if (!wells.Any())
return NoContent(); return NoContent();

View File

@ -107,9 +107,15 @@ namespace AsbCloudWebApi.Controllers
[Route("wellsStats")] [Route("wellsStats")]
[Permission] [Permission]
[ProducesResponseType(typeof(IEnumerable<StatWellDto>), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(IEnumerable<StatWellDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetWellsStatAsync([FromQuery] IEnumerable<int> idWells, CancellationToken token = default) public async Task<IActionResult> GetWellsStatAsync([FromQuery] IEnumerable<int> idWells, CancellationToken token)
{ {
var protectedIdWells = idWells.Where(CanUserAccessToWell); int? idCompany = User.GetCompanyId();
if (idCompany is null)
return Forbid();
var allowedWells = await wellService.GetAsync(new() { IdCompany = idCompany }, token);
var protectedIdWells = idWells.Where(id => allowedWells.Any(allowed => allowed.Id == id));
var result = await operationsStatService.GetWellsStatAsync(protectedIdWells, token) var result = await operationsStatService.GetWellsStatAsync(protectedIdWells, token)
.ConfigureAwait(false); .ConfigureAwait(false);
return Ok(result); return Ok(result);
@ -157,12 +163,6 @@ namespace AsbCloudWebApi.Controllers
return Ok(result); return Ok(result);
} }
private bool CanUserAccessToWell(int idWell)
{
int? idCompany = User.GetCompanyId();
return idCompany is not null && wellService.IsCompanyInvolvedInWell((int)idCompany, idWell);
}
private async Task<bool> CanUserAccessToWellAsync(int idWell, CancellationToken token = default) private async Task<bool> CanUserAccessToWellAsync(int idWell, CancellationToken token = default)
{ {
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();

View File

@ -38,7 +38,27 @@ namespace AsbCloudWebApi.Controllers
if (idCompany is null) if (idCompany is null)
return NoContent(); return NoContent();
var wells = await wellService.GetWellsByCompanyAsync((int)idCompany, var wells = await wellService.GetAsync(new() { IdCompany = idCompany },
token).ConfigureAwait(false);
return Ok(wells);
}
/// <summary>
/// Возвращает список доступных скважин
/// </summary>
/// <param name="token"> Токен отмены задачи </param>
/// <returns>Список скважин</returns>
[HttpGet("wellTree")]
[ProducesResponseType(typeof(IEnumerable<DepositBranchDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetWellTreeAsync(CancellationToken token = default)
{
var idCompany = User.GetCompanyId();
if (idCompany is null)
return NoContent();
var wells = await wellService.GetWellTreeAsync((int)idCompany,
token).ConfigureAwait(false); token).ConfigureAwait(false);
return Ok(wells); return Ok(wells);