forked from ddrilling/AsbCloudServer
Рефакторинг
1. Выпилил лишнюю логику 2. Прокинул IConfiguration в HelpPageService 3. Поправил миграции 4. Поправил тесты
This commit is contained in:
parent
9d2124673c
commit
a0720e9270
@ -2,6 +2,9 @@
|
|||||||
|
|
||||||
namespace AsbCloudApp.Data;
|
namespace AsbCloudApp.Data;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Справка по страницам
|
||||||
|
/// </summary>
|
||||||
public class HelpPageDto : IId
|
public class HelpPageDto : IId
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
@ -1,13 +1,11 @@
|
|||||||
using System;
|
using System;
|
||||||
using AsbCloudApp.Exceptions.Interfaces;
|
|
||||||
|
|
||||||
namespace AsbCloudApp.Exceptions
|
namespace AsbCloudApp.Exceptions
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Argument validation fail Exception
|
/// Argument validation fail Exception
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class ArgumentInvalidException : Exception,
|
public class ArgumentInvalidException : Exception
|
||||||
IHasValidation
|
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// название аргумента
|
/// название аргумента
|
||||||
|
@ -1,47 +0,0 @@
|
|||||||
using System;
|
|
||||||
using AsbCloudApp.Exceptions.Interfaces;
|
|
||||||
|
|
||||||
namespace AsbCloudApp.Exceptions;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Исключение для нескольких невалидных агрументов
|
|
||||||
/// </summary>
|
|
||||||
public class ArgumentsInvalidException : Exception,
|
|
||||||
IHasValidation
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// Имена параметров
|
|
||||||
/// </summary>
|
|
||||||
public string[] ParamNames { get; } = Array.Empty<string>();
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Контсруктор исключения
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="message"></param>
|
|
||||||
/// <param name="paramNames"></param>
|
|
||||||
public ArgumentsInvalidException(string message,
|
|
||||||
string[] paramNames)
|
|
||||||
{
|
|
||||||
ParamNames = paramNames;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// преобразование в объект валидации
|
|
||||||
/// </summary>
|
|
||||||
/// <returns></returns>
|
|
||||||
public object ToValidationErrorObject()
|
|
||||||
=> MakeValidationError(ParamNames, Message);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// фабрика объекта валидации
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="paramName"></param>
|
|
||||||
/// <param name="errors"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
public static object MakeValidationError(string[] paramNames, params string[] errors)
|
|
||||||
=> new
|
|
||||||
{
|
|
||||||
names = paramNames,
|
|
||||||
errors,
|
|
||||||
};
|
|
||||||
}
|
|
@ -1,13 +0,0 @@
|
|||||||
namespace AsbCloudApp.Exceptions.Interfaces;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Интерфейс конвертации исключений
|
|
||||||
/// </summary>
|
|
||||||
public interface IHasValidation
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// Интерфейс конвертации исключений
|
|
||||||
/// </summary>
|
|
||||||
/// <returns></returns>
|
|
||||||
object ToValidationErrorObject();
|
|
||||||
}
|
|
@ -20,15 +20,4 @@ public interface IHelpPageRepository : ICrudRepository<HelpPageDto>
|
|||||||
Task<HelpPageDto?> GetOrDefaultByUrlPageAndIdCategoryAsync(string urlPage,
|
Task<HelpPageDto?> GetOrDefaultByUrlPageAndIdCategoryAsync(string urlPage,
|
||||||
int idCategory,
|
int idCategory,
|
||||||
CancellationToken cancellationToken);
|
CancellationToken cancellationToken);
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Проверка на существование справки для определённой страницы в категории
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="urlPage"></param>
|
|
||||||
/// <param name="idCategory"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
Task<bool> IsCheckHelpPageWithUrlPageAndIdCategoryAsync(string urlPage,
|
|
||||||
int idCategory,
|
|
||||||
CancellationToken cancellationToken);
|
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
using AsbCloudApp.Data;
|
using System.IO;
|
||||||
using System.IO;
|
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
@ -11,7 +10,7 @@ namespace AsbCloudApp.Services;
|
|||||||
public interface IHelpPageService
|
public interface IHelpPageService
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Создание справки
|
/// Метод обновления или обновления файла справки
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="urlPage"></param>
|
/// <param name="urlPage"></param>
|
||||||
/// <param name="idCategory"></param>
|
/// <param name="idCategory"></param>
|
||||||
@ -19,52 +18,20 @@ public interface IHelpPageService
|
|||||||
/// <param name="fileStream"></param>
|
/// <param name="fileStream"></param>
|
||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
Task<int> CreateAsync(string urlPage,
|
Task<int> AddOrUpdateAsync(string urlPage,
|
||||||
int idCategory,
|
|
||||||
string fileName,
|
|
||||||
Stream fileStream,
|
|
||||||
CancellationToken cancellationToken);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Редактирование справки
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="idCategory"></param>
|
|
||||||
/// <param name="helpPage"></param>
|
|
||||||
/// <param name="fileName"></param>
|
|
||||||
/// <param name="fileStream"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
Task UpdateAsync(HelpPageDto helpPage,
|
|
||||||
int idCategory,
|
int idCategory,
|
||||||
string fileName,
|
string fileName,
|
||||||
Stream fileStream,
|
Stream fileStream,
|
||||||
CancellationToken cancellationToken);
|
CancellationToken cancellationToken);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Получение справки по url страницы и id категории
|
/// Метод получения файла справки
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="urlPage"></param>
|
/// <param name="urlPage"></param>
|
||||||
/// <param name="idCategory"></param>
|
/// <param name="idCategory"></param>
|
||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
Task<HelpPageDto?> GetOrDefaultByUrlPageAndIdCategoryAsync(string urlPage,
|
Task<(Stream stream, string fileName)> GetFileStreamAsync(string urlPage,
|
||||||
int idCategory,
|
int idCategory,
|
||||||
CancellationToken cancellationToken);
|
CancellationToken cancellationToken);
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Получение справки по Id
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="id"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
Task<HelpPageDto?> GetOrDefaultByIdAsync(int id,
|
|
||||||
CancellationToken cancellationToken);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Получение файла справки по Id
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="helpPage"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
Stream GetFileStream(HelpPageDto helpPage);
|
|
||||||
}
|
}
|
@ -2054,7 +2054,7 @@ namespace AsbCloudDb.Migrations
|
|||||||
{
|
{
|
||||||
Id = 519,
|
Id = 519,
|
||||||
Description = "Разрешить создание справок по страницам",
|
Description = "Разрешить создание справок по страницам",
|
||||||
Name = "HelpPage.create"
|
Name = "HelpPage.edit"
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -11,7 +11,7 @@ namespace AsbCloudDb.Migrations
|
|||||||
migrationBuilder.InsertData(
|
migrationBuilder.InsertData(
|
||||||
table: "t_permission",
|
table: "t_permission",
|
||||||
columns: new[] { "id", "description", "name" },
|
columns: new[] { "id", "description", "name" },
|
||||||
values: new object[] { 519, "Разрешить создание справок по страницам", "HelpPage.create" });
|
values: new object[] { 519, "Разрешить создание справок по страницам", "HelpPage.edit" });
|
||||||
|
|
||||||
migrationBuilder.InsertData(
|
migrationBuilder.InsertData(
|
||||||
table: "t_relation_user_role_permission",
|
table: "t_relation_user_role_permission",
|
||||||
|
@ -2052,7 +2052,7 @@ namespace AsbCloudDb.Migrations
|
|||||||
{
|
{
|
||||||
Id = 519,
|
Id = 519,
|
||||||
Description = "Разрешить создание справок по страницам",
|
Description = "Разрешить создание справок по страницам",
|
||||||
Name = "HelpPage.create"
|
Name = "HelpPage.edit"
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -150,7 +150,7 @@
|
|||||||
new (){ Id = 517, Name="FaqStatistics.edit", Description="Разрешение редактировать вопрос"},
|
new (){ Id = 517, Name="FaqStatistics.edit", Description="Разрешение редактировать вопрос"},
|
||||||
new (){ Id = 518, Name="FaqStatistics.delete", Description="Разрешение удалять вопрос"},
|
new (){ Id = 518, Name="FaqStatistics.delete", Description="Разрешение удалять вопрос"},
|
||||||
|
|
||||||
new() { Id = 519, Name = "HelpPage.create", Description = "Разрешить создание справок по страницам" }
|
new() { Id = 519, Name = "HelpPage.edit", Description = "Разрешить создание справок по страницам" }
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -136,12 +136,7 @@ namespace AsbCloudInfrastructure
|
|||||||
services.AddTransient<ILimitingParameterService, LimitingParameterService>();
|
services.AddTransient<ILimitingParameterService, LimitingParameterService>();
|
||||||
services.AddTransient<IProcessMapReportMakerService, ProcessMapReportMakerService>();
|
services.AddTransient<IProcessMapReportMakerService, ProcessMapReportMakerService>();
|
||||||
services.AddTransient<IProcessMapReportService, ProcessMapReportService>();
|
services.AddTransient<IProcessMapReportService, ProcessMapReportService>();
|
||||||
services.AddTransient<IHelpPageService, HelpPageService>(serviceProvider =>
|
services.AddTransient<IHelpPageService, HelpPageService>();
|
||||||
new HelpPageService(
|
|
||||||
serviceProvider.GetRequiredService<IHelpPageRepository>(),
|
|
||||||
serviceProvider.GetRequiredService<IFileStorageRepository>(),
|
|
||||||
configuration.GetSection("HelpPageOptions:DirectoryNameHelpPageFiles")
|
|
||||||
.Get<string>()));
|
|
||||||
|
|
||||||
services.AddTransient<TrajectoryService>();
|
services.AddTransient<TrajectoryService>();
|
||||||
|
|
||||||
|
@ -31,13 +31,4 @@ public class HelpPageRepository : CrudRepositoryBase<HelpPageDto, HelpPage>,
|
|||||||
|
|
||||||
return helpPage.Adapt<HelpPageDto>();
|
return helpPage.Adapt<HelpPageDto>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task<bool> IsCheckHelpPageWithUrlPageAndIdCategoryAsync(string urlPage, int idCategory,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
return dbSet.AnyAsync(x =>
|
|
||||||
x.UrlPage == urlPage &&
|
|
||||||
x.IdCategory == idCategory,
|
|
||||||
cancellationToken);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -1,16 +1,16 @@
|
|||||||
using System;
|
using AsbCloudApp.Data;
|
||||||
using AsbCloudApp.Data;
|
|
||||||
using AsbCloudApp.Repositories;
|
using AsbCloudApp.Repositories;
|
||||||
using AsbCloudApp.Services;
|
using AsbCloudApp.Services;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
using AsbCloudApp.Exceptions;
|
using AsbCloudApp.Exceptions;
|
||||||
|
|
||||||
namespace AsbCloudInfrastructure.Services;
|
namespace AsbCloudInfrastructure.Services;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Реализация сервиса справок страниц
|
/// Реализация сервиса для справок по страницам
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class HelpPageService : IHelpPageService
|
public class HelpPageService : IHelpPageService
|
||||||
{
|
{
|
||||||
@ -23,21 +23,18 @@ public class HelpPageService : IHelpPageService
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="helpPageRepository"></param>
|
/// <param name="helpPageRepository"></param>
|
||||||
/// <param name="fileStorageRepository"></param>
|
/// <param name="fileStorageRepository"></param>
|
||||||
/// <param name="directoryNameHelpPageFiles"></param>
|
/// <param name="configuration"></param>
|
||||||
public HelpPageService(IHelpPageRepository helpPageRepository,
|
public HelpPageService(IHelpPageRepository helpPageRepository,
|
||||||
IFileStorageRepository fileStorageRepository,
|
IFileStorageRepository fileStorageRepository,
|
||||||
string directoryNameHelpPageFiles)
|
IConfiguration configuration)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrWhiteSpace(directoryNameHelpPageFiles))
|
|
||||||
throw new ArgumentException("Value cannot be null or whitespace", nameof(this.directoryNameHelpPageFiles));
|
|
||||||
|
|
||||||
this.helpPageRepository = helpPageRepository;
|
this.helpPageRepository = helpPageRepository;
|
||||||
this.fileStorageRepository = fileStorageRepository;
|
this.fileStorageRepository = fileStorageRepository;
|
||||||
this.directoryNameHelpPageFiles = directoryNameHelpPageFiles;
|
directoryNameHelpPageFiles = configuration.GetValue<string>("DirectoryNameHelpPageFiles");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Создание справки страницы
|
/// Метод обновления или обновления файла справки
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="urlPage"></param>
|
/// <param name="urlPage"></param>
|
||||||
/// <param name="idCategory"></param>
|
/// <param name="idCategory"></param>
|
||||||
@ -45,20 +42,67 @@ public class HelpPageService : IHelpPageService
|
|||||||
/// <param name="fileStream"></param>
|
/// <param name="fileStream"></param>
|
||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public async Task<int> CreateAsync(string urlPage,
|
public async Task<int> AddOrUpdateAsync(string urlPage,
|
||||||
|
int idCategory,
|
||||||
|
string fileName,
|
||||||
|
Stream fileStream,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var helpPage = await helpPageRepository.GetOrDefaultByUrlPageAndIdCategoryAsync(urlPage,
|
||||||
|
idCategory,
|
||||||
|
cancellationToken);
|
||||||
|
|
||||||
|
if(helpPage is not null)
|
||||||
|
{
|
||||||
|
await UpdateFileAsync(helpPage,
|
||||||
|
idCategory,
|
||||||
|
fileName,
|
||||||
|
fileStream,
|
||||||
|
cancellationToken);
|
||||||
|
|
||||||
|
return helpPage.Id;
|
||||||
|
}
|
||||||
|
|
||||||
|
return await SaveFileAsync(urlPage,
|
||||||
|
idCategory,
|
||||||
|
fileName,
|
||||||
|
fileStream,
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Метод получения файла справки
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="urlPage"></param>
|
||||||
|
/// <param name="idCategory"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
/// <exception cref="ArgumentInvalidException"></exception>
|
||||||
|
public async Task<(Stream stream, string fileName)> GetFileStreamAsync(string urlPage,
|
||||||
|
int idCategory,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var helpPage = await helpPageRepository.GetOrDefaultByUrlPageAndIdCategoryAsync(urlPage,
|
||||||
|
idCategory,
|
||||||
|
cancellationToken) ?? throw new ArgumentInvalidException("Справки не существует", nameof(idCategory));
|
||||||
|
|
||||||
|
string filePath = fileStorageRepository.GetFilePath(directoryNameHelpPageFiles,
|
||||||
|
helpPage.IdCategory.ToString(),
|
||||||
|
helpPage.Id,
|
||||||
|
Path.GetExtension(helpPage.Name));
|
||||||
|
|
||||||
|
var fileStream = new FileStream(Path.GetFullPath(filePath), FileMode.Open);
|
||||||
|
|
||||||
|
return (fileStream, helpPage.Name);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<int> SaveFileAsync(string urlPage,
|
||||||
int idCategory,
|
int idCategory,
|
||||||
string fileName,
|
string fileName,
|
||||||
Stream fileStream,
|
Stream fileStream,
|
||||||
CancellationToken cancellationToken)
|
CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
if (await helpPageRepository.IsCheckHelpPageWithUrlPageAndIdCategoryAsync(urlPage,
|
|
||||||
idCategory,
|
|
||||||
cancellationToken))
|
|
||||||
{
|
|
||||||
throw new ArgumentsInvalidException("Справка с такой категории файла для данной страницы уже существует",
|
|
||||||
new[] { nameof(urlPage), nameof(idCategory) });
|
|
||||||
}
|
|
||||||
|
|
||||||
HelpPageDto helpPage = new()
|
HelpPageDto helpPage = new()
|
||||||
{
|
{
|
||||||
UrlPage = urlPage,
|
UrlPage = urlPage,
|
||||||
@ -79,16 +123,7 @@ public class HelpPageService : IHelpPageService
|
|||||||
return idFile;
|
return idFile;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
private async Task UpdateFileAsync(HelpPageDto helpPage,
|
||||||
/// Обновление справки страницы
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="helpPage"></param>
|
|
||||||
/// <param name="idCategory"></param>
|
|
||||||
/// <param name="fileName"></param>
|
|
||||||
/// <param name="fileStream"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
public async Task UpdateAsync(HelpPageDto helpPage,
|
|
||||||
int idCategory,
|
int idCategory,
|
||||||
string fileName,
|
string fileName,
|
||||||
Stream fileStream,
|
Stream fileStream,
|
||||||
@ -115,47 +150,11 @@ public class HelpPageService : IHelpPageService
|
|||||||
cancellationToken);
|
cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Получение справки по url страницы и id категории
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="urlPage"></param>
|
|
||||||
/// <param name="idCategory"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
public Task<HelpPageDto?> GetOrDefaultByUrlPageAndIdCategoryAsync(string urlPage,
|
|
||||||
int idCategory,
|
|
||||||
CancellationToken cancellationToken) =>
|
|
||||||
helpPageRepository.GetOrDefaultByUrlPageAndIdCategoryAsync(urlPage,
|
|
||||||
idCategory,
|
|
||||||
cancellationToken);
|
|
||||||
|
|
||||||
public Task<HelpPageDto?> GetOrDefaultByIdAsync(int id, CancellationToken cancellationToken) =>
|
|
||||||
helpPageRepository.GetOrDefaultAsync(id,
|
|
||||||
cancellationToken);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Получение файлового потока для файла справки
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="helpPage"></param>
|
|
||||||
/// <param name="cancellationToken"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
public Stream GetFileStream(HelpPageDto helpPage)
|
|
||||||
{
|
|
||||||
string filePath = fileStorageRepository.GetFilePath(directoryNameHelpPageFiles,
|
|
||||||
helpPage.IdCategory.ToString(),
|
|
||||||
helpPage.Id,
|
|
||||||
Path.GetExtension(helpPage.Name));;
|
|
||||||
|
|
||||||
var fileStream = new FileStream(Path.GetFullPath(filePath), FileMode.Open);
|
|
||||||
|
|
||||||
return fileStream;
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task SaveFileAsync(int idCategory,
|
private async Task SaveFileAsync(int idCategory,
|
||||||
string fileName,
|
string fileName,
|
||||||
Stream fileStream,
|
Stream fileStream,
|
||||||
int fileId,
|
int fileId,
|
||||||
CancellationToken cancellationToken = default)
|
CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
string filePath = fileStorageRepository.MakeFilePath(directoryNameHelpPageFiles,
|
string filePath = fileStorageRepository.MakeFilePath(directoryNameHelpPageFiles,
|
||||||
idCategory.ToString(),
|
idCategory.ToString(),
|
||||||
|
@ -5,10 +5,10 @@ using System.Linq;
|
|||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using AsbCloudApp.Data;
|
using AsbCloudApp.Data;
|
||||||
using AsbCloudApp.Exceptions;
|
|
||||||
using AsbCloudApp.Repositories;
|
using AsbCloudApp.Repositories;
|
||||||
using AsbCloudApp.Services;
|
using AsbCloudApp.Services;
|
||||||
using AsbCloudInfrastructure.Services;
|
using AsbCloudInfrastructure.Services;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
using Moq;
|
using Moq;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
|
||||||
@ -16,7 +16,9 @@ namespace AsbCloudWebApi.Tests.ServicesTests;
|
|||||||
|
|
||||||
public class HelpPageServiceTest
|
public class HelpPageServiceTest
|
||||||
{
|
{
|
||||||
private const string directoryNameHelpPageFiles = "helpPages";
|
private static Dictionary<string, string> configSettings = new (){
|
||||||
|
{"DirectoryNameHelpPageFiles", "helpPages"}
|
||||||
|
};
|
||||||
|
|
||||||
private static List<HelpPageDto> HelpPages = new()
|
private static List<HelpPageDto> HelpPages = new()
|
||||||
{
|
{
|
||||||
@ -45,7 +47,7 @@ public class HelpPageServiceTest
|
|||||||
UrlPage = "test2"
|
UrlPage = "test2"
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
private readonly Mock<IHelpPageRepository> helpPageRepository = new();
|
private readonly Mock<IHelpPageRepository> helpPageRepository = new();
|
||||||
private readonly Mock<IFileStorageRepository> fileStorageRepository = new();
|
private readonly Mock<IFileStorageRepository> fileStorageRepository = new();
|
||||||
|
|
||||||
@ -53,21 +55,36 @@ public class HelpPageServiceTest
|
|||||||
|
|
||||||
public HelpPageServiceTest()
|
public HelpPageServiceTest()
|
||||||
{
|
{
|
||||||
|
IConfiguration configuration = new ConfigurationBuilder()
|
||||||
|
.AddInMemoryCollection(configSettings)
|
||||||
|
.Build();
|
||||||
|
|
||||||
helpPageService = new HelpPageService(helpPageRepository.Object,
|
helpPageService = new HelpPageService(helpPageRepository.Object,
|
||||||
fileStorageRepository.Object,
|
fileStorageRepository.Object,
|
||||||
directoryNameHelpPageFiles);
|
configuration);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task CreateAsync_ShouldReturn_PositiveId()
|
public async Task AddOrUpdateAsync_ShouldReturn_NewHelpPage()
|
||||||
{
|
{
|
||||||
//arrange
|
//arrange
|
||||||
int idHelpPage = new Random().Next(1, 100);
|
int idHelpPage = new Random().Next(1, 100);
|
||||||
string urlPage = "test";
|
string urlPage = "test";
|
||||||
int idCategory = 20000;
|
int idCategory = 20000;
|
||||||
string fullName = "test.pdf";
|
string fileName = "test.pdf";
|
||||||
MemoryStream fileStream = new MemoryStream(Array.Empty<byte>());
|
MemoryStream fileStream = new MemoryStream(Array.Empty<byte>());
|
||||||
|
|
||||||
|
helpPageRepository.Setup(x => x.GetOrDefaultByUrlPageAndIdCategoryAsync(It.IsAny<string>(),
|
||||||
|
It.IsAny<int>(), It.IsAny<CancellationToken>()))
|
||||||
|
.Returns(() =>
|
||||||
|
{
|
||||||
|
var helpPage = HelpPages.FirstOrDefault(x =>
|
||||||
|
x.UrlPage == urlPage &&
|
||||||
|
x.IdCategory == idCategory);
|
||||||
|
|
||||||
|
return Task.FromResult(helpPage);
|
||||||
|
});
|
||||||
|
|
||||||
helpPageRepository.Setup(x => x.InsertAsync(It.IsAny<HelpPageDto>(),
|
helpPageRepository.Setup(x => x.InsertAsync(It.IsAny<HelpPageDto>(),
|
||||||
It.IsAny<CancellationToken>()))
|
It.IsAny<CancellationToken>()))
|
||||||
.Returns(() => Task.FromResult(idHelpPage));
|
.Returns(() => Task.FromResult(idHelpPage));
|
||||||
@ -77,9 +94,9 @@ public class HelpPageServiceTest
|
|||||||
It.IsAny<CancellationToken>()));
|
It.IsAny<CancellationToken>()));
|
||||||
|
|
||||||
//act
|
//act
|
||||||
int result = await helpPageService.CreateAsync(urlPage,
|
int result = await helpPageService.AddOrUpdateAsync(urlPage,
|
||||||
idCategory,
|
idCategory,
|
||||||
fullName,
|
fileName,
|
||||||
fileStream,
|
fileStream,
|
||||||
CancellationToken.None);
|
CancellationToken.None);
|
||||||
|
|
||||||
@ -87,110 +104,42 @@ public class HelpPageServiceTest
|
|||||||
Assert.True(result > 0);
|
Assert.True(result > 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task CreateAsync_ShouldReturn_ArgumentsInvalidException()
|
|
||||||
{
|
|
||||||
//arrange
|
|
||||||
string urlPage = "test";
|
|
||||||
int idCategory = 20000;
|
|
||||||
string fullName = "test.pdf";
|
|
||||||
MemoryStream fileStream = new MemoryStream(Array.Empty<byte>());
|
|
||||||
bool isExistingHelpPage = true;
|
|
||||||
|
|
||||||
helpPageRepository.Setup(x => x.IsCheckHelpPageWithUrlPageAndIdCategoryAsync(It.IsAny<string>(),
|
|
||||||
It.IsAny<int>(),
|
|
||||||
It.IsAny<CancellationToken>()))
|
|
||||||
.Returns(() => Task.FromResult(isExistingHelpPage));
|
|
||||||
|
|
||||||
//act
|
|
||||||
Task Result () => helpPageService.CreateAsync(urlPage,
|
|
||||||
idCategory,
|
|
||||||
fullName,
|
|
||||||
fileStream,
|
|
||||||
CancellationToken.None);
|
|
||||||
|
|
||||||
//assert
|
|
||||||
await Assert.ThrowsAsync<ArgumentsInvalidException>(Result);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task UpdateAsync_ShouldReturn_UpdatedHelpPage()
|
public async Task UpdateAsync_ShouldReturn_UpdatedHelpPage()
|
||||||
{
|
{
|
||||||
//arrange
|
//arrange
|
||||||
HelpPageDto helpPage = new()
|
int idHelpPage = new Random().Next(1, 100);
|
||||||
{
|
string urlPage = "test";
|
||||||
Id = 123,
|
int newIdCategory = 20000;
|
||||||
IdCategory = 134,
|
string newFileName = "test.pdf";
|
||||||
UrlPage = "test",
|
|
||||||
Name = "Справка.pdf",
|
|
||||||
Size = 54000
|
|
||||||
};
|
|
||||||
|
|
||||||
int newIdCategory = 451;
|
|
||||||
string newFileName = "Новая справка.pdf";
|
|
||||||
MemoryStream newFileStream = new MemoryStream(Array.Empty<byte>());
|
MemoryStream newFileStream = new MemoryStream(Array.Empty<byte>());
|
||||||
|
HelpPageDto existingHelpPage = HelpPages.First(x =>
|
||||||
|
x.UrlPage == urlPage &&
|
||||||
|
x.IdCategory == newIdCategory);
|
||||||
|
|
||||||
|
helpPageRepository.Setup(x => x.GetOrDefaultByUrlPageAndIdCategoryAsync(It.IsAny<string>(),
|
||||||
|
It.IsAny<int>(), It.IsAny<CancellationToken>()))
|
||||||
|
.Returns(() => Task.FromResult(existingHelpPage)!);
|
||||||
|
|
||||||
|
helpPageRepository.Setup(x => x.InsertAsync(It.IsAny<HelpPageDto>(),
|
||||||
|
It.IsAny<CancellationToken>()))
|
||||||
|
.Returns(() => Task.FromResult(idHelpPage));
|
||||||
|
|
||||||
|
fileStorageRepository.Setup(x => x.SaveFileAsync(It.IsAny<string>(),
|
||||||
|
It.IsAny<Stream>(),
|
||||||
|
It.IsAny<CancellationToken>()));
|
||||||
|
|
||||||
//act
|
//act
|
||||||
await helpPageService.UpdateAsync(helpPage,
|
await helpPageService.AddOrUpdateAsync(urlPage,
|
||||||
newIdCategory,
|
newIdCategory,
|
||||||
newFileName,
|
newFileName,
|
||||||
newFileStream,
|
newFileStream,
|
||||||
CancellationToken.None);
|
CancellationToken.None);
|
||||||
|
|
||||||
//assert
|
|
||||||
Assert.Equal(newFileName, helpPage.Name);
|
|
||||||
Assert.Equal(newIdCategory, helpPage.IdCategory);
|
|
||||||
Assert.Equal(newFileStream.Length, helpPage.Size);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData(20000, "test")]
|
|
||||||
[InlineData(20000, "test1")]
|
|
||||||
public async Task GetOrDefaultByUrlPageAndIdCategoryAsync_ShouldReturn_HelpPageDto(int idCategory,
|
|
||||||
string urlPage)
|
|
||||||
{
|
|
||||||
//arrange
|
|
||||||
helpPageRepository.Setup(x => x.GetOrDefaultByUrlPageAndIdCategoryAsync(It.IsAny<string>(),
|
|
||||||
It.IsAny<int>(), It.IsAny<CancellationToken>()))
|
|
||||||
.Returns(() =>
|
|
||||||
{
|
|
||||||
var helpPage = HelpPages.FirstOrDefault(x =>
|
|
||||||
x.UrlPage == urlPage &&
|
|
||||||
x.IdCategory == idCategory);
|
|
||||||
|
|
||||||
return Task.FromResult(helpPage);
|
|
||||||
});
|
|
||||||
|
|
||||||
//act
|
|
||||||
var result = await helpPageService.GetOrDefaultByUrlPageAndIdCategoryAsync(urlPage,
|
|
||||||
idCategory,
|
|
||||||
CancellationToken.None);
|
|
||||||
|
|
||||||
//assert
|
//assert
|
||||||
Assert.NotNull(result);
|
Assert.Equal(newFileName, existingHelpPage.Name);
|
||||||
}
|
Assert.Equal(newIdCategory, existingHelpPage.IdCategory);
|
||||||
|
Assert.Equal(newFileStream.Length, existingHelpPage.Size);
|
||||||
[Theory]
|
|
||||||
[InlineData(123)]
|
|
||||||
[InlineData(178)]
|
|
||||||
public async Task GetOrDefaultByIdAsync_ShouldReturn_HelpPageDto(int id)
|
|
||||||
{
|
|
||||||
//arrange
|
|
||||||
helpPageRepository.Setup(x => x.GetOrDefaultAsync(It.IsAny<int>(),
|
|
||||||
It.IsAny<CancellationToken>()))
|
|
||||||
.Returns(() =>
|
|
||||||
{
|
|
||||||
var helpPage = HelpPages.FirstOrDefault(x =>
|
|
||||||
x.Id == id);
|
|
||||||
|
|
||||||
return Task.FromResult(helpPage);
|
|
||||||
});
|
|
||||||
|
|
||||||
//act
|
|
||||||
var result = await helpPageService.GetOrDefaultByIdAsync(id,
|
|
||||||
CancellationToken.None);
|
|
||||||
|
|
||||||
//assert
|
|
||||||
Assert.NotNull(result);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -5,9 +5,9 @@ using System.ComponentModel.DataAnnotations;
|
|||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using AsbCloudApp.Data;
|
|
||||||
using AsbCloudApp.Repositories;
|
using AsbCloudApp.Repositories;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using System.Net;
|
||||||
|
|
||||||
namespace AsbCloudWebApi.Controllers;
|
namespace AsbCloudWebApi.Controllers;
|
||||||
|
|
||||||
@ -30,50 +30,37 @@ public class HelpPageController : ControllerBase
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Создание файла справки
|
/// Загрузка файла справки
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="urlPage">Url страницы для которой предназначена эта справка</param>
|
/// <param name="urlPage">Url страницы</param>
|
||||||
/// <param name="idCategory">Id катагории файла</param>
|
/// <param name="idCategory">Id категории файла</param>
|
||||||
/// <param name="file">Загружаемый файл</param>
|
/// <param name="file">Файл справки</param>
|
||||||
/// <returns>Id созданной справки</returns>
|
/// <param name="cancellationToken">Токен для отмены задачи</param>
|
||||||
|
/// <returns></returns>
|
||||||
[HttpPost]
|
[HttpPost]
|
||||||
[Permission]
|
[Permission]
|
||||||
[Route("saveFile")]
|
[Route("upload")]
|
||||||
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
|
[ProducesResponseType(typeof(int), (int)HttpStatusCode.OK)]
|
||||||
public async Task<IActionResult> CreateAsync(string urlPage,
|
public async Task<IActionResult> UploadAsync(string urlPage,
|
||||||
int idCategory,
|
int idCategory,
|
||||||
[Required] IFormFile file)
|
[Required] IFormFile file,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
int? idUser = User.GetUserId();
|
int? idUser = User.GetUserId();
|
||||||
|
|
||||||
if(!idUser.HasValue)
|
if(!idUser.HasValue)
|
||||||
return Forbid();
|
return Forbid();
|
||||||
|
|
||||||
if (!userRepository.HasPermission(idUser.Value, $"HelpPage.create"))
|
if (!userRepository.HasPermission(idUser.Value, $"HelpPage.edit"))
|
||||||
return Forbid();
|
return Forbid();
|
||||||
|
|
||||||
var helpPage = await helpPageService.GetOrDefaultByUrlPageAndIdCategoryAsync(urlPage,
|
|
||||||
idCategory,
|
|
||||||
CancellationToken.None);
|
|
||||||
|
|
||||||
using var fileStream = file.OpenReadStream();
|
using var fileStream = file.OpenReadStream();
|
||||||
|
|
||||||
if (helpPage is not null)
|
int helpPageId = await helpPageService.AddOrUpdateAsync(urlPage,
|
||||||
{
|
|
||||||
await helpPageService.UpdateAsync(helpPage,
|
|
||||||
idCategory,
|
|
||||||
file.FileName,
|
|
||||||
fileStream,
|
|
||||||
CancellationToken.None);
|
|
||||||
|
|
||||||
return Ok(helpPage.Id);
|
|
||||||
}
|
|
||||||
|
|
||||||
int helpPageId = await helpPageService.CreateAsync(urlPage,
|
|
||||||
idCategory,
|
idCategory,
|
||||||
file.FileName,
|
file.FileName,
|
||||||
fileStream,
|
fileStream,
|
||||||
CancellationToken.None);
|
cancellationToken);
|
||||||
|
|
||||||
return Ok(helpPageId);
|
return Ok(helpPageId);
|
||||||
}
|
}
|
||||||
@ -81,45 +68,29 @@ public class HelpPageController : ControllerBase
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Получение файла справки
|
/// Получение файла справки
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="id">Id справки</param>
|
/// <param name="urlPage">Url страницы</param>
|
||||||
/// <returns>Файл</returns>
|
/// <param name="idCategory">Id категории файла</param>
|
||||||
|
/// <param name="cancellationToken">Токен для отмены задачи</param>
|
||||||
|
/// <returns></returns>
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
[Route("getById/{id}")]
|
[Route("get/{urlPage}/{idCategory}")]
|
||||||
[ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK)]
|
[ProducesResponseType(typeof(PhysicalFileResult), (int)HttpStatusCode.OK)]
|
||||||
public async Task<IActionResult> GetFileAsync(int id)
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||||
|
public async Task<IActionResult> GetFileAsync(string urlPage,
|
||||||
|
int idCategory,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var helpPage = await helpPageService.GetOrDefaultByIdAsync(id,
|
var file = await helpPageService.GetFileStreamAsync(urlPage,
|
||||||
CancellationToken.None);
|
idCategory,
|
||||||
|
cancellationToken);
|
||||||
|
|
||||||
if (helpPage is null)
|
using var fileStream = file.stream;
|
||||||
return NotFound();
|
|
||||||
|
|
||||||
using var fileStream = helpPageService.GetFileStream(helpPage);
|
|
||||||
|
|
||||||
var memoryStream = new MemoryStream();
|
var memoryStream = new MemoryStream();
|
||||||
await fileStream.CopyToAsync(memoryStream,
|
await fileStream.CopyToAsync(memoryStream,
|
||||||
CancellationToken.None);
|
cancellationToken);
|
||||||
memoryStream.Position = 0;
|
memoryStream.Position = 0;
|
||||||
|
|
||||||
return File(memoryStream, "application/octet-stream", helpPage.Name);
|
return File(memoryStream, "application/octet-stream", file.fileName);
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Получение информации о справке
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="urlPage">Url страницы</param>
|
|
||||||
/// <param name="idCategory">Id категории</param>
|
|
||||||
/// <returns>Dto справки</returns>
|
|
||||||
[HttpGet]
|
|
||||||
[Route("getByUrlPage/{urlPage}/{idCategory}")]
|
|
||||||
[ProducesResponseType(typeof(HelpPageDto), (int)System.Net.HttpStatusCode.OK)]
|
|
||||||
public async Task<IActionResult> GetByUrlPageAsync(string urlPage,
|
|
||||||
int idCategory)
|
|
||||||
{
|
|
||||||
var helpPage = await helpPageService.GetOrDefaultByUrlPageAndIdCategoryAsync(urlPage,
|
|
||||||
idCategory,
|
|
||||||
CancellationToken.None);
|
|
||||||
|
|
||||||
return Ok(helpPage);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -3,7 +3,6 @@ using Microsoft.AspNetCore.Http;
|
|||||||
using System;
|
using System;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using AsbCloudApp.Exceptions.Interfaces;
|
|
||||||
|
|
||||||
namespace AsbCloudWebApi.Middlewares
|
namespace AsbCloudWebApi.Middlewares
|
||||||
{
|
{
|
||||||
@ -31,15 +30,6 @@ namespace AsbCloudWebApi.Middlewares
|
|||||||
var body = MakeJsonBody(ex);
|
var body = MakeJsonBody(ex);
|
||||||
await context.Response.WriteAsync(body);
|
await context.Response.WriteAsync(body);
|
||||||
}
|
}
|
||||||
catch (ArgumentsInvalidException ex)
|
|
||||||
{
|
|
||||||
Console.WriteLine($"ArgumentExceptions in {context.Request.Method}: {ex.Message}");
|
|
||||||
context.Response.Clear();
|
|
||||||
context.Response.StatusCode = 400;
|
|
||||||
context.Response.ContentType = "application/json";
|
|
||||||
var body = MakeJsonBody(ex);
|
|
||||||
await context.Response.WriteAsync(body);
|
|
||||||
}
|
|
||||||
catch (ForbidException ex)
|
catch (ForbidException ex)
|
||||||
{
|
{
|
||||||
Console.WriteLine($"ForbidException in {context.Request.Method}: {ex.Message}");
|
Console.WriteLine($"ForbidException in {context.Request.Method}: {ex.Message}");
|
||||||
@ -59,8 +49,7 @@ namespace AsbCloudWebApi.Middlewares
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string MakeJsonBody<TException>(TException ex)
|
private static string MakeJsonBody(ArgumentInvalidException ex)
|
||||||
where TException: Exception, IHasValidation
|
|
||||||
{
|
{
|
||||||
object error = ex.ToValidationErrorObject();
|
object error = ex.ToValidationErrorObject();
|
||||||
var buffer = System.Text.Json.JsonSerializer.Serialize(error);
|
var buffer = System.Text.Json.JsonSerializer.Serialize(error);
|
||||||
|
@ -26,9 +26,7 @@
|
|||||||
"companyName": "ООО \"Цифровое бурение\"",
|
"companyName": "ООО \"Цифровое бурение\"",
|
||||||
"supportMail": "support@digitaldrilling.ru"
|
"supportMail": "support@digitaldrilling.ru"
|
||||||
},
|
},
|
||||||
"HelpPageOptions": {
|
"DirectoryNameHelpPageFiles": "helpPages",
|
||||||
"DirectoryNameHelpPageFiles": "helpPages"
|
|
||||||
},
|
|
||||||
"Urls": "http://0.0.0.0:5000" //;https://0.0.0.0:5001" //,
|
"Urls": "http://0.0.0.0:5000" //;https://0.0.0.0:5001" //,
|
||||||
// See https man: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel/endpoints?view=aspnetcore-6.0
|
// See https man: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel/endpoints?view=aspnetcore-6.0
|
||||||
//"Kestrel": {
|
//"Kestrel": {
|
||||||
|
Loading…
Reference in New Issue
Block a user