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 wellSectionPlanRepository; private readonly ICrudRepository wellSectionTypeRepository; public WellSectionPlanService(IRepositoryWellRelated wellSectionPlanRepository, ICrudRepository wellSectionTypeRepository) { this.wellSectionPlanRepository = wellSectionPlanRepository; this.wellSectionTypeRepository = wellSectionTypeRepository; } public async Task InsertAsync(WellSectionPlanDto wellSectionPlan, CancellationToken cancellationToken) { await EnsureUniqueSectionTypeInWellAsync(wellSectionPlan, cancellationToken); return await wellSectionPlanRepository.InsertAsync(wellSectionPlan, cancellationToken); } public async Task UpdateAsync(WellSectionPlanDto wellSectionPlan, CancellationToken cancellationToken) { await EnsureUniqueSectionTypeInWellAsync(wellSectionPlan, cancellationToken); wellSectionPlan.LastUpdateDate = DateTime.UtcNow; return await wellSectionPlanRepository.UpdateAsync(wellSectionPlan, cancellationToken); } public async Task> 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)); } } }