DD.WellWorkover.Cloud/AsbCloudInfrastructure/Services/WellSections/WellSectionPlanService.cs

68 lines
2.6 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data;
using AsbCloudApp.Data.WellSections;
using AsbCloudApp.Exceptions;
using AsbCloudApp.Services;
using AsbCloudApp.Services.WellSections;
namespace AsbCloudInfrastructure.Services.WellSections;
public class WellSectionPlanService : IWellSectionPlanService
{
private readonly IRepositoryWellRelated<WellSectionPlanDto> wellSectionPlanRepository;
private readonly ICrudRepository<WellSectionTypeDto> wellSectionTypeRepository;
public WellSectionPlanService(IRepositoryWellRelated<WellSectionPlanDto> wellSectionPlanRepository,
ICrudRepository<WellSectionTypeDto> wellSectionTypeRepository)
{
this.wellSectionPlanRepository = wellSectionPlanRepository;
this.wellSectionTypeRepository = wellSectionTypeRepository;
}
public async Task<int> InsertAsync(WellSectionPlanDto wellSectionPlan, CancellationToken cancellationToken)
{
await EnsureUniqueSectionTypeInWellAsync(wellSectionPlan, cancellationToken);
return await wellSectionPlanRepository.InsertAsync(wellSectionPlan, cancellationToken);
}
public async Task<int> UpdateAsync(WellSectionPlanDto wellSectionPlan, CancellationToken cancellationToken)
{
await EnsureUniqueSectionTypeInWellAsync(wellSectionPlan, cancellationToken);
wellSectionPlan.LastUpdateDate = DateTime.UtcNow;
return await wellSectionPlanRepository.UpdateAsync(wellSectionPlan, cancellationToken);
}
public async Task<IEnumerable<WellSectionTypeDto>> GetWellSectionTypesAsync(int idWell, CancellationToken cancellationToken)
{
var wellSectionTypes = (await wellSectionTypeRepository.GetAllAsync(cancellationToken))
.OrderBy(w => w.Order);
var planWellSections = await wellSectionPlanRepository.GetByIdWellAsync(idWell, cancellationToken);
if (!planWellSections.Any())
return wellSectionTypes;
return wellSectionTypes.Where(w => planWellSections.Any(s => s.IdSectionType == w.Id));
}
private async Task EnsureUniqueSectionTypeInWellAsync(WellSectionPlanDto section, CancellationToken cancellationToken)
{
var existingWellSectionPlan = (await wellSectionPlanRepository.GetByIdWellAsync(section.IdWell, cancellationToken))
.SingleOrDefault(s => s.IdSectionType == section.IdSectionType);
if (existingWellSectionPlan is not null && existingWellSectionPlan.Id != section.Id)
{
var sectionType = await wellSectionTypeRepository.GetOrDefaultAsync(section.IdSectionType, cancellationToken);
throw new ArgumentInvalidException($"Секция '{sectionType?.Caption}' уже добавлена в конструкцию скважины",
nameof(section.IdSectionType));
}
}
}