Рефакторинг wellOperationRepository (продолжение)

This commit is contained in:
Olga Nemt 2024-04-22 11:16:23 +05:00
parent 4a878f5124
commit 0ba1b5c5fc
2 changed files with 81 additions and 115 deletions

View File

@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace AsbCloudApp.Requests; namespace AsbCloudApp.Requests;
@ -8,44 +9,44 @@ namespace AsbCloudApp.Requests;
/// </summary> /// </summary>
public class WellOperationRequestBase : RequestBase public class WellOperationRequestBase : RequestBase
{ {
/// <summary> /// <summary>
/// Больше или равно дате начала операции /// Больше или равно дате начала операции
/// </summary> /// </summary>
public DateTimeOffset? GeDate { get; set; } public DateTimeOffset? GeDate { get; set; }
/// <summary> /// <summary>
/// Меньше или равно дате окончания операции /// Меньше или равно дате окончания операции
/// </summary> /// </summary>
public DateTimeOffset? LeDate { get; set; } public DateTimeOffset? LeDate { get; set; }
/// <summary> /// <summary>
/// Больше или равно глубины скважины на начало операции. /// Больше или равно глубины скважины на начало операции.
/// </summary> /// </summary>
public double? GeDepth { get; set; } public double? GeDepth { get; set; }
/// <summary> /// <summary>
/// Меньше или равно глубины скважины на конец операции. /// Меньше или равно глубины скважины на конец операции.
/// </summary> /// </summary>
public double? LeDepth { get; set; } public double? LeDepth { get; set; }
/// <summary> /// <summary>
/// Идентификаторы категорий операции /// Идентификаторы категорий операции
/// </summary> /// </summary>
public IEnumerable<int>? OperationCategoryIds { get; set; } public IEnumerable<int>? OperationCategoryIds { get; set; }
/// <summary> /// <summary>
/// Тип операций /// Тип операций
/// <list type="bullet"> /// <list type="bullet">
/// <item>0 - плановая операция</item> /// <item>0 - плановая операция</item>
/// <item>1 - фактическая операция</item> /// <item>1 - фактическая операция</item>
/// </list> /// </list>
/// </summary> /// </summary>
public int? OperationType { get; set; } public int? OperationType { get; set; }
/// <summary> /// <summary>
/// Идентификаторы конструкций секции /// Идентификаторы конструкций секции
/// </summary> /// </summary>
public IEnumerable<int>? SectionTypeIds { get; set; } public IEnumerable<int>? SectionTypeIds { get; set; }
} }
/// <summary> /// <summary>
@ -53,32 +54,34 @@ public class WellOperationRequestBase : RequestBase
/// </summary> /// </summary>
public class WellOperationRequest : WellOperationRequestBase public class WellOperationRequest : WellOperationRequestBase
{ {
/// <inheritdoc /> /// <inheritdoc />
public WellOperationRequest(IEnumerable<int> idsWell) public WellOperationRequest(IEnumerable<int> idsWell)
{ {
IdsWell = idsWell; IdsWell = idsWell;
} }
/// <inheritdoc /> /// <inheritdoc />
public WellOperationRequest(WellOperationRequestBase request, IEnumerable<int> idsWell) public WellOperationRequest(WellOperationRequestBase request, IEnumerable<int> idsWell)
: this(idsWell) : this(idsWell)
{ {
GeDepth = request.GeDepth; GeDepth = request.GeDepth;
LeDepth = request.LeDepth; LeDepth = request.LeDepth;
GeDate = request.GeDate; GeDate = request.GeDate;
LeDate = request.LeDate; LeDate = request.LeDate;
OperationCategoryIds = request.OperationCategoryIds; OperationCategoryIds = request.OperationCategoryIds;
OperationType = request.OperationType; OperationType = request.OperationType;
SectionTypeIds = request.SectionTypeIds; SectionTypeIds = request.SectionTypeIds;
Skip = request.Skip; Skip = request.Skip;
Take = request.Take; Take = request.Take;
SortFields = request.SortFields; SortFields = request.SortFields;
} }
/// <summary> /// <summary>
/// Идентификаторы скважин /// Идентификаторы скважин
/// </summary> /// </summary>
public IEnumerable<int> IdsWell { get; } [Required]
[Length(1, 1)]
public IEnumerable<int> IdsWell { get; }
} }

View File

@ -28,8 +28,7 @@ public class WellOperationRepository : CrudRepositoryBase<WellOperationDto, Well
IMemoryCache memoryCache, IMemoryCache memoryCache,
IWellOperationCategoryRepository wellOperationCategoryRepository, IWellOperationCategoryRepository wellOperationCategoryRepository,
IWellService wellService) IWellService wellService)
: base(context, dbSet => dbSet.Include(e => e.WellSectionType) : base(context, dbSet => dbSet)
.Include(e => e.OperationCategory))
{ {
this.memoryCache = memoryCache; this.memoryCache = memoryCache;
this.wellOperationCategoryRepository = wellOperationCategoryRepository; this.wellOperationCategoryRepository = wellOperationCategoryRepository;
@ -44,7 +43,7 @@ public class WellOperationRepository : CrudRepositoryBase<WellOperationDto, Well
public async Task<IEnumerable<WellOperationDto>> GetAsync(WellOperationRequest request, CancellationToken token) public async Task<IEnumerable<WellOperationDto>> GetAsync(WellOperationRequest request, CancellationToken token)
{ {
var (items, _) = await GetPrivateAsync(request, token); var (items, _) = await GetAsyncWithDaysAndNpv(request, token);
return items; return items;
} }
@ -53,7 +52,7 @@ public class WellOperationRepository : CrudRepositoryBase<WellOperationDto, Well
var skip = request.Skip ?? 0; var skip = request.Skip ?? 0;
var take = request.Take ?? 32; var take = request.Take ?? 32;
var (items, count) = await GetPrivateAsync(request, token); var (items, count) = await GetAsyncWithDaysAndNpv(request, token);
var paginationContainer = new PaginationContainer<WellOperationDto> var paginationContainer = new PaginationContainer<WellOperationDto>
{ {
@ -166,61 +165,52 @@ public class WellOperationRepository : CrudRepositoryBase<WellOperationDto, Well
private async Task<IEnumerable<WellOperation>> GetByIdsWells(IEnumerable<int> idsWells, CancellationToken token) private async Task<IEnumerable<WellOperation>> GetByIdsWells(IEnumerable<int> idsWells, CancellationToken token)
{ {
var query = GetQuery() var query = GetQuery()
.Include(e => e.WellSectionType)
.Include(e => e.OperationCategory)
.Where(e => idsWells.Contains(e.IdWell)) .Where(e => idsWells.Contains(e.IdWell))
.OrderBy(e => e.DateStart); .OrderBy(e => e.DateStart);
var entities = await query.ToArrayAsync(token); var entities = await query.ToArrayAsync(token);
return entities; return entities;
} }
private async Task<(IEnumerable<WellOperationDto> items, int count)> GetPrivateAsync(WellOperationRequest request, CancellationToken token) private async Task<(IEnumerable<WellOperationDto> items, int count)> GetAsyncWithDaysAndNpv(WellOperationRequest request, CancellationToken token)
{ {
var skip = request.Skip ?? 0; var skip = request.Skip ?? 0;
var take = request.Take ?? 32; var take = request.Take ?? 32;
/*
каунт = сумма всех фильтеред1
for{
все записи по скважине и типу план/факт = wellOperationswithType
из wellOperationswithType выбираем первую операцию
из wellOperationswithType все НПВ
к wellOperationswithType применяем оставшиеся фильтры из buildquery = фильтеред1
к фильтеред1 применить скип тэйк = фильтеред2
фильтеред2 конвертировать в дто и рассчитать дэй и время нпв
...
}
*/
var entities = await GetByIdsWells(request.IdsWell, token); var entities = await GetByIdsWells(request.IdsWell, token);
var entitiesByWellAndType = entities var entitiesByWellAndType = entities
.GroupBy(e => new { e.IdWell, e.IdType }) .GroupBy(e => new { e.IdWell, e.IdType })
.Select(grp => grp.ToArray()); .Select(grp => grp.ToArray());
var result = new List<WellOperationDto>(); var result = new List<WellOperationDto>();
foreach (var wellOperationswithType in entitiesByWellAndType) var count = 0;
foreach (var wellOperationsWithType in entitiesByWellAndType)
{ {
var firstWellOperation = wellOperationswithType var firstWellOperation = wellOperationsWithType
.OrderBy(e => e.DateStart) .OrderBy(e => e.DateStart)
.FirstOrDefault(); .FirstOrDefault()!;
//НПВ var operationsWithNpt = wellOperationsWithType
var operationsWithNpt = wellOperationswithType
.Where(o => WellOperationCategory.NonProductiveTimeSubIds.Contains(o.IdCategory)); .Where(o => WellOperationCategory.NonProductiveTimeSubIds.Contains(o.IdCategory));
var filteredWellOperations = FilterOperations(wellOperationswithType, request); var filteredWellOperations = GetByRequest(wellOperationsWithType, request);
var filteredWellOperationsPart = filteredWellOperations var filteredWellOperationsPart = filteredWellOperations
.Skip(skip) .Skip(skip)
.Take(take); .Take(take);
var dtos = filteredWellOperationsPart var dtos = filteredWellOperationsPart
.Select(o => ConvertWithDrillingDaysAndNpvHours(o, firstWellOperation, operationsWithNpt, token)); .Select(o => ConvertWithDrillingDaysAndNpvHours(o, firstWellOperation, operationsWithNpt));
result.AddRange(dtos); result.AddRange(dtos);
count += filteredWellOperations.Count();
} }
return (result, entities.Count()); return (result, count);
} }
private IEnumerable<WellOperation> FilterOperations(IEnumerable<WellOperation> entities, WellOperationRequest request) private IEnumerable<WellOperation> GetByRequest(IEnumerable<WellOperation> entities, WellOperationRequest request)
{ {
if (request.OperationType.HasValue) if (request.OperationType.HasValue)
entities = entities.Where(e => e.IdType == request.OperationType.Value); entities = entities.Where(e => e.IdType == request.OperationType.Value);
@ -253,36 +243,7 @@ public class WellOperationRepository : CrudRepositoryBase<WellOperationDto, Well
private async Task<IEnumerable<WellOperation>> BuildQuery(WellOperationRequest request, CancellationToken token) private async Task<IEnumerable<WellOperation>> BuildQuery(WellOperationRequest request, CancellationToken token)
{ {
var entities = await GetByIdsWells(request.IdsWell, token); var entities = await GetByIdsWells(request.IdsWell, token);
entities = GetByRequest(entities, request);
if (request.OperationType.HasValue)
entities = entities.Where(e => e.IdType == request.OperationType.Value);
if (request.SectionTypeIds?.Any() is true)
entities = entities.Where(e => request.SectionTypeIds.Contains(e.IdWellSectionType));
if (request.OperationCategoryIds?.Any() is true)
entities = entities.Where(e => request.OperationCategoryIds.Contains(e.IdCategory));
if (request.GeDepth.HasValue)
entities = entities.Where(e => e.DepthEnd >= request.GeDepth.Value);
if (request.LeDepth.HasValue)
entities = entities.Where(e => e.DepthEnd <= request.LeDepth.Value);
if (request.GeDate.HasValue)
{
var geDateUtc = request.GeDate.Value.UtcDateTime;
entities = entities.Where(e => e.DateStart >= geDateUtc);
}
if (request.LeDate.HasValue)
{
var leDateUtc = request.LeDate.Value.UtcDateTime;
entities = entities.Where(e => e.DateStart <= leDateUtc);
}
if (request.SortFields?.Any() is true)
entities = entities.AsQueryable().SortBy(request.SortFields);
return entities; return entities;
} }
@ -378,8 +339,7 @@ public class WellOperationRepository : CrudRepositoryBase<WellOperationDto, Well
private WellOperationDto ConvertWithDrillingDaysAndNpvHours( private WellOperationDto ConvertWithDrillingDaysAndNpvHours(
WellOperation entity, WellOperation entity,
WellOperation firstOperation, WellOperation firstOperation,
IEnumerable<WellOperation> wellOperationsWithNtp, IEnumerable<WellOperation> wellOperationsWithNtp)
CancellationToken token)
{ {
var dto = Convert(entity); var dto = Convert(entity);
dto.Day = (entity.DateStart - firstOperation.DateStart).TotalDays; dto.Day = (entity.DateStart - firstOperation.DateStart).TotalDays;
@ -401,6 +361,9 @@ public class WellOperationRepository : CrudRepositoryBase<WellOperationDto, Well
{ {
//TODO: пока такое получение TimeZone скважины, нужно исправить на Lazy //TODO: пока такое получение TimeZone скважины, нужно исправить на Lazy
//Хоть мы и тянем данные из кэша, но от получения TimeZone в этом методе нужно избавиться, пока так //Хоть мы и тянем данные из кэша, но от получения TimeZone в этом методе нужно избавиться, пока так
//.Include(e => e.WellSectionType)
// .Include(e => e.OperationCategory)
var timeZoneOffset = wellService.GetTimezone(src.IdWell).Offset; var timeZoneOffset = wellService.GetTimezone(src.IdWell).Offset;
var dto = src.Adapt<WellOperationDto>(); var dto = src.Adapt<WellOperationDto>();
dto.DateStart = src.DateStart.ToOffset(timeZoneOffset); dto.DateStart = src.DateStart.ToOffset(timeZoneOffset);