Merge pull request 'рефакторинг WellOperationRepository' (#265) from feature/wellOperationRepository-refactoring into dev

Reviewed-on: http://test.digitaldrilling.ru:8080/DDrilling/AsbCloudServer/pulls/265
This commit is contained in:
Никита Фролов 2024-04-25 14:18:29 +05:00
commit 7e1a22370c
9 changed files with 456 additions and 370 deletions

View File

@ -54,7 +54,7 @@ namespace AsbCloudApp.Repositories
/// <summary> /// <summary>
/// Обновить существующую операцию /// Обновить существующую операцию
/// </summary> /// </summary>
/// <param name="dto"></param> /// <param name="dtos"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
Task<int> UpdateRangeAsync(IEnumerable<WellOperationDto> dtos, CancellationToken token); Task<int> UpdateRangeAsync(IEnumerable<WellOperationDto> dtos, CancellationToken token);

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,72 @@ 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>
public WellOperationRequestBase()
{
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
public WellOperationRequestBase(WellOperationRequestBase request)
{
GeDepth = request.GeDepth;
LeDepth = request.LeDepth;
GeDate = request.GeDate;
LeDate = request.LeDate;
OperationCategoryIds = request.OperationCategoryIds;
OperationType = request.OperationType;
SectionTypeIds = request.SectionTypeIds;
Skip = request.Skip;
Take = request.Take;
SortFields = request.SortFields;
}
} }
/// <summary> /// <summary>
@ -53,32 +82,23 @@ 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) : base(request)
{ {
GeDepth = request.GeDepth; IdsWell = idsWell;
LeDepth = request.LeDepth; }
GeDate = request.GeDate;
LeDate = request.LeDate;
OperationCategoryIds = request.OperationCategoryIds; /// <summary>
OperationType = request.OperationType; /// Идентификаторы скважин
SectionTypeIds = request.SectionTypeIds; /// </summary>
[Required]
Skip = request.Skip; [Length(1, 100)]
Take = request.Take; public IEnumerable<int> IdsWell { get; }
SortFields = request.SortFields;
}
/// <summary>
/// Идентификаторы скважин
/// </summary>
public IEnumerable<int>? IdsWell { get; }
} }

View File

@ -1,9 +1,4 @@
using System; using AsbCloudApp.Data;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data;
using AsbCloudApp.Data.WellOperation; using AsbCloudApp.Data.WellOperation;
using AsbCloudApp.Exceptions; using AsbCloudApp.Exceptions;
using AsbCloudApp.Repositories; using AsbCloudApp.Repositories;
@ -14,350 +9,367 @@ using AsbCloudDb.Model;
using Mapster; using Mapster;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Repository; namespace AsbCloudInfrastructure.Repository;
public class WellOperationRepository : CrudRepositoryBase<WellOperationDto, WellOperation>, public class WellOperationRepository : CrudRepositoryBase<WellOperationDto, WellOperation>,
IWellOperationRepository IWellOperationRepository
{ {
private readonly IMemoryCache memoryCache; private readonly IMemoryCache memoryCache;
private readonly IWellOperationCategoryRepository wellOperationCategoryRepository; private readonly IWellOperationCategoryRepository wellOperationCategoryRepository;
private readonly IWellService wellService; private readonly IWellService wellService;
private Lazy<IDictionary<int, WellOperationCategoryDto>> LazyWellCategories { get; }
private Lazy<IDictionary<int, WellSectionTypeDto>> LazyWellSectionTypes { get; }
public WellOperationRepository(IAsbCloudDbContext context, public WellOperationRepository(IAsbCloudDbContext context,
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; this.wellService = wellService;
this.wellService = wellService;
}
public IEnumerable<WellSectionTypeDto> GetSectionTypes() => LazyWellCategories = new(() => wellOperationCategoryRepository.Get(true, false).ToDictionary(c => c.Id));
memoryCache LazyWellSectionTypes = new(() => GetSectionTypes().ToDictionary(c => c.Id));
.GetOrCreateBasic(dbContext.WellSectionTypes) }
.OrderBy(s => s.Order)
.Select(s => s.Adapt<WellSectionTypeDto>());
public async Task<IEnumerable<WellOperationDto>> GetAsync(WellOperationRequest request, CancellationToken token) public IEnumerable<WellSectionTypeDto> GetSectionTypes() =>
{ memoryCache
var query = BuildQuery(request); .GetOrCreateBasic(dbContext.WellSectionTypes)
.OrderBy(s => s.Order)
.Select(s => s.Adapt<WellSectionTypeDto>());
if (request.Skip.HasValue) public async Task<IEnumerable<WellOperationDto>> GetAsync(WellOperationRequest request, CancellationToken token)
query = query.Skip(request.Skip.Value); {
var (items, _) = await GetWithDaysAndNpvAsync(request, token);
return items;
}
if (request.Take.HasValue) public async Task<PaginationContainer<WellOperationDto>> GetPageAsync(WellOperationRequest request, CancellationToken token)
query = query.Take(request.Take.Value); {
var skip = request.Skip ?? 0;
var take = request.Take ?? 32;
var entities = await query.AsNoTracking() var (items, count) = await GetWithDaysAndNpvAsync(request, token);
.ToArrayAsync(token);
return await ConvertWithDrillingDaysAndNpvHoursAsync(entities, token); var paginationContainer = new PaginationContainer<WellOperationDto>
} {
Skip = skip,
Take = take,
Count = count,
Items = items
};
public async Task<PaginationContainer<WellOperationDto>> GetPageAsync(WellOperationRequest request, CancellationToken token) return paginationContainer;
{ }
var skip = request.Skip ?? 0;
var take = request.Take ?? 32;
var query = BuildQuery(request); public async Task<IEnumerable<WellGroupOpertionDto>> GetGroupOperationsStatAsync(WellOperationRequest request, CancellationToken token)
{
var query = BuildQuery(request);
var entities = await query
.Select(o => new
{
o.IdCategory,
DurationMinutes = o.DurationHours * 60,
DurationDepth = o.DepthEnd - o.DepthStart
})
.ToArrayAsync(token);
var entities = await query.Skip(skip) var parentRelationDictionary = wellOperationCategoryRepository.Get(true)
.Take(take) .ToDictionary(c => c.Id, c => new
.AsNoTracking() {
.ToArrayAsync(token); c.Name,
c.IdParent
});
var paginationContainer = new PaginationContainer<WellOperationDto> var dtos = entities
{ .GroupBy(o => o.IdCategory)
Skip = skip, .Select(g => new WellGroupOpertionDto
Take = take, {
Count = await query.CountAsync(token), IdCategory = g.Key,
Items = await ConvertWithDrillingDaysAndNpvHoursAsync(entities, token) Category = parentRelationDictionary[g.Key].Name,
}; Count = g.Count(),
MinutesAverage = g.Average(o => o.DurationMinutes),
MinutesMin = g.Min(o => o.DurationMinutes),
MinutesMax = g.Max(o => o.DurationMinutes),
TotalMinutes = g.Sum(o => o.DurationMinutes),
DeltaDepth = g.Sum(o => o.DurationDepth),
IdParent = parentRelationDictionary[g.Key].IdParent
});
return paginationContainer; while (dtos.All(x => x.IdParent != null))
} {
dtos = dtos
.GroupBy(o => o.IdParent!)
.Select(g =>
{
var idCategory = g.Key ?? int.MinValue;
var category = parentRelationDictionary.GetValueOrDefault(idCategory);
var newDto = new WellGroupOpertionDto
{
IdCategory = idCategory,
Category = category?.Name ?? "unknown",
Count = g.Sum(o => o.Count),
DeltaDepth = g.Sum(o => o.DeltaDepth),
TotalMinutes = g.Sum(o => o.TotalMinutes),
Items = g.ToList(),
IdParent = category?.IdParent,
};
return newDto;
});
}
public async Task<IEnumerable<WellGroupOpertionDto>> GetGroupOperationsStatAsync(WellOperationRequest request, CancellationToken token) return dtos;
{ }
var query = BuildQuery(request);
var entities = await query
.Select(o => new
{
o.IdCategory,
DurationMinutes = o.DurationHours * 60,
DurationDepth = o.DepthEnd - o.DepthStart
})
.ToArrayAsync(token);
var parentRelationDictionary = wellOperationCategoryRepository.Get(true) public async Task<int> InsertRangeAsync(IEnumerable<WellOperationDto> dtos,
.ToDictionary(c => c.Id, c => new bool deleteBeforeInsert,
{ CancellationToken token)
c.Name, {
c.IdParent EnsureValidWellOperations(dtos);
});
var dtos = entities if (!deleteBeforeInsert)
.GroupBy(o => o.IdCategory) return await InsertRangeAsync(dtos, token);
.Select(g => new WellGroupOpertionDto
{
IdCategory = g.Key,
Category = parentRelationDictionary[g.Key].Name,
Count = g.Count(),
MinutesAverage = g.Average(o => o.DurationMinutes),
MinutesMin = g.Min(o => o.DurationMinutes),
MinutesMax = g.Max(o => o.DurationMinutes),
TotalMinutes = g.Sum(o => o.DurationMinutes),
DeltaDepth = g.Sum(o => o.DurationDepth),
IdParent = parentRelationDictionary[g.Key].IdParent
});
while (dtos.All(x => x.IdParent != null)) var idType = dtos.First().IdType;
{ var idWell = dtos.First().IdWell;
dtos = dtos
.GroupBy(o => o.IdParent!)
.Select(g =>
{
var idCategory = g.Key ?? int.MinValue;
var category = parentRelationDictionary.GetValueOrDefault(idCategory);
var newDto = new WellGroupOpertionDto
{
IdCategory = idCategory,
Category = category?.Name ?? "unknown",
Count = g.Sum(o => o.Count),
DeltaDepth = g.Sum(o => o.DeltaDepth),
TotalMinutes = g.Sum(o => o.TotalMinutes),
Items = g.ToList(),
IdParent = category?.IdParent,
};
return newDto;
});
}
return dtos; var existingOperationIds = await dbContext.WellOperations
} .Where(e => e.IdWell == idWell && e.IdType == idType)
.Select(e => e.Id)
.ToArrayAsync(token);
public async Task<int> InsertRangeAsync(IEnumerable<WellOperationDto> dtos, await DeleteRangeAsync(existingOperationIds, token);
bool deleteBeforeInsert,
CancellationToken token)
{
EnsureValidWellOperations(dtos);
if (!deleteBeforeInsert) return await InsertRangeAsync(dtos, token);
return await InsertRangeAsync(dtos, token); }
var idType = dtos.First().IdType; public override Task<int> UpdateRangeAsync(IEnumerable<WellOperationDto> dtos, CancellationToken token)
var idWell = dtos.First().IdWell; {
EnsureValidWellOperations(dtos);
var existingOperationIds = await dbContext.WellOperations return base.UpdateRangeAsync(dtos, token);
.Where(e => e.IdWell == idWell && e.IdType == idType) }
.Select(e => e.Id)
.ToArrayAsync(token);
await DeleteRangeAsync(existingOperationIds, token); private static void EnsureValidWellOperations(IEnumerable<WellOperationDto> dtos)
{
if (dtos.GroupBy(d => d.IdType).Count() > 1)
throw new ArgumentInvalidException(nameof(dtos), "Все операции должны быть одного типа");
return await InsertRangeAsync(dtos, token); if (dtos.GroupBy(d => d.IdType).Count() > 1)
} throw new ArgumentInvalidException(nameof(dtos), "Все операции должны принадлежать одной скважине");
}
public override Task<int> UpdateRangeAsync(IEnumerable<WellOperationDto> dtos, CancellationToken token) private async Task<IEnumerable<WellOperation>> GetByIdsWells(IEnumerable<int> idsWells, CancellationToken token)
{ {
EnsureValidWellOperations(dtos); var query = GetQuery()
.Where(e => idsWells.Contains(e.IdWell))
.OrderBy(e => e.DateStart);
var entities = await query.ToArrayAsync(token);
return entities;
}
return base.UpdateRangeAsync(dtos, token); private async Task<(IEnumerable<WellOperationDto> items, int count)> GetWithDaysAndNpvAsync(WellOperationRequest request, CancellationToken token)
} {
var skip = request.Skip ?? 0;
var take = request.Take ?? 32;
private static void EnsureValidWellOperations(IEnumerable<WellOperationDto> dtos) var entities = await GetByIdsWells(request.IdsWell, token);
{ var groupedByWellAndType = entities
if (dtos.GroupBy(d => d.IdType).Count() > 1) .GroupBy(e => new { e.IdWell, e.IdType });
throw new ArgumentInvalidException(nameof(dtos), "Все операции должны быть одного типа");
if (dtos.GroupBy(d => d.IdType).Count() > 1) var result = new List<WellOperationDto>();
throw new ArgumentInvalidException(nameof(dtos), "Все операции должны принадлежать одной скважине"); var count = 0;
} foreach (var wellOperationsWithType in groupedByWellAndType)
{
var firstWellOperation = wellOperationsWithType
.OrderBy(e => e.DateStart)
.FirstOrDefault()!;
private IQueryable<WellOperation> BuildQuery(WellOperationRequest request) var operationsWithNpt = wellOperationsWithType
{ .Where(o => WellOperationCategory.NonProductiveTimeSubIds.Contains(o.IdCategory));
var query = GetQuery()
.Where(e => request.IdsWell != null && request.IdsWell.Contains(e.IdWell))
.OrderBy(e => e.DateStart)
.AsQueryable();
if (request.OperationType.HasValue) IEnumerable<WellOperation> filteredWellOperations = FilterByRequest(wellOperationsWithType.AsQueryable(), request);
query = query.Where(e => e.IdType == request.OperationType.Value);
if (request.SectionTypeIds?.Any() is true) var filteredWellOperationsPart = filteredWellOperations
query = query.Where(e => request.SectionTypeIds.Contains(e.IdWellSectionType)); .Skip(skip)
.Take(take);
if (request.OperationCategoryIds?.Any() is true) var dtos = filteredWellOperationsPart
query = query.Where(e => request.OperationCategoryIds.Contains(e.IdCategory)); .Select(entity =>
{
var dto = Convert(entity);
dto.Day = (entity.DateStart - firstWellOperation.DateStart).TotalDays;
dto.NptHours = operationsWithNpt
.Where(o => o.DateStart <= entity.DateStart)
.Sum(e => e.DurationHours);
return dto;
});
if (request.GeDepth.HasValue) result.AddRange(dtos);
query = query.Where(e => e.DepthEnd >= request.GeDepth.Value); count += filteredWellOperations.Count();
}
if (request.LeDepth.HasValue) return (result, count);
query = query.Where(e => e.DepthEnd <= request.LeDepth.Value); }
if (request.GeDate.HasValue) private static IQueryable<WellOperation> FilterByRequest(IQueryable<WellOperation> entities, WellOperationRequest request)
{ {
var geDateUtc = request.GeDate.Value.UtcDateTime; if (request.OperationType.HasValue)
query = query.Where(e => e.DateStart >= geDateUtc); 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.LeDate.HasValue) if (request.GeDate.HasValue)
{ {
var leDateUtc = request.LeDate.Value.UtcDateTime; var geDateUtc = request.GeDate.Value.UtcDateTime;
query = query.Where(e => e.DateStart <= leDateUtc); entities = entities.Where(e => e.DateStart >= geDateUtc);
} }
if (request.SortFields?.Any() is true) if (request.LeDate.HasValue)
query = query.SortBy(request.SortFields); {
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);
else
entities = entities.AsQueryable().OrderBy(e => e.DateStart);
return query; return entities;
} }
public async Task<IEnumerable<SectionByOperationsDto>> GetSectionsAsync(IEnumerable<int> idsWells, CancellationToken token) private IQueryable<WellOperation> BuildQuery(WellOperationRequest request)
{ {
const string keyCacheSections = "OperationsBySectionSummarties"; var query = GetQuery()
.Where(e => request.IdsWell.Contains(e.IdWell))
.OrderBy(e => e.DateStart)
.AsQueryable();
query = FilterByRequest(query, request);
var cache = await memoryCache.GetOrCreateAsync(keyCacheSections, async (entry) => return query;
{ }
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30);
var query = dbContext.Set<WellOperation>() public async Task<IEnumerable<SectionByOperationsDto>> GetSectionsAsync(IEnumerable<int> idsWells, CancellationToken token)
.GroupBy(operation => new {
{ const string keyCacheSections = "OperationsBySectionSummarties";
operation.IdWell,
operation.IdType,
operation.IdWellSectionType,
operation.WellSectionType.Caption,
})
.Select(group => new
{
group.Key.IdWell,
group.Key.IdType,
group.Key.IdWellSectionType,
group.Key.Caption,
First = group var cache = await memoryCache.GetOrCreateAsync(keyCacheSections, async (entry) =>
.OrderBy(operation => operation.DateStart) {
.Select(operation => new entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30);
{
operation.DateStart,
operation.DepthStart,
})
.First(),
Last = group var query = dbContext.Set<WellOperation>()
.OrderByDescending(operation => operation.DateStart) .GroupBy(operation => new
.Select(operation => new {
{ operation.IdWell,
operation.DateStart, operation.IdType,
operation.DurationHours, operation.IdWellSectionType,
operation.DepthEnd, operation.WellSectionType.Caption,
}) })
.First(), .Select(group => new
}) {
.Where(s => idsWells.Contains(s.IdWell)); group.Key.IdWell,
var dbData = await query.ToArrayAsync(token); group.Key.IdType,
var sections = dbData.Select( group.Key.IdWellSectionType,
item => new SectionByOperationsDto group.Key.Caption,
{
IdWell = item.IdWell,
IdType = item.IdType,
IdWellSectionType = item.IdWellSectionType,
Caption = item.Caption, First = group
.OrderBy(operation => operation.DateStart)
.Select(operation => new
{
operation.DateStart,
operation.DepthStart,
})
.First(),
DateStart = item.First.DateStart, Last = group
DepthStart = item.First.DepthStart, .OrderByDescending(operation => operation.DateStart)
.Select(operation => new
{
operation.DateStart,
operation.DurationHours,
operation.DepthEnd,
})
.First(),
})
.Where(s => idsWells.Contains(s.IdWell));
var dbData = await query.ToArrayAsync(token);
var sections = dbData.Select(
item => new SectionByOperationsDto
{
IdWell = item.IdWell,
IdType = item.IdType,
IdWellSectionType = item.IdWellSectionType,
DateEnd = item.Last.DateStart.AddHours(item.Last.DurationHours), Caption = item.Caption,
DepthEnd = item.Last.DepthEnd,
})
.ToArray()
.AsEnumerable();
entry.Value = sections; DateStart = item.First.DateStart,
return sections; DepthStart = item.First.DepthStart,
});
return cache; DateEnd = item.Last.DateStart.AddHours(item.Last.DurationHours),
} DepthEnd = item.Last.DepthEnd,
})
.ToArray()
.AsEnumerable();
public async Task<DatesRangeDto?> GetDatesRangeAsync(int idWell, int idType, CancellationToken cancellationToken) entry.Value = sections;
{ return sections;
var query = dbContext.WellOperations.Where(o => o.IdWell == idWell && o.IdType == idType); });
if (!await query.AnyAsync(cancellationToken)) return cache!;
return null; }
var timeZoneOffset = wellService.GetTimezone(idWell).Offset; public async Task<DatesRangeDto?> GetDatesRangeAsync(int idWell, int idType, CancellationToken cancellationToken)
{
var minDate = await query.MinAsync(o => o.DateStart, cancellationToken); var query = dbContext.WellOperations.Where(o => o.IdWell == idWell && o.IdType == idType);
var maxDate = await query.MaxAsync(o => o.DateStart, cancellationToken);
return new DatesRangeDto if (!await query.AnyAsync(cancellationToken))
{ return null;
From = minDate.ToOffset(timeZoneOffset),
To = maxDate.ToOffset(timeZoneOffset)
};
}
private async Task<IEnumerable<WellOperationDto>> ConvertWithDrillingDaysAndNpvHoursAsync(IEnumerable<WellOperation> entities, var timeZoneOffset = wellService.GetTimezone(idWell).Offset;
CancellationToken token)
{
var idsWell = entities.Select(e => e.IdWell).Distinct();
var currentWellOperations = GetQuery() var minDate = await query.MinAsync(o => o.DateStart, cancellationToken);
.Where(entity => idsWell.Contains(entity.IdWell)); var maxDate = await query.MaxAsync(o => o.DateStart, cancellationToken);
var dateFirstDrillingOperationByIdWell = await currentWellOperations return new DatesRangeDto
.Where(entity => entity.IdType == WellOperation.IdOperationTypeFact) {
.GroupBy(entity => entity.IdWell) From = minDate.ToOffset(timeZoneOffset),
.ToDictionaryAsync(g => g.Key, g => g.Min(o => o.DateStart), token); To = maxDate.ToOffset(timeZoneOffset)
};
}
var operationsWithNptByIdWell = await currentWellOperations.Where(entity => protected override WellOperation Convert(WellOperationDto src)
entity.IdType == WellOperation.IdOperationTypeFact && {
WellOperationCategory.NonProductiveTimeSubIds.Contains(entity.IdCategory)) var entity = src.Adapt<WellOperation>();
.GroupBy(entity => entity.IdWell) entity.DateStart = src.DateStart.UtcDateTime;
.ToDictionaryAsync(g => g.Key, g => g.Select(o => o), token); return entity;
}
var dtos = entities.Select(entity => protected override WellOperationDto Convert(WellOperation src)
{ {
var dto = Convert(entity); //TODO: пока такое получение TimeZone скважины, нужно исправить на Lazy
//Хоть мы и тянем данные из кэша, но от получения TimeZone в этом методе нужно избавиться, пока так
var timeZoneOffset = wellService.GetTimezone(src.IdWell).Offset;
if (dateFirstDrillingOperationByIdWell.TryGetValue(entity.IdWell, out var dateFirstDrillingOperation)) var dto = src.Adapt<WellOperationDto>();
dto.Day = (entity.DateStart - dateFirstDrillingOperation).TotalDays; dto.DateStart = src.DateStart.ToOffset(timeZoneOffset);
dto.LastUpdateDate = src.LastUpdateDate.ToOffset(timeZoneOffset);
if (operationsWithNptByIdWell.TryGetValue(entity.IdWell, out var wellOperationsWithNtp)) dto.OperationCategoryName = LazyWellCategories.Value.TryGetValue(src.IdCategory, out WellOperationCategoryDto? category) ? category.Name : string.Empty;
dto.NptHours = wellOperationsWithNtp dto.WellSectionTypeCaption = LazyWellSectionTypes.Value.TryGetValue(src.IdWellSectionType, out WellSectionTypeDto? sectionType) ? sectionType.Caption : string.Empty;
.Where(o => o.DateStart <= entity.DateStart) return dto;
.Sum(e => e.DurationHours); }
return dto;
});
return dtos;
}
protected override WellOperation Convert(WellOperationDto src)
{
var entity = src.Adapt<WellOperation>();
entity.DateStart = src.DateStart.UtcDateTime;
return entity;
}
protected override WellOperationDto Convert(WellOperation src)
{
//TODO: пока такое получение TimeZone скважины, нужно исправить на Lazy
//Хоть мы и тянем данные из кэша, но от получения TimeZone в этом методе нужно избавиться, пока так
var timeZoneOffset = wellService.GetTimezone(src.IdWell).Offset;
var dto = src.Adapt<WellOperationDto>();
dto.DateStart = src.DateStart.ToOffset(timeZoneOffset);
dto.LastUpdateDate = src.LastUpdateDate.ToOffset(timeZoneOffset);
return dto;
}
} }

View File

@ -27,7 +27,7 @@ public class WellOperationControllerTest : BaseIntegrationTest
} }
/// <summary> /// <summary>
/// Успешное добавление операций (без предварительной очистки данных) /// Óñïåøíîå äîáàâëåíèå îïåðàöèé (áåç ïðåäâàðèòåëüíîé î÷èñòêè äàííûõ)
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[Fact] [Fact]
@ -46,7 +46,7 @@ public class WellOperationControllerTest : BaseIntegrationTest
} }
/// <summary> /// <summary>
/// Успешное добавление операций (с предварительной очисткой данных) /// Óñïåøíîå äîáàâëåíèå îïåðàöèé (ñ ïðåäâàðèòåëüíîé î÷èñòêîé äàííûõ)
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[Fact] [Fact]
@ -65,7 +65,7 @@ public class WellOperationControllerTest : BaseIntegrationTest
} }
/// <summary> /// <summary>
/// Успешное обновление операций /// Óñïåøíîå îáíîâëåíèå îïåðàöèé
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[Fact] [Fact]
@ -87,7 +87,7 @@ public class WellOperationControllerTest : BaseIntegrationTest
} }
/// <summary> /// <summary>
/// Получение плановых операций /// Ïîëó÷åíèå ïëàíîâûõ îïåðàöèé
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[Fact] [Fact]
@ -144,7 +144,7 @@ public class WellOperationControllerTest : BaseIntegrationTest
IdWellSectionType = 2, IdWellSectionType = 2,
IdCategory = WellOperationCategory.IdSlide, IdCategory = WellOperationCategory.IdSlide,
IdPlan = null, IdPlan = null,
CategoryInfo = "Доп.инфо", CategoryInfo = "Äîï.èíôî",
IdType = idType, IdType = idType,
DepthStart = 10.0, DepthStart = 10.0,
DepthEnd = 20.0, DepthEnd = 20.0,
@ -201,7 +201,7 @@ public class WellOperationControllerTest : BaseIntegrationTest
var stream = responseTemplate.Content; var stream = responseTemplate.Content;
using var workbook = new XLWorkbook(stream); using var workbook = new XLWorkbook(stream);
var sheet = workbook.GetWorksheet("Справочники"); var sheet = workbook.GetWorksheet("Ñïðàâî÷íèêè");
var count = sheet.RowsUsed().Count() - 1; var count = sheet.RowsUsed().Count() - 1;
@ -230,21 +230,75 @@ public class WellOperationControllerTest : BaseIntegrationTest
Assert.True(notExistedInDb.Count() == 0); Assert.True(notExistedInDb.Count() == 0);
} }
private static WellOperation CreateWellOperation(int idWell, int idType = WellOperation.IdOperationTypePlan) => [Theory]
new() [InlineData(WellOperation.IdOperationTypePlan)]
{ [InlineData(WellOperation.IdOperationTypeFact)]
IdWell = idWell, public async Task GetPageOperationsAsyncWithDaysAndNpv_returns_success(int idType)
IdWellSectionType = 2, {
IdCategory = WellOperationCategory.IdSlide, //arrange
IdPlan = null, const int pageSize = 10;
CategoryInfo = "Доп.инфо", const int pageIndex = 0;
LastUpdateDate = new DateTimeOffset(new DateTime(2023, 1, 10)).ToUniversalTime(),
IdType = idType, var well = await dbContext.Wells.FirstAsync();
DepthStart = 10.0, var entity1 = CreateWellOperation(well.Id);
DepthEnd = 20.0,
DateStart = new DateTimeOffset(new DateTime(2023, 1, 10), TimeSpan.FromHours(Defaults.Timezone.Hours)).ToUniversalTime(), var entity2 = entity1.Adapt<WellOperation>();
DurationHours = 1.0, entity2.DateStart = entity2.DateStart.AddDays(1);
Comment = "1", entity2.IdCategory = WellOperationCategory.IdEquipmentDrillingRepair;
IdUser = 1, entity2.DurationHours = 2;
var entity3 = entity2.Adapt<WellOperation>();
entity3.DateStart = entity3.DateStart.AddDays(1);
entity3.IdCategory = WellOperationCategory.IdEquipmentDrillingRepair;
entity3.DurationHours = 3;
dbContext.WellOperations.Add(entity1);
dbContext.WellOperations.Add(entity2);
dbContext.WellOperations.Add(entity3);
await dbContext.SaveChangesAsync();
var request = new WellOperationRequestBase
{
OperationType = WellOperation.IdOperationTypePlan,
Skip = pageIndex,
Take = pageSize,
SortFields = [nameof(WellOperation.DateStart)]
}; };
//act
var response = await client.GetPageOperationsAsync(well.Id, request);
//assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
var items = response.Content.Items.ToArray();
Assert.Equal(0, items[0].Day);
Assert.Equal(1, items[1].Day);
Assert.Equal(2, items[2].Day);
Assert.Equal(0, items[0].NptHours);
Assert.Equal(2, items[1].NptHours);
Assert.Equal(5, items[2].NptHours);
}
private static WellOperation CreateWellOperation(int idWell, int idType = WellOperation.IdOperationTypePlan) =>
new()
{
IdWell = idWell,
IdWellSectionType = 2,
IdCategory = WellOperationCategory.IdSlide,
IdPlan = null,
CategoryInfo = "Äîï.èíôî",
LastUpdateDate = new DateTimeOffset(new DateTime(2023, 1, 10)).ToUniversalTime(),
IdType = idType,
DepthStart = 10.0,
DepthEnd = 20.0,
DateStart = new DateTimeOffset(new DateTime(2023, 1, 10), TimeSpan.FromHours(Defaults.Timezone.Hours)).ToUniversalTime(),
DurationHours = 1.0,
Comment = "1",
IdUser = 1,
};
} }