From 0ad4cebdb8c229b845c5534586e0f507d06787aa Mon Sep 17 00:00:00 2001 From: "ai.astrakhantsev" Date: Thu, 8 Sep 2022 12:05:56 +0500 Subject: [PATCH] =?UTF-8?q?#5998816=20=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B7=D0=B0=D0=BC=D0=B5=D1=87?= =?UTF-8?q?=D0=B0=D0=BD=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AsbCloudApp/Data/FileCategoryDto.cs | 2 + AsbCloudApp/Data/WellFinalDocumentsDBDto.cs | 4 +- AsbCloudApp/Data/WellFinalDocumentsDto.cs | 12 +- .../Data/WellFinalDocumentsHistoryDto.cs | 4 +- AsbCloudApp/Services/IFileCategoryService.cs | 2 + .../Services/IWellFinalDocumentsService.cs | 32 ++--- AsbCloudDb/Model/AsbCloudDbContext.cs | 6 - .../DrillingProgram/DrillingProgramService.cs | 16 +-- .../Services/Email/BaseFactory.cs | 55 +++++++++ ...yFactory.cs => DrillingMailBodyFactory.cs} | 43 +------ .../WellFinalDocumentMailBodyFactory .cs | 32 +++++ .../Services/FileCategoryService.cs | 10 ++ .../Services/WellFinalDocumentsService.cs | 116 +++++++----------- .../WellFinalDocumentsServiceTest.cs | 18 +-- .../WellFinalDocumentsController.cs | 26 ++-- 15 files changed, 209 insertions(+), 169 deletions(-) create mode 100644 AsbCloudInfrastructure/Services/Email/BaseFactory.cs rename AsbCloudInfrastructure/Services/Email/{MailBodyFactory.cs => DrillingMailBodyFactory.cs} (69%) create mode 100644 AsbCloudInfrastructure/Services/Email/WellFinalDocumentMailBodyFactory .cs diff --git a/AsbCloudApp/Data/FileCategoryDto.cs b/AsbCloudApp/Data/FileCategoryDto.cs index d21a558c..b432c1df 100644 --- a/AsbCloudApp/Data/FileCategoryDto.cs +++ b/AsbCloudApp/Data/FileCategoryDto.cs @@ -1,5 +1,6 @@ namespace AsbCloudApp.Data { +#nullable enable /// /// DTO категории файла /// @@ -18,4 +19,5 @@ /// public string ShortName { get; set; } } +#nullable disable } diff --git a/AsbCloudApp/Data/WellFinalDocumentsDBDto.cs b/AsbCloudApp/Data/WellFinalDocumentsDBDto.cs index b9bef6a3..78141f4d 100644 --- a/AsbCloudApp/Data/WellFinalDocumentsDBDto.cs +++ b/AsbCloudApp/Data/WellFinalDocumentsDBDto.cs @@ -1,5 +1,6 @@ namespace AsbCloudApp.Data { +#nullable enable /// /// DTO Дело скважины /// @@ -11,7 +12,7 @@ public int Id { get; set; } /// - /// Идентификатор вышка + /// Идентификатор скважины /// public int IdWell { get; set; } @@ -30,4 +31,5 @@ /// public int? IdFile { get; set; } } +#nullable disable } diff --git a/AsbCloudApp/Data/WellFinalDocumentsDto.cs b/AsbCloudApp/Data/WellFinalDocumentsDto.cs index 7e3d16cb..1a631f39 100644 --- a/AsbCloudApp/Data/WellFinalDocumentsDto.cs +++ b/AsbCloudApp/Data/WellFinalDocumentsDto.cs @@ -3,31 +3,31 @@ using System.Linq; namespace AsbCloudApp.Data { -#nullable disable +#nullable enable /// - /// DTO Дело скважины + /// DTO Документ дела скважины /// public class WellFinalDocumentsDto { /// - /// Вышка + /// Скважина /// public int IdWell { get; set; } /// - /// Наменование категории файла + /// Наименование категории файла /// public string NameCategory { get; set; } /// /// Список ответственных /// - public IEnumerable ListResponsible { get; set; } = Enumerable.Empty(); + public IEnumerable Publishers { get; set; } = Enumerable.Empty(); /// /// Количество файлов этой категории загруженных ранее /// - public int CountFiles { get; set; } + public int FilesCount { get; set; } /// /// Актуальный файл diff --git a/AsbCloudApp/Data/WellFinalDocumentsHistoryDto.cs b/AsbCloudApp/Data/WellFinalDocumentsHistoryDto.cs index 89ad54fd..24500db9 100644 --- a/AsbCloudApp/Data/WellFinalDocumentsHistoryDto.cs +++ b/AsbCloudApp/Data/WellFinalDocumentsHistoryDto.cs @@ -2,6 +2,7 @@ namespace AsbCloudApp.Data { +#nullable enable /// /// DTO Дело скважины, история файлов /// @@ -13,7 +14,7 @@ namespace AsbCloudApp.Data public int IdWell { get; set; } /// - /// Наменование категории файла + /// Наименование категории файла /// public int IdCategory { get; set; } @@ -22,4 +23,5 @@ namespace AsbCloudApp.Data /// public List File { get; set; } } +#nullable disable } diff --git a/AsbCloudApp/Services/IFileCategoryService.cs b/AsbCloudApp/Services/IFileCategoryService.cs index 5b997483..01710c8e 100644 --- a/AsbCloudApp/Services/IFileCategoryService.cs +++ b/AsbCloudApp/Services/IFileCategoryService.cs @@ -10,6 +10,8 @@ namespace AsbCloudApp.Services /// public interface IFileCategoryService { + Task GetOrDefaultAsync(int id, CancellationToken token); + /// /// Получение справочника категорий файлов /// diff --git a/AsbCloudApp/Services/IWellFinalDocumentsService.cs b/AsbCloudApp/Services/IWellFinalDocumentsService.cs index c4b4b627..51665b51 100644 --- a/AsbCloudApp/Services/IWellFinalDocumentsService.cs +++ b/AsbCloudApp/Services/IWellFinalDocumentsService.cs @@ -1,14 +1,12 @@ using AsbCloudApp.Data; -using System; using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; using System.Threading; using System.Threading.Tasks; namespace AsbCloudApp.Services { +#nullable enable /// /// Сервис "Дело скважины" /// @@ -20,7 +18,7 @@ namespace AsbCloudApp.Services /// /// /// - Task> GetByWellId(int idWell, CancellationToken token); + Task> GetByWellId(int idWell, CancellationToken token); /// /// Получение списка ответственных @@ -28,23 +26,7 @@ namespace AsbCloudApp.Services /// /// /// - Task> GetListResponsiblesAsync(int idWell, CancellationToken token); - - /// - /// Добавление записи - /// - /// - /// - /// - Task InsertRangeAsync(List dtos, CancellationToken token); - - /// - /// Удалить запись - /// - /// - /// - /// - Task DeleteAsync(int dtoId, CancellationToken token); + Task> GetPublishersAsync(int idWell, CancellationToken token); /// /// Получение истории файлов @@ -53,16 +35,18 @@ namespace AsbCloudApp.Services /// /// /// - Task GetHistoryFileByIdCategory(int idWell, int idCategory, CancellationToken token); + Task GetFilesHistoryByIdCategory(int idWell, int idCategory, CancellationToken token); /// /// Сохранение файла /// /// + /// /// /// /// /// - Task SaveCategoryFile(int idDto, Stream fileStream, string fileName, CancellationToken token); + Task SaveCategoryFile(int idDto, int idUser, Stream fileStream, string fileName, CancellationToken token); } -} +#nullable disable +} \ No newline at end of file diff --git a/AsbCloudDb/Model/AsbCloudDbContext.cs b/AsbCloudDb/Model/AsbCloudDbContext.cs index 73c68729..09f77820 100644 --- a/AsbCloudDb/Model/AsbCloudDbContext.cs +++ b/AsbCloudDb/Model/AsbCloudDbContext.cs @@ -344,12 +344,6 @@ namespace AsbCloudDb.Model }); DefaultData.DefaultContextData.Fill(modelBuilder); - - modelBuilder.Entity(entity => - { - entity.HasKey(d => new { d.Id }) - .HasName("t_well_final_documents_pk"); - }); } public Task RefreshMaterializedViewAsync(CancellationToken token) diff --git a/AsbCloudInfrastructure/Services/DrillingProgram/DrillingProgramService.cs b/AsbCloudInfrastructure/Services/DrillingProgram/DrillingProgramService.cs index ee0b3aa8..5fbc7301 100644 --- a/AsbCloudInfrastructure/Services/DrillingProgram/DrillingProgramService.cs +++ b/AsbCloudInfrastructure/Services/DrillingProgram/DrillingProgramService.cs @@ -359,8 +359,8 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram var file = await fileService.GetInfoAsync(fileMark.IdFile, token); var well = await wellService.GetOrDefaultAsync(file.IdWell, token); var user = file.Author; - var factory = new MailBodyFactory(configuration); - var subject = MailBodyFactory.MakeSubject(well, "Загруженный вами документ полностью согласован"); + var factory = new DrillingMailBodyFactory(configuration); + var subject = factory.MakeSubject(well, "Загруженный вами документ полностью согласован"); var body = factory.MakeMailBodyForPublisherOnFullAccept(well, user.Name, file.Id, file.Name); emailService.EnqueueSend(user.Email, subject, body); @@ -371,8 +371,8 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram var file = await fileService.GetInfoAsync(fileMark.IdFile, token); var well = await wellService.GetOrDefaultAsync(file.IdWell, token); var user = file.Author; - var factory = new MailBodyFactory(configuration); - var subject = MailBodyFactory.MakeSubject(well, "Загруженный вами документ отклонен"); + var factory = new DrillingMailBodyFactory(configuration); + var subject = factory.MakeSubject(well, "Загруженный вами документ отклонен"); var body = factory.MakeMailBodyForPublisherOnReject(well, user.Name, file.Id, file.Name, fileMark); emailService.EnqueueSend(user.Email, subject, body); @@ -381,8 +381,8 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram private async Task NotifyApproversAsync(DrillingProgramPart part, int idFile, string fileName, CancellationToken token) { var well = await wellService.GetOrDefaultAsync(part.IdWell, token); - var factory = new MailBodyFactory(configuration); - var subject = MailBodyFactory.MakeSubject(well, "Загружен новый документ для согласования."); + var factory = new DrillingMailBodyFactory(configuration); + var subject = factory.MakeSubject(well, "Загружен новый документ для согласования."); var users = part.RelatedUsers .Where(r => r.IdUserRole == idUserRoleApprover) .Select(r => r.User); @@ -397,8 +397,8 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram private async Task NotifyNewPublisherAsync(int idWell, UserDto user, string documentCategory, CancellationToken token) { var well = await wellService.GetOrDefaultAsync(idWell, token); - var factory = new MailBodyFactory(configuration); - var subject = MailBodyFactory.MakeSubject(well, $"От вас ожидается загрузка на портал документа «{documentCategory}»"); + var factory = new DrillingMailBodyFactory(configuration); + var subject = factory.MakeSubject(well, $"От вас ожидается загрузка на портал документа «{documentCategory}»"); var body = factory.MakeMailBodyForNewPublisher(well, user.Name, documentCategory); emailService.EnqueueSend(user.Email, subject, body); } diff --git a/AsbCloudInfrastructure/Services/Email/BaseFactory.cs b/AsbCloudInfrastructure/Services/Email/BaseFactory.cs new file mode 100644 index 00000000..1e94cab3 --- /dev/null +++ b/AsbCloudInfrastructure/Services/Email/BaseFactory.cs @@ -0,0 +1,55 @@ +using AsbCloudApp.Data; +using Microsoft.Extensions.Configuration; +using System; +using System.IO; + +namespace AsbCloudInfrastructure.Services.Email +{ + public class BaseFactory + { + private readonly string platformName; + private readonly string platformUrl; + private readonly string companyName; + private readonly string supportMail; + + public BaseFactory(IConfiguration configuration) + { + platformName = configuration.GetValue("email:platformName", "Цифровое бурение"); + platformUrl = configuration.GetValue("email:platformUrl", "https://cloud.digitaldrilling.ru/"); + companyName = configuration.GetValue("email:companyName", "ООО \"Цифровое бурение\""); + supportMail = configuration.GetValue("email:supportMail", "support@digitaldrilling.ru"); + } + + public static string GetImageBase64(string resourceFileName) + { + if (string.IsNullOrEmpty(resourceFileName)) + return null; + + var baseDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); + var resoursesDir = "Res"; + + var logoFilePath = Path.Combine(baseDir, resoursesDir, resourceFileName); + + var imageBytes = File.ReadAllBytes(logoFilePath); + var format = Path.GetExtension(resourceFileName).Trim('.'); + return "data:image/" + format + ";base64," + Convert.ToBase64String(imageBytes); + } + + public static string MakeHref(string url, string text) + => $"{text}"; + + public string MakeSignatue() + { + var logo = GetImageBase64("logo_32.png"); + var sign = $"

---

" + + $"{companyName}
" + + $"Это письмо сформировано автоматически.
" + + $"Для получения помощи по работе на портале {platformName}" + + $"обращайтесь по адресу {supportMail}"; + return sign; + } + + public virtual string MakeSubject(WellDto well, string action) + => $"{well.Deposit}, {well.Cluster}, {well.Caption}. {action}"; + } +} diff --git a/AsbCloudInfrastructure/Services/Email/MailBodyFactory.cs b/AsbCloudInfrastructure/Services/Email/DrillingMailBodyFactory.cs similarity index 69% rename from AsbCloudInfrastructure/Services/Email/MailBodyFactory.cs rename to AsbCloudInfrastructure/Services/Email/DrillingMailBodyFactory.cs index 4ca82d87..664fee99 100644 --- a/AsbCloudInfrastructure/Services/Email/MailBodyFactory.cs +++ b/AsbCloudInfrastructure/Services/Email/DrillingMailBodyFactory.cs @@ -1,26 +1,24 @@ using AsbCloudApp.Data; +using AsbCloudInfrastructure.Services.Email; using Microsoft.Extensions.Configuration; using System; using System.IO; namespace AsbCloudInfrastructure { - class MailBodyFactory - { + class DrillingMailBodyFactory : BaseFactory + { private readonly string platformName; private readonly string platformUrl; - private readonly string companyName; - private readonly string supportMail; - public MailBodyFactory(IConfiguration configuration) + public DrillingMailBodyFactory(IConfiguration configuration) + : base(configuration) { platformName = configuration.GetValue("email:platformName", "Цифровое бурение"); platformUrl = configuration.GetValue("email:platformUrl", "https://cloud.digitaldrilling.ru/"); - companyName = configuration.GetValue("email:companyName", "ООО \"Цифровое бурение\""); - supportMail = configuration.GetValue("email:supportMail", "support@digitaldrilling.ru"); } - public static string MakeSubject(WellDto well, string action) + public override string MakeSubject(WellDto well, string action) { var subj = $"{well.Deposit}, {well.Cluster}, {well.Caption}. Программа бурения. {action}"; return subj; @@ -85,34 +83,5 @@ namespace AsbCloudInfrastructure var drillingProgramHref = MakeHref(drillingProgramUrl, well.Caption); return drillingProgramHref; } - - private static string MakeHref(string url, string text) - => $"{text}"; - - protected string MakeSignatue() - { - var logo = GetImageBase64("logo_32.png"); - var sign = $"

---

" + - $"{companyName}
" + - $"Это письмо сформировано автоматически.
" + - $"Для получения помощи по работе на портале {platformName}" + - $"обращайтесь по адресу {supportMail}"; - return sign; - } - - public static string GetImageBase64(string resourceFileName) - { - if (string.IsNullOrEmpty(resourceFileName)) - return null; - - var baseDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); - var resoursesDir = "Res"; - - var logoFilePath = Path.Combine(baseDir, resoursesDir, resourceFileName); - - var imageBytes = File.ReadAllBytes(logoFilePath); - var format = Path.GetExtension(resourceFileName).Trim('.'); - return "data:image/" + format + ";base64," + Convert.ToBase64String(imageBytes); - } } } diff --git a/AsbCloudInfrastructure/Services/Email/WellFinalDocumentMailBodyFactory .cs b/AsbCloudInfrastructure/Services/Email/WellFinalDocumentMailBodyFactory .cs new file mode 100644 index 00000000..e83fa55a --- /dev/null +++ b/AsbCloudInfrastructure/Services/Email/WellFinalDocumentMailBodyFactory .cs @@ -0,0 +1,32 @@ +using AsbCloudApp.Data; +using AsbCloudInfrastructure.Services.Email; +using Microsoft.Extensions.Configuration; +using System; +using System.IO; + +namespace AsbCloudInfrastructure +{ + class WellFinalDocumentMailBodyFactory : BaseFactory + { + private readonly string platformName; + + public WellFinalDocumentMailBodyFactory(IConfiguration configuration) + : base(configuration) + { + platformName = configuration.GetValue("email:platformName", "Цифровое бурение"); + } + + public override string MakeSubject(WellDto well, string action) + => $"{well.Deposit}, {well.Cluster}, {well.Caption}. Дело скважины. {action}"; + + public string MakeMailBodyForWellFinalDocument(WellDto well, string publisherName, string message) + { + var body = $"

Здравствуйте, {publisherName}.

" + + $"На портале {platformName} {message}," + + $" куст {well.Cluster}, месторождение {well.Deposit}." + + MakeSignatue() + + $""; + return body; + } + } +} diff --git a/AsbCloudInfrastructure/Services/FileCategoryService.cs b/AsbCloudInfrastructure/Services/FileCategoryService.cs index 4b2c34c7..c37a3885 100644 --- a/AsbCloudInfrastructure/Services/FileCategoryService.cs +++ b/AsbCloudInfrastructure/Services/FileCategoryService.cs @@ -2,6 +2,7 @@ using AsbCloudApp.Services; using AsbCloudDb.Model; using AsbCloudInfrastructure.Repository; +using DocumentFormat.OpenXml.InkML; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; @@ -35,5 +36,14 @@ namespace AsbCloudInfrastructure.Services return data.ToList(); } + + public override async Task GetOrDefaultAsync(int id, CancellationToken token) + { + var entity = await db.FileCategories + .FirstOrDefaultAsync(x => x.Id == id) + .ConfigureAwait(false); + var dto = Convert(entity); + return dto; + } } } diff --git a/AsbCloudInfrastructure/Services/WellFinalDocumentsService.cs b/AsbCloudInfrastructure/Services/WellFinalDocumentsService.cs index ee4b6bb4..f1a95953 100644 --- a/AsbCloudInfrastructure/Services/WellFinalDocumentsService.cs +++ b/AsbCloudInfrastructure/Services/WellFinalDocumentsService.cs @@ -1,4 +1,5 @@ using AsbCloudApp.Data; +using AsbCloudApp.Exceptions; using AsbCloudApp.Services; using AsbCloudDb.Model; using AsbCloudInfrastructure.Repository; @@ -24,13 +25,16 @@ namespace AsbCloudInfrastructure.Services private readonly IWellService wellService; private readonly IConfiguration configuration; private readonly IEmailService emailService; + private readonly IFileCategoryService fileCategoryService; + private const int ResultSaveCategoryFile = 0; public WellFinalDocumentsService(IAsbCloudDbContext context, IFileService fileService, IUserService userService, IWellService wellService, IConfiguration configuration, - IEmailService emailService) + IEmailService emailService, + IFileCategoryService fileCategoryService) : base(context) { this.context = context; @@ -39,51 +43,43 @@ namespace AsbCloudInfrastructure.Services this.wellService = wellService; this.configuration = configuration; this.emailService = emailService; + this.fileCategoryService = fileCategoryService; } - public async Task InsertRangeAsync(List dtos, CancellationToken token) + public override async Task InsertRangeAsync(IEnumerable dtos, CancellationToken token) { var data = await base.InsertRangeAsync(dtos, token); if (data > 0) { - // Текст сообщения - var message = "От Вас ожидается загрузка на портал документа «{0}»"; - await GenerateMessage(dtos, message, token); + var message = "от Вас ожидается загрузка на портал документа «{0}»"; + await GenerateMessageAsync(dtos, message, token); } return data; } - public async Task DeleteAsync(int dtoId, CancellationToken token) + public override async Task DeleteAsync(int dtoId, CancellationToken token) { - // Получение данные удаляемой записи - var dtos = await context.WellFinalDocuments.Where(x => x.Id == dtoId) - .Select(x => new WellFinalDocumentsDBDto - { - IdCategory = x.IdCategory, - IdWell = x.IdWell, - IdUser = x.IdUser, - IdFile = x.IdFile - }) - .ToListAsync(token) - .ConfigureAwait(false); + var entity = await context.WellFinalDocuments + .AsNoTracking() + .FirstOrDefaultAsync(x => x.Id == dtoId); + var dto = Convert(entity); var data = await base.DeleteAsync(dtoId, token); if (data > 0) { - // Текст сообщения var message = "Вас удалили из ответственных за загрузку документа «{0}»"; - await GenerateMessage(dtos, message, token); + await GenerateMessageAsync(new List { dto }, message, token); } return data; } - public async Task> GetByWellId(int idWell, CancellationToken token) + public async Task> GetByWellId(int idWell, CancellationToken token) { var result = new List(); - // Выбиираем все дела, по id скважины + // Выбираем все дела, по id скважины var wells = await context.WellFinalDocuments.Where(x => x.IdWell == idWell) .ToListAsync(token) .ConfigureAwait(false); @@ -132,8 +128,8 @@ namespace AsbCloudInfrastructure.Services result.Add(new WellFinalDocumentsDto { IdWell = idWell, NameCategory = item.NameCategory, - ListResponsible = allUsers.Where(x => userIds.Contains(x.Id)), - CountFiles = fileIds.Count(x => x.HasValue), + Publishers = allUsers.Where(x => userIds.Contains(x.Id)), + FilesCount = fileIds.Count(x => x.HasValue), File = actualFile }); }); @@ -142,7 +138,7 @@ namespace AsbCloudInfrastructure.Services return result; } - public async Task> GetListResponsiblesAsync(int idWell, CancellationToken token) + public async Task> GetPublishersAsync(int idWell, CancellationToken token) { // Получаем отношение скважин и компаний по идентификатору скважины var companyIds = await context.RelationCompaniesWells @@ -150,7 +146,6 @@ namespace AsbCloudInfrastructure.Services .ToListAsync(token) .ConfigureAwait(false); - // Получаем пользователей var allUsers = await userService.GetAllAsync(token) .ConfigureAwait(false); @@ -163,42 +158,37 @@ namespace AsbCloudInfrastructure.Services .ToList(); } - public async Task SaveCategoryFile(int idDto, Stream fileStream, string fileName, CancellationToken token) + public async Task SaveCategoryFile(int idDto, int idUser, Stream fileStream, string fileName, CancellationToken token) { - // Получаем запись - var dtos = await context.WellFinalDocuments.Where(x => x.Id == idDto) - .Select(x => new WellFinalDocumentsDBDto - { - Id = x.Id, - IdCategory = x.IdCategory, - IdWell = x.IdWell, - IdUser = x.IdUser, - IdFile = x.IdFile - }) - .ToListAsync(token) - .ConfigureAwait(false); - var dto = dtos.FirstOrDefault(); + var entity = await context.WellFinalDocuments + .AsNoTracking() + .FirstOrDefaultAsync(x => x.Id == idDto); + + if (entity.IdUser != idUser) + throw new ArgumentInvalidException("Пользователь не является ответственным за загрузку файла для данной категории."); + + var dto = Convert(entity); - // Сохраняем файл и добавляем id файла в запись var file = await fileService.SaveAsync(dto.IdWell, dto.IdUser, dto.IdCategory, fileName, fileStream, token).ConfigureAwait(false); - if (file != null) - dto.IdFile = file.Id; - var data = await base.UpdateAsync(dto, token); - return data; + if (file is not null) + { + dto.IdFile = file.Id; + return await base.UpdateAsync(dto, token); + } + else return ResultSaveCategoryFile; } - public async Task GetHistoryFileByIdCategory(int idWell, int idCategory, CancellationToken token) + public async Task GetFilesHistoryByIdCategory(int idWell, int idCategory, CancellationToken token) { - // Выбиираем все id файлов, по id скважины и id категории + // Выбираем все id файлов, по id скважины и id категории var wellsIds = await context.WellFinalDocuments .Where(x => idWell == x.IdWell && x.IdCategory == idCategory && x.IdFile != null) .Select(x => (int)x.IdFile) .ToListAsync(token) .ConfigureAwait(false); - // Находим фалы var files = await fileService.GetInfoByIdsAsync(wellsIds, token).ConfigureAwait(false); return new WellFinalDocumentsHistoryDto { @@ -208,35 +198,23 @@ namespace AsbCloudInfrastructure.Services }; } - private async Task GenerateMessage(List dtos, string message, CancellationToken token) + private async Task GenerateMessageAsync(IEnumerable dtos, string message, CancellationToken token) { - // Получам пользователей - var userIds = dtos.Select(x => x.IdUser); - var allUsers = await userService.GetAllAsync(token) - .ConfigureAwait(false); - var users = allUsers.Where(x => userIds.Contains(x.Id)); - - // Получаем категории файлов - var categoryIds = dtos.Select(x => x.IdCategory); - var category = await context.FileCategories - .Where(x => categoryIds.Contains(x.Id)) - .ToListAsync(token) - .ConfigureAwait(false); - foreach (var item in dtos) { - var currentUser = users.FirstOrDefault(x => x.Id == item.IdUser); - var categoryName = category.FirstOrDefault(x => x.Id == item.IdCategory)?.Name; - await SendMessage(item.IdWell, currentUser, categoryName, message, token); + var user = await userService.GetOrDefaultAsync(item.IdUser, token); + var category = await fileCategoryService.GetOrDefaultAsync(item.IdCategory, token); + var well = await wellService.GetOrDefaultAsync(item.IdWell, token); + + SendMessage(well, user, category.Name, message, token); } } - private async Task SendMessage(int idWell, UserDto user, string documentCategory, string message, CancellationToken token) + private void SendMessage(WellDto well, UserDto user, string documentCategory, string message, CancellationToken token) { - var well = await wellService.GetOrDefaultAsync(idWell, token); - var factory = new MailBodyFactory(configuration); - var subject = MailBodyFactory.MakeSubject(well, string.Format(message, documentCategory)); - var body = factory.MakeMailBodyForNewPublisher(well, user.Name, documentCategory); + var factory = new WellFinalDocumentMailBodyFactory(configuration); + var subject = factory.MakeSubject(well, documentCategory); + var body = factory.MakeMailBodyForWellFinalDocument(well, user.Name ?? user.Surname, string.Format(message, documentCategory)); emailService.EnqueueSend(user.Email, subject, body); } diff --git a/AsbCloudWebApi.Tests/ServicesTests/WellFinalDocumentsServiceTest.cs b/AsbCloudWebApi.Tests/ServicesTests/WellFinalDocumentsServiceTest.cs index af0c38f7..df04ab73 100644 --- a/AsbCloudWebApi.Tests/ServicesTests/WellFinalDocumentsServiceTest.cs +++ b/AsbCloudWebApi.Tests/ServicesTests/WellFinalDocumentsServiceTest.cs @@ -9,6 +9,7 @@ using System.Threading.Tasks; using Xunit; using System.IO; using System.Collections.Generic; +using System.Linq; namespace AsbCloudWebApi.Tests.ServicesTests { @@ -21,15 +22,16 @@ namespace AsbCloudWebApi.Tests.ServicesTests private readonly Mock wellServiceMock; private readonly Mock configurationMock; private readonly Mock emailServiceMock; + private readonly Mock fileCategoryService; - private readonly IEnumerable users = new List { - new UserExtendedDto { + private readonly IEnumerable users = new List { + new UserDto { Id = 1, IdCompany = 1, Name = "test", Email = "test@test.com" }, - new UserExtendedDto { + new UserDto { Id = 3, IdCompany = 1, Name = "test1", @@ -44,11 +46,12 @@ namespace AsbCloudWebApi.Tests.ServicesTests fileServiceMock = new Mock(); userServiceMock = new Mock(); - userServiceMock.Setup(x => x.GetAllAsync(CancellationToken.None)).Returns(Task.Run(() => users)); + userServiceMock.Setup(x => x.GetAllAsync(CancellationToken.None)).Returns(Task.Run(() => users.Select(x => (UserExtendedDto)x))); wellServiceMock = new Mock(); configurationMock = new Mock(); emailServiceMock = new Mock(); + fileCategoryService = new Mock(); service = new WellFinalDocumentsService( context: context, @@ -56,7 +59,8 @@ namespace AsbCloudWebApi.Tests.ServicesTests userService: userServiceMock.Object, wellService: wellServiceMock.Object, configuration: configurationMock.Object, - emailService: emailServiceMock.Object); + emailService: emailServiceMock.Object, + fileCategoryService: fileCategoryService.Object); } ~WellFinalDocumentsServiceTest() @@ -73,14 +77,14 @@ namespace AsbCloudWebApi.Tests.ServicesTests [Fact] public async Task GetListResponsibles_return_cnt_users() { - var data = await service.GetListResponsiblesAsync(90, CancellationToken.None); + var data = await service.GetPublishersAsync(90, CancellationToken.None); Assert.NotNull(data); } [Fact] public async Task GetHistoryFileByIdCategory_return_data_hitory() { - var data = await service.GetHistoryFileByIdCategory(90, 10018, CancellationToken.None); + var data = await service.GetFilesHistoryByIdCategory(90, 10018, CancellationToken.None); Assert.NotNull(data); } diff --git a/AsbCloudWebApi/Controllers/WellFinalDocumentsController.cs b/AsbCloudWebApi/Controllers/WellFinalDocumentsController.cs index ec7ab307..9f716f40 100644 --- a/AsbCloudWebApi/Controllers/WellFinalDocumentsController.cs +++ b/AsbCloudWebApi/Controllers/WellFinalDocumentsController.cs @@ -12,7 +12,7 @@ namespace AsbCloudWebApi.Controllers /// /// Дело скважины /// - [Route("api/wellFinalDocuments")] + [Route("api/[controller]")] [ApiController] [Authorize] public class WellFinalDocumentsController : ControllerBase @@ -31,6 +31,7 @@ namespace AsbCloudWebApi.Controllers /// [HttpGet] [Permission] + [ProducesResponseType(typeof(IEnumerable), (int)System.Net.HttpStatusCode.OK)] public async Task GetAsync(int idWell, CancellationToken token = default) { var data = await this.wellFinalDocumentsService.GetByWellId(idWell, token); @@ -45,10 +46,11 @@ namespace AsbCloudWebApi.Controllers /// [HttpGet] [Permission] - [Route("getResponsibles")] - public async Task GetResponsiblesAsync(int idWell, CancellationToken token = default) + [Route("publishers")] + [ProducesResponseType(typeof(IEnumerable), (int)System.Net.HttpStatusCode.OK)] + public async Task GetPublishersAsync(int idWell, CancellationToken token = default) { - var data = await this.wellFinalDocumentsService.GetListResponsiblesAsync(idWell, token); + var data = await this.wellFinalDocumentsService.GetPublishersAsync(idWell, token); return Ok(data); } @@ -60,7 +62,8 @@ namespace AsbCloudWebApi.Controllers /// [HttpPut] [Permission] - public async Task InsertRangeAsync(List dtos, CancellationToken token = default) + [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)] + public async Task InsertRangeAsync(IEnumerable dtos, CancellationToken token = default) { var data = await this.wellFinalDocumentsService.InsertRangeAsync(dtos, token); return Ok(data); @@ -74,6 +77,7 @@ namespace AsbCloudWebApi.Controllers /// [HttpDelete] [Permission] + [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)] public async Task DeleteAsync(int iDdto, CancellationToken token = default) { var data = await this.wellFinalDocumentsService.DeleteAsync(iDdto, token); @@ -89,12 +93,13 @@ namespace AsbCloudWebApi.Controllers /// [HttpGet] [Permission] - [Route("getHistoryFileByIdCategory")] - public async Task GetHistoryFileByIdCategory(int idWell, + [Route("filesHistoryByIdCategory")] + [ProducesResponseType(typeof(WellFinalDocumentsHistoryDto), (int)System.Net.HttpStatusCode.OK)] + public async Task GetFilesHistoryByIdCategory(int idWell, int idCategory, CancellationToken token = default) { - var data = await this.wellFinalDocumentsService.GetHistoryFileByIdCategory(idWell, idCategory, token); + var data = await this.wellFinalDocumentsService.GetFilesHistoryByIdCategory(idWell, idCategory, token); return Ok(data); } @@ -102,17 +107,18 @@ namespace AsbCloudWebApi.Controllers /// Сохранение файла ///
/// + /// /// /// /// [HttpPost] [Permission] [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)] - public async Task SaveFilesAsync(int idDto, + public async Task SaveCategoryFile(int idDto, int idUser, IFormFile file, CancellationToken token = default) { var fileStream = file.OpenReadStream(); - var data = await this.wellFinalDocumentsService.SaveCategoryFile(idDto, fileStream, file.FileName, token); + var data = await this.wellFinalDocumentsService.SaveCategoryFile(idDto, idUser, fileStream, file.FileName, token); return Ok(data); } }