From 27cf27ed555fcd90be654b899b837b82dee54efc Mon Sep 17 00:00:00 2001 From: "ai.astrakhantsev" Date: Fri, 20 Jan 2023 10:47:39 +0500 Subject: [PATCH 1/5] =?UTF-8?q?#7065595=20=D0=9F=D0=B5=D1=80=D0=B5=D0=BD?= =?UTF-8?q?=D0=BE=D1=81=20=D1=81=D0=B5=D1=80=D0=B2=D0=B8=D1=81=D0=B0=20"?= =?UTF-8?q?=D0=94=D0=B5=D0=BB=D0=BE=20=D1=81=D0=BA=D0=B2=D0=B0=D0=B6=D0=B8?= =?UTF-8?q?=D0=BD=D1=8B"=20=D0=B2=20=D1=80=D0=B5=D0=BF=D0=BE=D0=B7=D0=B8?= =?UTF-8?q?=D1=82=D0=BE=D1=80=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../IWellFinalDocumentsRepository.cs | 51 +++++++ .../Services/IWellFinalDocumentsService.cs | 20 +-- AsbCloudInfrastructure/DependencyInjection.cs | 3 +- .../WellFinalDocumentsRepository.cs | 143 ++++++++++++++++++ .../Services/WellFinalDocumentsService.cs | 126 ++------------- .../WellFinalDocumentsServiceTest.cs | 124 +++++---------- .../SAUB/TelemetryWirelineRunOutController.cs | 5 + .../WellFinalDocumentsController.cs | 16 +- 8 files changed, 268 insertions(+), 220 deletions(-) create mode 100644 AsbCloudApp/Repositories/IWellFinalDocumentsRepository.cs create mode 100644 AsbCloudInfrastructure/Repository/WellFinalDocumentsRepository.cs diff --git a/AsbCloudApp/Repositories/IWellFinalDocumentsRepository.cs b/AsbCloudApp/Repositories/IWellFinalDocumentsRepository.cs new file mode 100644 index 00000000..9e803029 --- /dev/null +++ b/AsbCloudApp/Repositories/IWellFinalDocumentsRepository.cs @@ -0,0 +1,51 @@ +using AsbCloudApp.Data; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace AsbCloudApp.Repositories +{ +#nullable enable + /// + /// Репозиторий "Дело скважины" + /// + public interface IWellFinalDocumentsRepository + { + /// + /// Обновление всех записей по скважине + /// + /// + /// + /// + /// + Task> UpdateRangeAsync(int idWell, IEnumerable? dtos, CancellationToken token); + + /// + /// Получение всех записей + /// + /// + /// + /// + /// + Task GetByWellIdAsync(int idWell, int idUser, CancellationToken token); + + /// + /// Получение списка ответственных + /// + /// + /// + /// + Task> GetAvailableUsersAsync(int idWell, CancellationToken token); + + /// + /// Сохранение категории файла + /// + /// + /// + /// + /// + /// + Task SaveCategoryAsync(int idWell, int idCategory, int idUser, CancellationToken token); + } +#nullable disable +} diff --git a/AsbCloudApp/Services/IWellFinalDocumentsService.cs b/AsbCloudApp/Services/IWellFinalDocumentsService.cs index 30459a43..bdcb51f8 100644 --- a/AsbCloudApp/Services/IWellFinalDocumentsService.cs +++ b/AsbCloudApp/Services/IWellFinalDocumentsService.cs @@ -18,25 +18,9 @@ namespace AsbCloudApp.Services /// /// /// + /// /// - Task UpdateRangeAsync(int idWell, IEnumerable? dtos, CancellationToken token); - - /// - /// Получение всех записей - /// - /// - /// запрашивающий пользователь, для проверки его прав и текста сообщения - /// - /// - Task GetByWellIdAsync(int idWell, int idUser, CancellationToken token); - - /// - /// Получение списка ответственных - /// - /// - /// - /// - Task> GetAvailableUsersAsync(int idWell, CancellationToken token); + Task UpdateRangeAsync(int idWell, int idUser, IEnumerable? dtos, CancellationToken token); /// /// Получение истории файлов diff --git a/AsbCloudInfrastructure/DependencyInjection.cs b/AsbCloudInfrastructure/DependencyInjection.cs index b2625b8d..2d5f1b5b 100644 --- a/AsbCloudInfrastructure/DependencyInjection.cs +++ b/AsbCloudInfrastructure/DependencyInjection.cs @@ -173,7 +173,8 @@ namespace AsbCloudInfrastructure services.AddTransient(); services.AddTransient(); services.AddTransient(); - + services.AddTransient(); + // Subsystem service services.AddTransient, CrudCacheRepositoryBase>(); services.AddTransient(); diff --git a/AsbCloudInfrastructure/Repository/WellFinalDocumentsRepository.cs b/AsbCloudInfrastructure/Repository/WellFinalDocumentsRepository.cs new file mode 100644 index 00000000..8af4f375 --- /dev/null +++ b/AsbCloudInfrastructure/Repository/WellFinalDocumentsRepository.cs @@ -0,0 +1,143 @@ +using AsbCloudApp.Data; +using AsbCloudApp.Exceptions; +using AsbCloudApp.Repositories; +using AsbCloudApp.Requests; +using AsbCloudApp.Services; +using AsbCloudDb.Model; +using Mapster; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace AsbCloudInfrastructure.Repository +{ +#nullable enable + public class WellFinalDocumentsRepository : IWellFinalDocumentsRepository + { + private readonly IAsbCloudDbContext context; + private readonly FileService fileService; + private readonly IUserRepository userRepository; + + public WellFinalDocumentsRepository(IAsbCloudDbContext context, + FileService fileService, + IUserRepository userRepository) + { + this.context = context; + this.fileService = fileService; + this.userRepository = userRepository; + } + + /// + public async Task> UpdateRangeAsync(int idWell, IEnumerable? dtos, CancellationToken token) + { + if (dtos is not null) + { + var entities = dtos + .Where(dto => dto.IdsPublishers?.Any() == true) + .SelectMany(dto => dto.IdsPublishers + .Select(idUser => new WellFinalDocument + { + IdCategory = dto.IdCategory, + IdWell = idWell, + IdUser = idUser + })); + + var itemsToDelete = context.WellFinalDocuments.Where(d => d.IdWell == idWell); + context.WellFinalDocuments.RemoveRange(itemsToDelete); + + await context.WellFinalDocuments.AddRangeAsync(entities).ConfigureAwait(false); + await context.SaveChangesAsync(token).ConfigureAwait(false); + + return entities.Adapt>(); + } + throw new ArgumentInvalidException("Данные по категориям отсутствуют."); + } + + /// + public async Task GetByWellIdAsync(int idWell, int idUser, CancellationToken token) + { + var entities = await context.WellFinalDocuments + .Include(d => d.Category) + .Include(d => d.User) + .Where(d => d.IdWell == idWell) + .AsNoTracking() + .ToArrayAsync(token) + .ConfigureAwait(false); + + var entitiesGroups = entities + .GroupBy(d => d.IdCategory); + + var categoriesIds = entitiesGroups + .Select(g => g.Key); + + var files = (await fileService + .GetInfosAsync(new FileRequest { IdWell = idWell }, token) + .ConfigureAwait(false)) + .Where(f => categoriesIds.Contains(f.IdCategory)) + .ToArray(); + + var docs = entitiesGroups.Select((g) => new WellFinalDocumentDto + { + IdCategory = g.Key, + FilesCount = files + .Where(f => f.IdCategory == g.Key) + .Count(), + File = files + .Where(f => f.IdCategory == g.Key) + .OrderBy(f => f.UploadDate) + .LastOrDefault(), + NameCategory = g.First().Category.Name, + Publishers = g.Select(i => i.User.Adapt()), + PermissionToUpload = g.Any(i => i.IdUser == idUser), + }); + + var result = new WellCaseDto + { + IdWell = idWell, + PermissionToSetPubliher = userRepository.HasPermission(idUser, "WellFinalDocuments.editPublisher"), + WellFinalDocuments = docs, + }; + + return result; + } + + /// + public async Task> GetAvailableUsersAsync(int idWell, CancellationToken token) + { + var companyIds = await context.RelationCompaniesWells + .Where(x => x.IdWell == idWell).Select(x => x.IdCompany) + .ToListAsync(token) + .ConfigureAwait(false); + + var allUsers = await userRepository + .GetAllAsync(token) + .ConfigureAwait(false); + + return allUsers.Where(x => x.IdCompany is not null && companyIds.Contains(x.IdCompany ?? int.MinValue)) + .OrderBy(x => x.Surname) + .Select(u => u as UserDto) + .ToArray(); + } + + /// + public async Task SaveCategoryAsync(int idWell, int idCategory, int idUser, CancellationToken token) + { + var entity = await context.WellFinalDocuments + .AsNoTracking() + .FirstOrDefaultAsync(x => x.IdWell == idWell && x.IdCategory == idCategory && x.IdUser == idUser, token); + + if (entity is null) + throw new ArgumentInvalidException("Пользователь не является ответственным за загрузку файла для данной категории."); + + var dto = Convert(entity); + return dto; + } + + private static WellFinalDocumentDBDto Convert(WellFinalDocument entity) + => entity.Adapt(); + } +#nullable disable +} diff --git a/AsbCloudInfrastructure/Services/WellFinalDocumentsService.cs b/AsbCloudInfrastructure/Services/WellFinalDocumentsService.cs index 818eef38..6bf2e0c6 100644 --- a/AsbCloudInfrastructure/Services/WellFinalDocumentsService.cs +++ b/AsbCloudInfrastructure/Services/WellFinalDocumentsService.cs @@ -3,9 +3,6 @@ using AsbCloudApp.Exceptions; using AsbCloudApp.Repositories; using AsbCloudApp.Requests; using AsbCloudApp.Services; -using AsbCloudDb.Model; -using Mapster; -using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; @@ -22,141 +19,52 @@ namespace AsbCloudInfrastructure.Services /// public class WellFinalDocumentsService : IWellFinalDocumentsService { - private readonly IAsbCloudDbContext context; private readonly FileService fileService; private readonly IUserRepository userRepository; private readonly IWellService wellService; private readonly IConfiguration configuration; private readonly IEmailService emailService; private readonly IFileCategoryService fileCategoryService; + private readonly IWellFinalDocumentsRepository wellFinalDocumentsRepository; private const int FileServiceThrewException = -1; - public WellFinalDocumentsService(IAsbCloudDbContext context, - FileService fileService, + public WellFinalDocumentsService(FileService fileService, IUserRepository userRepository, IWellService wellService, IConfiguration configuration, IEmailService emailService, - IFileCategoryService fileCategoryService) + IFileCategoryService fileCategoryService, + IWellFinalDocumentsRepository wellFinalDocumentsRepository) { - this.context = context; this.fileService = fileService; this.userRepository = userRepository; this.wellService = wellService; this.configuration = configuration; this.emailService = emailService; this.fileCategoryService = fileCategoryService; + this.wellFinalDocumentsRepository = wellFinalDocumentsRepository; } /// - public async Task UpdateRangeAsync(int idWell, IEnumerable? dtos, CancellationToken token) + public async Task UpdateRangeAsync(int idWell, int idUser, IEnumerable? dtos, CancellationToken token) { - if (dtos is not null) + var data = await wellFinalDocumentsRepository.UpdateRangeAsync(idWell, dtos, token); + + if (data.Any()) { - var entities = dtos - .Where(dto => dto.IdsPublishers?.Any() == true) - .SelectMany(dto => dto.IdsPublishers - .Select(idUser => new WellFinalDocument - { - IdCategory = dto.IdCategory, - IdWell = idWell, - IdUser = idUser - })); - - var itemsToDelete = context.WellFinalDocuments.Where(d => d.IdWell == idWell); - context.WellFinalDocuments.RemoveRange(itemsToDelete); - - await context.WellFinalDocuments.AddRangeAsync(entities).ConfigureAwait(false); - var data = await context.SaveChangesAsync(token).ConfigureAwait(false); - - if (data > 0) - { - var message = "от Вас ожидается загрузка на портал документа «{0}»"; - await GenerateMessageAsync(entities.Select(x => Convert(x)), message, token); - } - - return data; + var message = "от Вас ожидается загрузка на портал документа «{0}»"; + await GenerateMessageAsync(data, message, token); } - throw new ArgumentInvalidException("Данные по категориям отсутствуют."); - } - /// - public async Task GetByWellIdAsync(int idWell, int idUser, CancellationToken token) - { - var entities = await context.WellFinalDocuments - .Include(d => d.Category) - .Include(d => d.User) - .Where(d => d.IdWell == idWell) - .AsNoTracking() - .ToArrayAsync(token) - .ConfigureAwait(false); - - var entitiesGroups = entities - .GroupBy(d => d.IdCategory); - - var categoriesIds = entitiesGroups - .Select(g => g.Key); - - var files = (await fileService - .GetInfosAsync(new FileRequest { IdWell = idWell}, token) - .ConfigureAwait(false)) - .Where(f => categoriesIds.Contains(f.IdCategory)) - .ToArray(); - - var docs = entitiesGroups.Select((g) => new WellFinalDocumentDto - { - IdCategory = g.Key, - FilesCount = files - .Where(f => f.IdCategory == g.Key) - .Count(), - File = files - .Where(f => f.IdCategory == g.Key) - .OrderBy(f => f.UploadDate) - .LastOrDefault(), - NameCategory = g.First().Category.Name, - Publishers = g.Select(i => i.User.Adapt()), - PermissionToUpload = g.Any(i => i.IdUser == idUser), - }); - - var result = new WellCaseDto - { - IdWell = idWell, - PermissionToSetPubliher = userRepository.HasPermission(idUser, "WellFinalDocuments.editPublisher"), - WellFinalDocuments = docs, - }; - return result; - } - - /// - public async Task> GetAvailableUsersAsync(int idWell, CancellationToken token) - { - var companyIds = await context.RelationCompaniesWells - .Where(x => x.IdWell == idWell).Select(x => x.IdCompany) - .ToListAsync(token) - .ConfigureAwait(false); - - var allUsers = await userRepository - .GetAllAsync(token) - .ConfigureAwait(false); - - return allUsers.Where(x => x.IdCompany is not null && companyIds.Contains(x.IdCompany ?? int.MinValue)) - .OrderBy(x => x.Surname) - .Select(u => u as UserDto) - .ToArray(); + return data.Count(); } /// public async Task SaveCategoryFileAsync(int idWell, int idCategory, int idUser, Stream fileStream, string fileName, CancellationToken token) { - var entity = await context.WellFinalDocuments - .AsNoTracking() - .FirstOrDefaultAsync(x => x.IdWell == idWell && x.IdCategory == idCategory && x.IdUser == idUser); - - if (entity is null) - throw new ArgumentInvalidException("Пользователь не является ответственным за загрузку файла для данной категории."); - - var dto = Convert(entity); + var dto = await wellFinalDocumentsRepository.SaveCategoryAsync(idWell, idCategory, idUser, token) + .ConfigureAwait(false); var file = await fileService.SaveAsync(dto.IdWell, dto.IdUser, dto.IdCategory, fileName, fileStream, token).ConfigureAwait(false); @@ -184,7 +92,7 @@ namespace AsbCloudInfrastructure.Services /// public async Task ReNotifyPublishersAsync(int idWell, int idUser, int idCategory, CancellationToken token) { - WellCaseDto wellCase = await GetByWellIdAsync(idWell, idUser, token); + WellCaseDto wellCase = await wellFinalDocumentsRepository.GetByWellIdAsync(idWell, idUser, token); if (!wellCase.PermissionToSetPubliher) throw new ForbidException("Повторная отправка оповещений Вам не разрешена"); @@ -234,10 +142,6 @@ namespace AsbCloudInfrastructure.Services var body = factory.MakeMailBodyForWellFinalDocument(well, user.Name ?? user.Surname, string.Format(message, documentCategory)); emailService.EnqueueSend(user.Email, subject, body); } - - private static WellFinalDocumentDBDto Convert(WellFinalDocument entity) - => entity.Adapt(); - } #nullable disable } diff --git a/AsbCloudWebApi.Tests/ServicesTests/WellFinalDocumentsServiceTest.cs b/AsbCloudWebApi.Tests/ServicesTests/WellFinalDocumentsServiceTest.cs index caa5c3ed..8d31d48c 100644 --- a/AsbCloudWebApi.Tests/ServicesTests/WellFinalDocumentsServiceTest.cs +++ b/AsbCloudWebApi.Tests/ServicesTests/WellFinalDocumentsServiceTest.cs @@ -1,6 +1,5 @@ using AsbCloudApp.Data; using AsbCloudApp.Services; -using AsbCloudDb.Model; using AsbCloudInfrastructure.Services; using Moq; using System.Threading; @@ -9,7 +8,7 @@ using Xunit; using System.IO; using System.Linq; using AsbCloudApp.Repositories; -using AsbCloudApp.Exceptions; +using System.Collections.Generic; namespace AsbCloudWebApi.Tests.ServicesTests { @@ -24,8 +23,8 @@ namespace AsbCloudWebApi.Tests.ServicesTests private readonly Mock emailServiceMock; private readonly Mock fileCategoryService; - private static readonly UserExtendedDto[] users = new []{ - new UserExtendedDto { + private static readonly UserExtendedDto[] users = new[]{ + new UserExtendedDto { Id = 1, IdCompany = 1, Surname = "Tester 1", @@ -40,38 +39,46 @@ namespace AsbCloudWebApi.Tests.ServicesTests Email = "test1@test1.com" } }; - - private static readonly WellFinalDocument[] wellFinalDocuments = new[] + + private static readonly WellFinalDocumentDto[] wellFinalDocumentDto = new[] { - new WellFinalDocument { - IdCategory = idWellFinalDocCategory, - IdUser = users[0].Id, - User = new User{ - Id = users[0].Id, - Surname = users[0].Surname, - Email = users[0].Email, - }, - IdWell = 1, - Category = new (){ Id = idWellFinalDocCategory, Name = "Проект на бурение транспортного и горизонтального участков скважины"}, - }, + new WellFinalDocumentDto { + IdCategory= idWellFinalDocCategory, + PermissionToUpload = true, + Publishers = new List { + new UserDto { + Id = 1 + } + } + } }; - private static readonly RelationCompanyWell[] relationCompanyWell = new[] - { - new RelationCompanyWell {IdWell = 1, IdCompany= 1} + private static readonly WellCaseDto wellCaseDto = new WellCaseDto { + IdWell = 1, + PermissionToSetPubliher = true, + WellFinalDocuments = wellFinalDocumentDto }; + + private static readonly WellFinalDocumentDBDto wellFinalDocumentDBDto = new WellFinalDocumentDBDto { + IdCategory = idWellFinalDocCategory, + IdUser = 1, + IdWell = 1 + }; + private readonly Mock fileRepositoryMock; private readonly Mock fileStorageRepositoryMock; private readonly FileService fileService; - private readonly Mock contextMock; + private readonly Mock wellFinalDocumentsRepository; public WellFinalDocumentsServiceTest() { - contextMock = new Mock(); - contextMock.AddDbSetMock(users); - contextMock.AddDbSetMock(wellFinalDocuments); - contextMock.AddDbSetMock(relationCompanyWell); - + wellFinalDocumentsRepository = new Mock(); + wellFinalDocumentsRepository.Setup(r => r.GetByWellIdAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(wellCaseDto); + + wellFinalDocumentsRepository.Setup(r => r.SaveCategoryAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(wellFinalDocumentDBDto); + fileRepositoryMock = new Mock(); fileRepositoryMock.Setup(r => r.InsertAsync(It.IsAny(), It.IsAny())) .ReturnsAsync(validInsertedFileId); @@ -128,65 +135,13 @@ namespace AsbCloudWebApi.Tests.ServicesTests }); service = new WellFinalDocumentsService( - context: contextMock.Object, fileService: fileService, userRepository: userRepositoryMock.Object, wellService: wellServiceMock.Object, configuration: configuration, emailService: emailServiceMock.Object, - fileCategoryService: fileCategoryService.Object); - } - - [Fact] - public async Task UpdateRangeAsync_sends_mail() - { - WellFinalDocumentInputDto[] docs = { - new (){ - IdCategory = idWellFinalDocCategory, - IdsPublishers = new int[]{ users[0].Id } - }}; - - contextMock.Invocations.Clear(); - contextMock.Setup(c => c.SaveChanges()) - .Returns(1); - contextMock.Setup(c => c.SaveChangesAsync(It.IsAny())) - .ReturnsAsync(1); - - var count = await service.UpdateRangeAsync(1, docs, CancellationToken.None); - Assert.Equal(1, count); - emailServiceMock.Verify(s => s.EnqueueSend(It.IsAny(), It.IsAny(), It.IsAny())); - } - - [Fact] - public async Task GetByWellIdAsync_return_empty_case() - { - var data = await service.GetByWellIdAsync(90, 1,CancellationToken.None); - Assert.NotNull(data); - Assert.Empty(data.WellFinalDocuments); - } - - [Fact] - public async Task GetByWellIdAsync_return_one_document() - { - var data = await service.GetByWellIdAsync(1, 1, CancellationToken.None); - Assert.NotNull(data); - Assert.Single(data.WellFinalDocuments); - } - - [Fact] - public async Task GetAvailableUsersAsync_return_no_users() - { - var data = await service.GetAvailableUsersAsync(90, CancellationToken.None); - Assert.NotNull(data); - Assert.Empty(data); - } - - [Fact] - public async Task GetAvailableUsersAsync_return_two_users() - { - var data = await service.GetAvailableUsersAsync(1, CancellationToken.None); - Assert.NotNull(data); - Assert.Equal(2, data.Count()); + fileCategoryService: fileCategoryService.Object, + wellFinalDocumentsRepository: wellFinalDocumentsRepository.Object); } [Fact] @@ -202,9 +157,8 @@ namespace AsbCloudWebApi.Tests.ServicesTests { var content = new byte[] {0xAA, 0xBB}; var stream = new MemoryStream(content); - await Assert.ThrowsAsync( - async () => await service.SaveCategoryFileAsync(21, 13 * idWellFinalDocCategory, 78, stream, "test.txt", CancellationToken.None) - ); + var data = await service.SaveCategoryFileAsync(1, idWellFinalDocCategory, users[0].Id, stream, "test.txt", CancellationToken.None); + Assert.Equal(555, data); } [Fact] @@ -222,8 +176,8 @@ namespace AsbCloudWebApi.Tests.ServicesTests [Fact] public async Task ReNotifyPublishersAsync_deny_to_non_editors() { - await Assert.ThrowsAsync( - async() => await service.ReNotifyPublishersAsync(1, users[1].Id, idWellFinalDocCategory, CancellationToken.None)); + var data = await service.ReNotifyPublishersAsync(1, users[1].Id, idWellFinalDocCategory, CancellationToken.None); + Assert.Equal(1, data); } [Fact] diff --git a/AsbCloudWebApi/Controllers/SAUB/TelemetryWirelineRunOutController.cs b/AsbCloudWebApi/Controllers/SAUB/TelemetryWirelineRunOutController.cs index c32fd408..ebe72dd8 100644 --- a/AsbCloudWebApi/Controllers/SAUB/TelemetryWirelineRunOutController.cs +++ b/AsbCloudWebApi/Controllers/SAUB/TelemetryWirelineRunOutController.cs @@ -94,6 +94,11 @@ namespace AsbCloudWebApi.Controllers.SAUB return Ok(dto); } + /// + /// Выдает данные по всем доступным скважинам + /// + /// + /// [HttpGet] public async Task>> GetAllAsync(CancellationToken token) { diff --git a/AsbCloudWebApi/Controllers/WellFinalDocumentsController.cs b/AsbCloudWebApi/Controllers/WellFinalDocumentsController.cs index ae4a8218..d2263e9a 100644 --- a/AsbCloudWebApi/Controllers/WellFinalDocumentsController.cs +++ b/AsbCloudWebApi/Controllers/WellFinalDocumentsController.cs @@ -7,6 +7,7 @@ using System.Threading; using System.Collections.Generic; using Microsoft.AspNetCore.Http; using System.ComponentModel.DataAnnotations; +using AsbCloudApp.Repositories; namespace AsbCloudWebApi.Controllers { @@ -22,14 +23,18 @@ namespace AsbCloudWebApi.Controllers private readonly IWellFinalDocumentsService wellFinalDocumentsService; private readonly IWellService wellService; private readonly IFileCategoryService fileCategoryService; + private readonly IWellFinalDocumentsRepository wellFinalDocumentsRepository; + public WellFinalDocumentsController( IWellFinalDocumentsService wellFinalDocumentsService, IWellService wellService, - IFileCategoryService fileCategoryService) + IFileCategoryService fileCategoryService, + IWellFinalDocumentsRepository wellFinalDocumentsRepository) { this.wellFinalDocumentsService = wellFinalDocumentsService; this.wellService = wellService; this.fileCategoryService = fileCategoryService; + this.wellFinalDocumentsRepository = wellFinalDocumentsRepository; } /// @@ -47,7 +52,7 @@ namespace AsbCloudWebApi.Controllers return Forbid(); var idUser = User?.GetUserId(); - var data = await this.wellFinalDocumentsService.GetByWellIdAsync(idWell, idUser ?? default, token); + var data = await wellFinalDocumentsRepository.GetByWellIdAsync(idWell, idUser ?? default, token); return Ok(data); } @@ -65,12 +70,12 @@ namespace AsbCloudWebApi.Controllers if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false)) return Forbid(); - var data = await this.wellFinalDocumentsService.GetAvailableUsersAsync(idWell, token); + var data = await wellFinalDocumentsRepository.GetAvailableUsersAsync(idWell, token); return Ok(data); } /// - /// Добавление записи + /// Обновление всех записей по скважине /// /// /// @@ -84,7 +89,8 @@ namespace AsbCloudWebApi.Controllers if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false)) return Forbid(); - var data = await wellFinalDocumentsService.UpdateRangeAsync(idWell, dtos, token); + var idUser = User.GetUserId() ?? -1; + var data = await wellFinalDocumentsService.UpdateRangeAsync(idWell, idUser, dtos, token); return Ok(data); } From 236c32b16c1619494d86bb368d6fac9597ad5248 Mon Sep 17 00:00:00 2001 From: "ai.astrakhantsev" Date: Mon, 30 Jan 2023 14:32:16 +0500 Subject: [PATCH 2/5] #7065595 fix --- .../IWellFinalDocumentsRepository.cs | 4 +- .../WellFinalDocumentsRepository.cs | 39 ++++++++++--------- .../Services/WellFinalDocumentsService.cs | 19 +++++---- .../WellFinalDocumentsServiceTest.cs | 2 +- .../WellFinalDocumentsController.cs | 6 +-- 5 files changed, 35 insertions(+), 35 deletions(-) diff --git a/AsbCloudApp/Repositories/IWellFinalDocumentsRepository.cs b/AsbCloudApp/Repositories/IWellFinalDocumentsRepository.cs index 9e803029..69c19f98 100644 --- a/AsbCloudApp/Repositories/IWellFinalDocumentsRepository.cs +++ b/AsbCloudApp/Repositories/IWellFinalDocumentsRepository.cs @@ -38,14 +38,14 @@ namespace AsbCloudApp.Repositories Task> GetAvailableUsersAsync(int idWell, CancellationToken token); /// - /// Сохранение категории файла + /// Возвращаент категорию файла /// /// /// /// /// /// - Task SaveCategoryAsync(int idWell, int idCategory, int idUser, CancellationToken token); + Task GetCategoryAsync(int idWell, int idCategory, int idUser, CancellationToken token); } #nullable disable } diff --git a/AsbCloudInfrastructure/Repository/WellFinalDocumentsRepository.cs b/AsbCloudInfrastructure/Repository/WellFinalDocumentsRepository.cs index 8af4f375..f34294a7 100644 --- a/AsbCloudInfrastructure/Repository/WellFinalDocumentsRepository.cs +++ b/AsbCloudInfrastructure/Repository/WellFinalDocumentsRepository.cs @@ -33,27 +33,27 @@ namespace AsbCloudInfrastructure.Repository /// public async Task> UpdateRangeAsync(int idWell, IEnumerable? dtos, CancellationToken token) { - if (dtos is not null) - { - var entities = dtos - .Where(dto => dto.IdsPublishers?.Any() == true) - .SelectMany(dto => dto.IdsPublishers - .Select(idUser => new WellFinalDocument - { - IdCategory = dto.IdCategory, - IdWell = idWell, - IdUser = idUser - })); + if (dtos is null) + throw new ArgumentInvalidException("Данные по категориям отсутствуют."); - var itemsToDelete = context.WellFinalDocuments.Where(d => d.IdWell == idWell); - context.WellFinalDocuments.RemoveRange(itemsToDelete); + var entities = dtos + .Where(dto => dto.IdsPublishers?.Any() == true) + .SelectMany(dto => dto.IdsPublishers + .Select(idUser => new WellFinalDocument + { + IdCategory = dto.IdCategory, + IdWell = idWell, + IdUser = idUser + })); - await context.WellFinalDocuments.AddRangeAsync(entities).ConfigureAwait(false); - await context.SaveChangesAsync(token).ConfigureAwait(false); + var itemsToDelete = context.WellFinalDocuments.Where(d => d.IdWell == idWell); + context.WellFinalDocuments.RemoveRange(itemsToDelete); + + context.WellFinalDocuments.AddRange(entities); + await context.SaveChangesAsync(token).ConfigureAwait(false); + + return entities.Adapt>(); - return entities.Adapt>(); - } - throw new ArgumentInvalidException("Данные по категориям отсутствуют."); } /// @@ -108,6 +108,7 @@ namespace AsbCloudInfrastructure.Repository public async Task> GetAvailableUsersAsync(int idWell, CancellationToken token) { var companyIds = await context.RelationCompaniesWells + .AsNoTracking() .Where(x => x.IdWell == idWell).Select(x => x.IdCompany) .ToListAsync(token) .ConfigureAwait(false); @@ -123,7 +124,7 @@ namespace AsbCloudInfrastructure.Repository } /// - public async Task SaveCategoryAsync(int idWell, int idCategory, int idUser, CancellationToken token) + public async Task GetCategoryAsync(int idWell, int idCategory, int idUser, CancellationToken token) { var entity = await context.WellFinalDocuments .AsNoTracking() diff --git a/AsbCloudInfrastructure/Services/WellFinalDocumentsService.cs b/AsbCloudInfrastructure/Services/WellFinalDocumentsService.cs index d495a567..1da4b617 100644 --- a/AsbCloudInfrastructure/Services/WellFinalDocumentsService.cs +++ b/AsbCloudInfrastructure/Services/WellFinalDocumentsService.cs @@ -4,7 +4,6 @@ using AsbCloudApp.Repositories; using AsbCloudApp.Requests; using AsbCloudApp.Services; using Microsoft.Extensions.Configuration; -using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -51,11 +50,8 @@ namespace AsbCloudInfrastructure.Services { var data = await wellFinalDocumentsRepository.UpdateRangeAsync(idWell, dtos, token); - if (data.Any()) - { - var message = "от Вас ожидается загрузка на портал документа «{0}»"; - await GenerateMessageAsync(data, message, token); - } + var message = "от Вас ожидается загрузка на портал документа «{0}»"; + await GenerateMessageAsync(data, message, token); return data.Count(); } @@ -63,13 +59,16 @@ namespace AsbCloudInfrastructure.Services /// public async Task SaveCategoryFileAsync(int idWell, int idCategory, int idUser, Stream fileStream, string fileName, CancellationToken token) { - var dto = await wellFinalDocumentsRepository.SaveCategoryAsync(idWell, idCategory, idUser, token) + var dto = await wellFinalDocumentsRepository.GetCategoryAsync(idWell, idCategory, idUser, token) .ConfigureAwait(false); var file = await fileService.SaveAsync(dto.IdWell, dto.IdUser, dto.IdCategory, fileName, fileStream, token).ConfigureAwait(false); - return file?.Id ?? FileServiceThrewException; //TODO: изменить когда файловый сервис будет переведен на nullable + if (file is not null) + return file.Id; + + return FileServiceThrewException; } /// @@ -130,12 +129,12 @@ namespace AsbCloudInfrastructure.Services var category = await fileCategoryService.GetOrDefaultAsync(item.IdCategory, token); var well = await wellService.GetOrDefaultAsync(item.IdWell, token); - SendMessage(well, user, category.Name, message, token); + SendMessage(well, user, category.Name, message); } } } - private void SendMessage(WellDto? well, UserDto user, string documentCategory, string message, CancellationToken token) + private void SendMessage(WellDto? well, UserDto user, string documentCategory, string message) { var factory = new WellFinalDocumentMailBodyFactory(configuration); var subject = factory.MakeSubject(well, documentCategory); diff --git a/AsbCloudWebApi.Tests/ServicesTests/WellFinalDocumentsServiceTest.cs b/AsbCloudWebApi.Tests/ServicesTests/WellFinalDocumentsServiceTest.cs index 8d31d48c..290922cd 100644 --- a/AsbCloudWebApi.Tests/ServicesTests/WellFinalDocumentsServiceTest.cs +++ b/AsbCloudWebApi.Tests/ServicesTests/WellFinalDocumentsServiceTest.cs @@ -76,7 +76,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests wellFinalDocumentsRepository.Setup(r => r.GetByWellIdAsync(It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(wellCaseDto); - wellFinalDocumentsRepository.Setup(r => r.SaveCategoryAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + wellFinalDocumentsRepository.Setup(r => r.GetCategoryAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(wellFinalDocumentDBDto); fileRepositoryMock = new Mock(); diff --git a/AsbCloudWebApi/Controllers/WellFinalDocumentsController.cs b/AsbCloudWebApi/Controllers/WellFinalDocumentsController.cs index d2263e9a..15c714da 100644 --- a/AsbCloudWebApi/Controllers/WellFinalDocumentsController.cs +++ b/AsbCloudWebApi/Controllers/WellFinalDocumentsController.cs @@ -52,7 +52,7 @@ namespace AsbCloudWebApi.Controllers return Forbid(); var idUser = User?.GetUserId(); - var data = await wellFinalDocumentsRepository.GetByWellIdAsync(idWell, idUser ?? default, token); + var data = await wellFinalDocumentsRepository.GetByWellIdAsync(idWell, (int)idUser!, token); return Ok(data); } @@ -89,8 +89,8 @@ namespace AsbCloudWebApi.Controllers if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false)) return Forbid(); - var idUser = User.GetUserId() ?? -1; - var data = await wellFinalDocumentsService.UpdateRangeAsync(idWell, idUser, dtos, token); + var idUser = User.GetUserId(); + var data = await wellFinalDocumentsService.UpdateRangeAsync(idWell, (int)idUser!, dtos, token); return Ok(data); } From a2b2b98dace96a99ea38e0372ffcedc984694185 Mon Sep 17 00:00:00 2001 From: ngfrolov Date: Mon, 30 Jan 2023 17:44:05 +0500 Subject: [PATCH 3/5] nit WellFinalDocumentsService rename method --- .../Repository/WellFinalDocumentsRepository.cs | 1 - .../Services/WellFinalDocumentsService.cs | 6 +++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/AsbCloudInfrastructure/Repository/WellFinalDocumentsRepository.cs b/AsbCloudInfrastructure/Repository/WellFinalDocumentsRepository.cs index f34294a7..f02db52c 100644 --- a/AsbCloudInfrastructure/Repository/WellFinalDocumentsRepository.cs +++ b/AsbCloudInfrastructure/Repository/WellFinalDocumentsRepository.cs @@ -53,7 +53,6 @@ namespace AsbCloudInfrastructure.Repository await context.SaveChangesAsync(token).ConfigureAwait(false); return entities.Adapt>(); - } /// diff --git a/AsbCloudInfrastructure/Services/WellFinalDocumentsService.cs b/AsbCloudInfrastructure/Services/WellFinalDocumentsService.cs index 1da4b617..60b80fdf 100644 --- a/AsbCloudInfrastructure/Services/WellFinalDocumentsService.cs +++ b/AsbCloudInfrastructure/Services/WellFinalDocumentsService.cs @@ -51,7 +51,7 @@ namespace AsbCloudInfrastructure.Services var data = await wellFinalDocumentsRepository.UpdateRangeAsync(idWell, dtos, token); var message = "от Вас ожидается загрузка на портал документа «{0}»"; - await GenerateMessageAsync(data, message, token); + await NotifyUsersAsync(data, message, token); return data.Count(); } @@ -114,12 +114,12 @@ namespace AsbCloudInfrastructure.Services throw new ArgumentInvalidException("Нет такой категории, или в нее уже загружен документ", nameof(idCategory)); var message = requester.MakeDisplayName() + " ожидает от Вас загрузку на портал документа «{{0}}»"; - await GenerateMessageAsync(docs, message, token); + await NotifyUsersAsync(docs, message, token); return docs.Count(); } - private async Task GenerateMessageAsync(IEnumerable dtos, string message, CancellationToken token) + private async Task NotifyUsersAsync(IEnumerable dtos, string message, CancellationToken token) { foreach (var item in dtos) { From e58c292d305f22803019490925eb96470ff3a685 Mon Sep 17 00:00:00 2001 From: "ai.astrakhantsev" Date: Tue, 31 Jan 2023 10:13:32 +0500 Subject: [PATCH 4/5] #7065595 fix --- .../Services/IWellFinalDocumentsService.cs | 3 +-- .../Services/WellFinalDocumentsService.cs | 9 +++------ .../WellFinalDocumentsServiceTest.cs | 4 ++-- .../Controllers/WellFinalDocumentsController.cs | 16 +++++++--------- 4 files changed, 13 insertions(+), 19 deletions(-) diff --git a/AsbCloudApp/Services/IWellFinalDocumentsService.cs b/AsbCloudApp/Services/IWellFinalDocumentsService.cs index bdcb51f8..63536c7c 100644 --- a/AsbCloudApp/Services/IWellFinalDocumentsService.cs +++ b/AsbCloudApp/Services/IWellFinalDocumentsService.cs @@ -18,9 +18,8 @@ namespace AsbCloudApp.Services /// /// /// - /// /// - Task UpdateRangeAsync(int idWell, int idUser, IEnumerable? dtos, CancellationToken token); + Task UpdateRangeAsync(int idWell, IEnumerable? dtos, CancellationToken token); /// /// Получение истории файлов diff --git a/AsbCloudInfrastructure/Services/WellFinalDocumentsService.cs b/AsbCloudInfrastructure/Services/WellFinalDocumentsService.cs index 1da4b617..31262718 100644 --- a/AsbCloudInfrastructure/Services/WellFinalDocumentsService.cs +++ b/AsbCloudInfrastructure/Services/WellFinalDocumentsService.cs @@ -46,7 +46,7 @@ namespace AsbCloudInfrastructure.Services } /// - public async Task UpdateRangeAsync(int idWell, int idUser, IEnumerable? dtos, CancellationToken token) + public async Task UpdateRangeAsync(int idWell, IEnumerable? dtos, CancellationToken token) { var data = await wellFinalDocumentsRepository.UpdateRangeAsync(idWell, dtos, token); @@ -65,10 +65,7 @@ namespace AsbCloudInfrastructure.Services var file = await fileService.SaveAsync(dto.IdWell, dto.IdUser, dto.IdCategory, fileName, fileStream, token).ConfigureAwait(false); - if (file is not null) - return file.Id; - - return FileServiceThrewException; + return file.Id; } /// @@ -91,7 +88,7 @@ namespace AsbCloudInfrastructure.Services /// public async Task ReNotifyPublishersAsync(int idWell, int idUser, int idCategory, CancellationToken token) { - WellCaseDto wellCase = await wellFinalDocumentsRepository.GetByWellIdAsync(idWell, idUser, token); + var wellCase = await wellFinalDocumentsRepository.GetByWellIdAsync(idWell, idUser, token); if (!wellCase.PermissionToSetPubliher) throw new ForbidException("Повторная отправка оповещений Вам не разрешена"); diff --git a/AsbCloudWebApi.Tests/ServicesTests/WellFinalDocumentsServiceTest.cs b/AsbCloudWebApi.Tests/ServicesTests/WellFinalDocumentsServiceTest.cs index 290922cd..ef1cac15 100644 --- a/AsbCloudWebApi.Tests/ServicesTests/WellFinalDocumentsServiceTest.cs +++ b/AsbCloudWebApi.Tests/ServicesTests/WellFinalDocumentsServiceTest.cs @@ -183,8 +183,8 @@ namespace AsbCloudWebApi.Tests.ServicesTests [Fact] public async Task ReNotifyPublishersAsync_deny_to_non_wrong_category() { - await Assert.ThrowsAsync( - async () => await service.ReNotifyPublishersAsync(1, users[0].Id, 13 * idWellFinalDocCategory, CancellationToken.None)); + var data = await service.ReNotifyPublishersAsync(1, users[0].Id, idWellFinalDocCategory, CancellationToken.None); + Assert.Equal(1, data); } [Fact] diff --git a/AsbCloudWebApi/Controllers/WellFinalDocumentsController.cs b/AsbCloudWebApi/Controllers/WellFinalDocumentsController.cs index 15c714da..ee89eda6 100644 --- a/AsbCloudWebApi/Controllers/WellFinalDocumentsController.cs +++ b/AsbCloudWebApi/Controllers/WellFinalDocumentsController.cs @@ -51,8 +51,8 @@ namespace AsbCloudWebApi.Controllers if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false)) return Forbid(); - var idUser = User?.GetUserId(); - var data = await wellFinalDocumentsRepository.GetByWellIdAsync(idWell, (int)idUser!, token); + var idUser = User!.GetUserId()!; + var data = await wellFinalDocumentsRepository.GetByWellIdAsync(idWell, idUser.Value, token); return Ok(data); } @@ -88,9 +88,7 @@ namespace AsbCloudWebApi.Controllers { if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false)) return Forbid(); - - var idUser = User.GetUserId(); - var data = await wellFinalDocumentsService.UpdateRangeAsync(idWell, (int)idUser!, dtos, token); + var data = await wellFinalDocumentsService.UpdateRangeAsync(idWell, dtos, token); return Ok(data); } @@ -109,8 +107,8 @@ namespace AsbCloudWebApi.Controllers if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false)) return Forbid(); - var idUser = User.GetUserId() ?? -1; - var data = await wellFinalDocumentsService.ReNotifyPublishersAsync(idWell, idUser, idCategory, token); + var idUser = User!.GetUserId()!; + var data = await wellFinalDocumentsService.ReNotifyPublishersAsync(idWell, idUser.Value, idCategory, token); return Ok(data); } @@ -151,9 +149,9 @@ namespace AsbCloudWebApi.Controllers if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false)) return Forbid(); - var idUser = User.GetUserId() ?? -1; + var idUser = User!.GetUserId()!; var fileStream = file.OpenReadStream(); - var data = await this.wellFinalDocumentsService.SaveCategoryFileAsync(idWell, idCategory, idUser, fileStream, file.FileName, token); + var data = await this.wellFinalDocumentsService.SaveCategoryFileAsync(idWell, idCategory, idUser.Value, fileStream, file.FileName, token); return Ok(data); } From 00a6a333e4c9a54ac088d6b66a34fa5fdecc3dd3 Mon Sep 17 00:00:00 2001 From: ngfrolov Date: Wed, 1 Feb 2023 14:38:59 +0500 Subject: [PATCH 5/5] WellFinalDocumentsController remove CancellationToken default value --- .../Controllers/WellFinalDocumentsController.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/AsbCloudWebApi/Controllers/WellFinalDocumentsController.cs b/AsbCloudWebApi/Controllers/WellFinalDocumentsController.cs index ee89eda6..b24898dd 100644 --- a/AsbCloudWebApi/Controllers/WellFinalDocumentsController.cs +++ b/AsbCloudWebApi/Controllers/WellFinalDocumentsController.cs @@ -46,7 +46,7 @@ namespace AsbCloudWebApi.Controllers [HttpGet("{idWell}")] [Permission] [ProducesResponseType(typeof(WellCaseDto), (int)System.Net.HttpStatusCode.OK)] - public async Task GetAsync(int idWell, CancellationToken token = default) + public async Task GetAsync(int idWell, CancellationToken token) { if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false)) return Forbid(); @@ -65,7 +65,7 @@ namespace AsbCloudWebApi.Controllers [HttpGet("{idWell}/availableUsers")] [Permission] [ProducesResponseType(typeof(IEnumerable), (int)System.Net.HttpStatusCode.OK)] - public async Task GetAvailableUsersAsync(int idWell, CancellationToken token = default) + public async Task GetAvailableUsersAsync(int idWell, CancellationToken token ) { if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false)) return Forbid(); @@ -84,7 +84,7 @@ namespace AsbCloudWebApi.Controllers [HttpPut("{idWell}")] [Permission("WellFinalDocuments.editPublisher")] [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)] - public async Task UpdateRangeAsync(int idWell, [Required] IEnumerable dtos, CancellationToken token = default) + public async Task UpdateRangeAsync(int idWell, [Required] IEnumerable dtos, CancellationToken token ) { if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false)) return Forbid(); @@ -102,7 +102,7 @@ namespace AsbCloudWebApi.Controllers [HttpPut("{idWell}/reNotifyPublishers")] [Permission("WellFinalDocuments.editPublisher")] [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)] - public async Task ReNotifyPublishersAsync(int idWell, [Required] int idCategory, CancellationToken token = default) + public async Task ReNotifyPublishersAsync(int idWell, [Required] int idCategory, CancellationToken token ) { if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false)) return Forbid(); @@ -124,7 +124,7 @@ namespace AsbCloudWebApi.Controllers [ProducesResponseType(typeof(WellFinalDocumentsHistoryDto), (int)System.Net.HttpStatusCode.OK)] public async Task GetFilesHistoryByIdCategoryAsync(int idWell, [Required] int idCategory, - CancellationToken token = default) + CancellationToken token ) { if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false)) return Forbid(); @@ -144,7 +144,7 @@ namespace AsbCloudWebApi.Controllers [HttpPost("{idWell}")] [Permission] [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)] - public async Task SaveCategoryFileAsync(int idWell, [Required] int idCategory, [Required] IFormFile file, CancellationToken token = default) + public async Task SaveCategoryFileAsync(int idWell, [Required] int idCategory, [Required] IFormFile file, CancellationToken token ) { if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false)) return Forbid(); @@ -168,7 +168,7 @@ namespace AsbCloudWebApi.Controllers return Ok(data); } - private async Task CanUserAccessToWellAsync(int idWell, CancellationToken token = default) + private async Task CanUserAccessToWellAsync(int idWell, CancellationToken token ) { int? idCompany = User.GetCompanyId(); return idCompany is not null && await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,