6 Commits

Author SHA1 Message Date
af440f46e0 CustomMapper 2025-04-21 19:57:47 +04:00
77909ba831 locale en 2025-04-10 21:04:43 +04:00
212527d3de check locale 2025-04-10 20:56:45 +04:00
94d09f33b6 strings 2025-04-10 20:39:32 +04:00
d397dcd2cc Dates 2025-04-10 17:47:46 +04:00
f7444f5582 Numbers 2025-04-10 17:05:10 +04:00
102 changed files with 2478 additions and 1108 deletions

View File

@@ -2,22 +2,25 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Resources;
using CatHasPawsContratcs.StoragesContracts;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace CatHasPawsBusinessLogic.Implementations;
internal class BuyerBusinessLogicContract(IBuyerStorageContract buyerStorageContract, ILogger logger) : IBuyerBusinessLogicContract
internal class BuyerBusinessLogicContract(IBuyerStorageContract buyerStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : IBuyerBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IBuyerStorageContract _buyerStorageContract = buyerStorageContract;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<BuyerDataModel> GetAllBuyers()
{
_logger.LogInformation("GetAllBuyers");
return _buyerStorageContract.GetList() ?? throw new NullListException();
return _buyerStorageContract.GetList();
}
public BuyerDataModel GetBuyerByData(string data)
@@ -29,20 +32,20 @@ internal class BuyerBusinessLogicContract(IBuyerStorageContract buyerStorageCont
}
if (data.IsGuid())
{
return _buyerStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return _buyerStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data, _localizer);
}
if (Regex.IsMatch(data, @"^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7,10}$"))
{
return _buyerStorageContract.GetElementByPhoneNumber(data) ?? throw new ElementNotFoundException(data);
return _buyerStorageContract.GetElementByPhoneNumber(data) ?? throw new ElementNotFoundException(data, _localizer);
}
return _buyerStorageContract.GetElementByFIO(data) ?? throw new ElementNotFoundException(data);
return _buyerStorageContract.GetElementByFIO(data) ?? throw new ElementNotFoundException(data, _localizer);
}
public void InsertBuyer(BuyerDataModel buyerDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(buyerDataModel));
ArgumentNullException.ThrowIfNull(buyerDataModel);
buyerDataModel.Validate();
buyerDataModel.Validate(_localizer);
_buyerStorageContract.AddElement(buyerDataModel);
}
@@ -50,7 +53,7 @@ internal class BuyerBusinessLogicContract(IBuyerStorageContract buyerStorageCont
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(buyerDataModel));
ArgumentNullException.ThrowIfNull(buyerDataModel);
buyerDataModel.Validate();
buyerDataModel.Validate(_localizer);
_buyerStorageContract.UpdElement(buyerDataModel);
}
@@ -63,7 +66,7 @@ internal class BuyerBusinessLogicContract(IBuyerStorageContract buyerStorageCont
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
}
_buyerStorageContract.DelElement(id);
}

View File

@@ -2,21 +2,24 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Resources;
using CatHasPawsContratcs.StoragesContracts;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace CatHasPawsBusinessLogic.Implementations;
internal class ManufacturerBusinessLogicContract(IManufacturerStorageContract manufacturerStorageContract, ILogger logger) : IManufacturerBusinessLogicContract
internal class ManufacturerBusinessLogicContract(IManufacturerStorageContract manufacturerStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : IManufacturerBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IManufacturerStorageContract _manufacturerStorageContract = manufacturerStorageContract;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<ManufacturerDataModel> GetAllManufacturers()
{
_logger.LogInformation("GetAllManufacturers");
return _manufacturerStorageContract.GetList() ?? throw new NullListException();
return _manufacturerStorageContract.GetList();
}
public ManufacturerDataModel GetManufacturerByData(string data)
@@ -28,17 +31,17 @@ internal class ManufacturerBusinessLogicContract(IManufacturerStorageContract ma
}
if (data.IsGuid())
{
return _manufacturerStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return _manufacturerStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data, _localizer);
}
return _manufacturerStorageContract.GetElementByName(data) ?? _manufacturerStorageContract.GetElementByOldName(data) ??
throw new ElementNotFoundException(data);
throw new ElementNotFoundException(data, _localizer);
}
public void InsertManufacturer(ManufacturerDataModel manufacturerDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(manufacturerDataModel));
ArgumentNullException.ThrowIfNull(manufacturerDataModel);
manufacturerDataModel.Validate();
manufacturerDataModel.Validate(_localizer);
_manufacturerStorageContract.AddElement(manufacturerDataModel);
}
@@ -46,7 +49,7 @@ internal class ManufacturerBusinessLogicContract(IManufacturerStorageContract ma
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(manufacturerDataModel));
ArgumentNullException.ThrowIfNull(manufacturerDataModel);
manufacturerDataModel.Validate();
manufacturerDataModel.Validate(_localizer);
_manufacturerStorageContract.UpdElement(manufacturerDataModel);
}
@@ -59,7 +62,7 @@ internal class ManufacturerBusinessLogicContract(IManufacturerStorageContract ma
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
}
_manufacturerStorageContract.DelElement(id);
}

View File

@@ -2,21 +2,24 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Resources;
using CatHasPawsContratcs.StoragesContracts;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace CatHasPawsBusinessLogic.Implementations;
internal class PostBusinessLogicContract(IPostStorageContract postStorageContract, ILogger logger) : IPostBusinessLogicContract
internal class PostBusinessLogicContract(IPostStorageContract postStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : IPostBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IPostStorageContract _postStorageContract = postStorageContract;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<PostDataModel> GetAllPosts()
{
_logger.LogInformation("GetAllPosts");
return _postStorageContract.GetList() ?? throw new NullListException();
return _postStorageContract.GetList();
}
public List<PostDataModel> GetAllDataOfPost(string postId)
@@ -28,9 +31,9 @@ internal class PostBusinessLogicContract(IPostStorageContract postStorageContrac
}
if (!postId.IsGuid())
{
throw new ValidationException("The value in the field postId is not a unique identifier.");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "PostId"));
}
return _postStorageContract.GetPostWithHistory(postId) ?? throw new NullListException();
return _postStorageContract.GetPostWithHistory(postId);
}
public PostDataModel GetPostByData(string data)
@@ -42,16 +45,16 @@ internal class PostBusinessLogicContract(IPostStorageContract postStorageContrac
}
if (data.IsGuid())
{
return _postStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return _postStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data, _localizer);
}
return _postStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data);
return _postStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data, _localizer);
}
public void InsertPost(PostDataModel postDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(postDataModel));
ArgumentNullException.ThrowIfNull(postDataModel);
postDataModel.Validate();
postDataModel.Validate(_localizer);
_postStorageContract.AddElement(postDataModel);
}
@@ -59,7 +62,7 @@ internal class PostBusinessLogicContract(IPostStorageContract postStorageContrac
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(postDataModel));
ArgumentNullException.ThrowIfNull(postDataModel);
postDataModel.Validate();
postDataModel.Validate(_localizer);
_postStorageContract.UpdElement(postDataModel);
}
@@ -72,7 +75,7 @@ internal class PostBusinessLogicContract(IPostStorageContract postStorageContrac
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
}
_postStorageContract.DelElement(id);
}
@@ -86,7 +89,7 @@ internal class PostBusinessLogicContract(IPostStorageContract postStorageContrac
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
}
_postStorageContract.ResElement(id);
}

View File

@@ -2,21 +2,24 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Resources;
using CatHasPawsContratcs.StoragesContracts;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace CatHasPawsBusinessLogic.Implementations;
internal class ProductBusinessLogicContract(IProductStorageContract productStorageContract, ILogger logger) : IProductBusinessLogicContract
internal class ProductBusinessLogicContract(IProductStorageContract productStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : IProductBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IProductStorageContract _productStorageContract = productStorageContract;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<ProductDataModel> GetAllProducts(bool onlyActive)
{
_logger.LogInformation("GetAllProducts params: {onlyActive}", onlyActive);
return _productStorageContract.GetList(onlyActive) ?? throw new NullListException();
return _productStorageContract.GetList(onlyActive);
}
public List<ProductDataModel> GetAllProductsByManufacturer(string manufacturerId, bool onlyActive = true)
@@ -27,10 +30,10 @@ internal class ProductBusinessLogicContract(IProductStorageContract productStora
}
if (!manufacturerId.IsGuid())
{
throw new ValidationException("The value in the field manufacturerId is not a unique identifier.");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "ManufacturerId"));
}
_logger.LogInformation("GetAllProducts params: {manufacturerId}, {onlyActive}", manufacturerId, onlyActive);
return _productStorageContract.GetList(onlyActive, manufacturerId) ?? throw new NullListException();
return _productStorageContract.GetList(onlyActive, manufacturerId);
}
public List<ProductHistoryDataModel> GetProductHistoryByProduct(string productId)
@@ -42,9 +45,9 @@ internal class ProductBusinessLogicContract(IProductStorageContract productStora
}
if (!productId.IsGuid())
{
throw new ValidationException("The value in the field productId is not a unique identifier.");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "ProductId"));
}
return _productStorageContract.GetHistoryByProductId(productId) ?? throw new NullListException();
return _productStorageContract.GetHistoryByProductId(productId);
}
public ProductDataModel GetProductByData(string data)
@@ -56,16 +59,16 @@ internal class ProductBusinessLogicContract(IProductStorageContract productStora
}
if (data.IsGuid())
{
return _productStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return _productStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data, _localizer);
}
return _productStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data);
return _productStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data, _localizer);
}
public void InsertProduct(ProductDataModel productDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(productDataModel));
ArgumentNullException.ThrowIfNull(productDataModel);
productDataModel.Validate();
productDataModel.Validate(_localizer);
_productStorageContract.AddElement(productDataModel);
}
@@ -73,7 +76,7 @@ internal class ProductBusinessLogicContract(IProductStorageContract productStora
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(productDataModel));
ArgumentNullException.ThrowIfNull(productDataModel);
productDataModel.Validate();
productDataModel.Validate(_localizer);
_productStorageContract.UpdElement(productDataModel);
}
@@ -86,7 +89,7 @@ internal class ProductBusinessLogicContract(IProductStorageContract productStora
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
}
_productStorageContract.DelElement(id);
}

View File

@@ -3,39 +3,58 @@ using CatHasPawsContratcs.BusinessLogicsContracts;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Resources;
using CatHasPawsContratcs.StoragesContracts;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
namespace CatHasPawsBusinessLogic.Implementations;
internal class ReportContract(IProductStorageContract productStorageContract, ISaleStorageContract saleStorageContract, ISalaryStorageContract salaryStorageContract, BaseWordBuilder baseWordBuilder, BaseExcelBuilder baseExcelBuilder, BasePdfBuilder basePdfBuilder, ILogger logger) : IReportContract
internal class ReportContract : IReportContract
{
private readonly IProductStorageContract _productStorageContract = productStorageContract;
private readonly IProductStorageContract _productStorageContract;
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
private readonly ISaleStorageContract _saleStorageContract;
private readonly ISalaryStorageContract _salaryStorageContract = salaryStorageContract;
private readonly ISalaryStorageContract _salaryStorageContract;
private readonly BaseWordBuilder _baseWordBuilder = baseWordBuilder;
private readonly BaseWordBuilder _baseWordBuilder;
private readonly BaseExcelBuilder _baseExcelBuilder = baseExcelBuilder;
private readonly BaseExcelBuilder _baseExcelBuilder;
private readonly BasePdfBuilder _basePdfBuilder = basePdfBuilder;
private readonly BasePdfBuilder _basePdfBuilder;
private readonly ILogger _logger = logger;
private readonly IStringLocalizer<Messages> _localizer;
internal static readonly string[] documentHeader = ["Производитель", "Товар"];
private readonly ILogger _logger;
internal static readonly string[] tableHeader = ["Дата", "Сумма", "Скидка", "Товар", "Кол-во"];
internal readonly string[] _documentHeader;
internal readonly string[] _tableHeader;
public ReportContract(IProductStorageContract productStorageContract, ISaleStorageContract saleStorageContract, ISalaryStorageContract salaryStorageContract, BaseWordBuilder baseWordBuilder, BaseExcelBuilder baseExcelBuilder, BasePdfBuilder basePdfBuilder, IStringLocalizer<Messages> localizer, ILogger logger)
{
_productStorageContract = productStorageContract;
_saleStorageContract = saleStorageContract;
_salaryStorageContract = salaryStorageContract;
_baseWordBuilder = baseWordBuilder;
_baseExcelBuilder = baseExcelBuilder;
_basePdfBuilder = basePdfBuilder;
_localizer = localizer;
_logger = logger;
_documentHeader = [_localizer["DocumentDocCaptionManufacturer"], _localizer["DocumentDocCaptionProduct"]];
_tableHeader = [_localizer["DocumentExcelCaptionDate"], _localizer["DocumentExcelCaptionSum"],
_localizer["DocumentExcelCaptionDiscount"], _localizer["DocumentExcelCaptionProduct"], _localizer["DocumentExcelCaptionCount"]];
}
public async Task<Stream> CreateDocumentProductsByManufacturerAsync(CancellationToken ct)
{
_logger.LogInformation("Create report ProductsByManufacturer");
var data = await GetDataByProductsAsync(ct);
return _baseWordBuilder
.AddHeader("Продукты по производителям")
.AddParagraph($"Сформировано на дату {DateTime.Now}")
.AddTable([3000, 5000], [.. new List<string[]>() { documentHeader }.Union([.. data.SelectMany(x => (new List<string[]>() { new string[] { x.ManufacturerName, "" } }).Union(x.Products.Select(y => new string[] { "", y })))])])
.AddHeader(_localizer["DocumentDocHeader"])
.AddParagraph(string.Format(_localizer["DocumentDocSubHeader"], DateTime.Now))
.AddTable([3000, 5000], [.. new List<string[]>() { _documentHeader }.Union([.. data.SelectMany(x => (new List<string[]>() { new string[] { x.ManufacturerName, "" } }).Union(x.Products.Select(y => new string[] { "", y })))])])
.Build();
}
@@ -44,9 +63,9 @@ internal class ReportContract(IProductStorageContract productStorageContract, IS
_logger.LogInformation("Create report SalesByPeriod from {dateStart} to {dateFinish}", dateStart, dateFinish);
var data = await GetDataBySalesAsync(dateStart, dateFinish, ct) ?? throw new InvalidOperationException("No found data");
return _baseExcelBuilder
.AddHeader("Продажи за период", 0, 5)
.AddParagraph($"c {dateStart.ToShortDateString()} по {dateFinish.ToShortDateString()}", 2)
.AddTable([10, 10, 10, 10, 10], [.. new List<string[]>() { tableHeader }.Union(data.SelectMany(x => (new List<string[]>() { new string[] { x.SaleDate.ToShortDateString(), x.Sum.ToString("N2"), x.Discount.ToString("N2"), "", "" } }).Union(x.Products!.Select(y => new string[] { "", "", "", y.ProductName, y.Count.ToString("N2") })).ToArray())).Union([["Всего", data.Sum(x => x.Sum).ToString("N2"), data.Sum(x => x.Discount).ToString("N2"), "", ""]])])
.AddHeader(_localizer["DocumentExcelHeader"], 0, 5)
.AddParagraph(string.Format(_localizer["DocumentExcelSubHeader"], dateStart.ToLocalTime().ToShortDateString(), dateFinish.ToLocalTime().ToShortDateString()), 2)
.AddTable([10, 10, 10, 10, 10], [.. new List<string[]>() { _tableHeader }.Union(data.SelectMany(x => (new List<string[]>() { new string[] { x.SaleDate.ToShortDateString(), x.Sum.ToString("N2"), x.Discount.ToString("N2"), "", "" } }).Union(x.Products!.Select(y => new string[] { "", "", "", y.ProductName, y.Count.ToString("N2") })).ToArray())).Union([["Всего", data.Sum(x => x.Sum).ToString("N2"), data.Sum(x => x.Discount).ToString("N2"), "", ""]])])
.Build();
}
@@ -56,8 +75,8 @@ internal class ReportContract(IProductStorageContract productStorageContract, IS
_logger.LogInformation("Create report SalaryByPeriod from {dateStart} to {dateFinish}", dateStart, dateFinish);
var data = await GetDataBySalaryAsync(dateStart, dateFinish, ct) ?? throw new InvalidOperationException("No found data");
return _basePdfBuilder
.AddHeader("Зарплатная ведомость")
.AddParagraph($"за период с {dateStart.ToShortDateString()} по {dateFinish.ToShortDateString()}")
.AddHeader(_localizer["DocumentPdfHeader"])
.AddParagraph(string.Format(_localizer["DocumentPdfSubHeader"], dateStart.ToLocalTime().ToShortDateString(), dateFinish.ToLocalTime().ToShortDateString()))
.AddPieChart("Начисления", [.. data.Select(x => (x.WorkerFIO, x.TotalSalary))])
.Build();
}
@@ -84,7 +103,7 @@ internal class ReportContract(IProductStorageContract productStorageContract, IS
{
if (dateStart.IsDateNotOlder(dateFinish))
{
throw new IncorrectDatesException(dateStart, dateFinish);
throw new IncorrectDatesException(dateStart, dateFinish, _localizer);
}
return [.. (await _saleStorageContract.GetListAsync(dateStart, dateFinish, ct)).OrderBy(x => x.SaleDate)];
}
@@ -93,7 +112,7 @@ internal class ReportContract(IProductStorageContract productStorageContract, IS
{
if (dateStart.IsDateNotOlder(dateFinish))
{
throw new IncorrectDatesException(dateStart, dateFinish);
throw new IncorrectDatesException(dateStart, dateFinish, _localizer);
}
return [.. (await _salaryStorageContract.GetListAsync(dateStart, dateFinish, ct)).GroupBy(x => x.WorkerId).Select(x => new WorkerSalaryByPeriodDataModel { WorkerFIO = x.Key, TotalSalary = x.Sum(y => y.Salary), FromPeriod = x.Min(y => y.SalaryDate), ToPeriod = x.Max(y => y.SalaryDate) }).OrderBy(x => x.WorkerFIO)];
}

View File

@@ -4,12 +4,14 @@ using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Infrastructure;
using CatHasPawsContratcs.Infrastructure.PostConfigurations;
using CatHasPawsContratcs.Resources;
using CatHasPawsContratcs.StoragesContracts;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
namespace CatHasPawsBusinessLogic.Implementations;
internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract, ISaleStorageContract saleStorageContract, IPostStorageContract postStorageContract, IWorkerStorageContract workerStorageContract, ILogger logger, IConfigurationSalary сonfiguration) : ISalaryBusinessLogicContract
internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract, ISaleStorageContract saleStorageContract, IPostStorageContract postStorageContract, IWorkerStorageContract workerStorageContract, IStringLocalizer<Messages> localizer, ILogger logger, IConfigurationSalary сonfiguration) : ISalaryBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISalaryStorageContract _salaryStorageContract = salaryStorageContract;
@@ -17,6 +19,7 @@ internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageC
private readonly IPostStorageContract _postStorageContract = postStorageContract;
private readonly IWorkerStorageContract _workerStorageContract = workerStorageContract;
private readonly IConfigurationSalary _salaryConfiguration = сonfiguration;
private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly Lock _lockObject = new();
public List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate)
@@ -24,16 +27,16 @@ internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageC
_logger.LogInformation("GetAllSalaries params: {fromDate}, {toDate}", fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
throw new IncorrectDatesException(fromDate, toDate, _localizer);
}
return _salaryStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
return _salaryStorageContract.GetList(fromDate, toDate);
}
public List<SalaryDataModel> GetAllSalariesByPeriodByWorker(DateTime fromDate, DateTime toDate, string workerId)
{
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
throw new IncorrectDatesException(fromDate, toDate, _localizer);
}
if (workerId.IsEmpty())
{
@@ -41,10 +44,10 @@ internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageC
}
if (!workerId.IsGuid())
{
throw new ValidationException("The value in the field workerId is not a unique identifier.");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "WorkerId"));
}
_logger.LogInformation("GetAllSalaries params: {fromDate}, {toDate}, {workerId}", fromDate, toDate, workerId);
return _salaryStorageContract.GetList(fromDate, toDate, workerId) ?? throw new NullListException();
return _salaryStorageContract.GetList(fromDate, toDate, workerId);
}
public void CalculateSalaryByMounth(DateTime date)
@@ -52,11 +55,11 @@ internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageC
_logger.LogInformation("CalculateSalaryByMounth: {date}", date);
var startDate = new DateTime(date.Year, date.Month, 1);
var finishDate = new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month));
var workers = _workerStorageContract.GetList() ?? throw new NullListException();
var workers = _workerStorageContract.GetList();
foreach (var worker in workers)
{
var sales = _saleStorageContract.GetList(startDate, finishDate, workerId: worker.Id) ?? throw new NullListException();
var post = _postStorageContract.GetElementById(worker.PostId) ?? throw new NullListException();
var sales = _saleStorageContract.GetList(startDate, finishDate, workerId: worker.Id);
var post = _postStorageContract.GetElementById(worker.PostId) ?? throw new ElementNotFoundException(worker.PostId, _localizer);
var salary = post.ConfigurationModel switch
{
null => 0,

View File

@@ -2,25 +2,28 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Resources;
using CatHasPawsContratcs.StoragesContracts;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace CatHasPawsBusinessLogic.Implementations;
internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContract, ILogger logger) : ISaleBusinessLogicContract
internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : ISaleBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<SaleDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {fromDate}, {toDate}", fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
throw new IncorrectDatesException(fromDate, toDate, _localizer);
}
return _saleStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
return _saleStorageContract.GetList(fromDate, toDate);
}
public List<SaleDataModel> GetAllSalesByWorkerByPeriod(string workerId, DateTime fromDate, DateTime toDate)
@@ -28,7 +31,7 @@ internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContrac
_logger.LogInformation("GetAllSales params: {workerId}, {fromDate}, {toDate}", workerId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
throw new IncorrectDatesException(fromDate, toDate, _localizer);
}
if (workerId.IsEmpty())
{
@@ -36,9 +39,9 @@ internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContrac
}
if (!workerId.IsGuid())
{
throw new ValidationException("The value in the field workerId is not a unique identifier.");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "WorkerId"));
}
return _saleStorageContract.GetList(fromDate, toDate, workerId: workerId) ?? throw new NullListException();
return _saleStorageContract.GetList(fromDate, toDate, workerId: workerId);
}
public List<SaleDataModel> GetAllSalesByBuyerByPeriod(string buyerId, DateTime fromDate, DateTime toDate)
@@ -46,7 +49,7 @@ internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContrac
_logger.LogInformation("GetAllSales params: {buyerId}, {fromDate}, {toDate}", buyerId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
throw new IncorrectDatesException(fromDate, toDate, _localizer);
}
if (buyerId.IsEmpty())
{
@@ -54,9 +57,9 @@ internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContrac
}
if (!buyerId.IsGuid())
{
throw new ValidationException("The value in the field buyerId is not a unique identifier.");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "BuyerId"));
}
return _saleStorageContract.GetList(fromDate, toDate, buyerId: buyerId) ?? throw new NullListException();
return _saleStorageContract.GetList(fromDate, toDate, buyerId: buyerId);
}
public List<SaleDataModel> GetAllSalesByProductByPeriod(string productId, DateTime fromDate, DateTime toDate)
@@ -64,7 +67,7 @@ internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContrac
_logger.LogInformation("GetAllSales params: {productId}, {fromDate}, {toDate}", productId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
throw new IncorrectDatesException(fromDate, toDate, _localizer);
}
if (productId.IsEmpty())
{
@@ -72,9 +75,9 @@ internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContrac
}
if (!productId.IsGuid())
{
throw new ValidationException("The value in the field productId is not a unique identifier.");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "ProductId"));
}
return _saleStorageContract.GetList(fromDate, toDate, productId: productId) ?? throw new NullListException();
return _saleStorageContract.GetList(fromDate, toDate, productId: productId);
}
public SaleDataModel GetSaleByData(string data)
@@ -86,16 +89,16 @@ internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContrac
}
if (!data.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
}
return _saleStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return _saleStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data, _localizer);
}
public void InsertSale(SaleDataModel saleDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(saleDataModel));
ArgumentNullException.ThrowIfNull(saleDataModel);
saleDataModel.Validate();
saleDataModel.Validate(_localizer);
_saleStorageContract.AddElement(saleDataModel);
}
@@ -108,7 +111,7 @@ internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContrac
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
}
_saleStorageContract.DelElement(id);
}

View File

@@ -2,21 +2,24 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Resources;
using CatHasPawsContratcs.StoragesContracts;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace CatHasPawsBusinessLogic.Implementations;
internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageContract, ILogger logger) : IWorkerBusinessLogicContract
internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : IWorkerBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IWorkerStorageContract _workerStorageContract = workerStorageContract;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<WorkerDataModel> GetAllWorkers(bool onlyActive = true)
{
_logger.LogInformation("GetAllWorkers params: {onlyActive}", onlyActive);
return _workerStorageContract.GetList(onlyActive) ?? throw new NullListException();
return _workerStorageContract.GetList(onlyActive);
}
public List<WorkerDataModel> GetAllWorkersByPost(string postId, bool onlyActive = true)
@@ -28,9 +31,9 @@ internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageC
}
if (!postId.IsGuid())
{
throw new ValidationException("The value in the field postId is not a unique identifier.");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "PostId"));
}
return _workerStorageContract.GetList(onlyActive, postId) ?? throw new NullListException();
return _workerStorageContract.GetList(onlyActive, postId);
}
public List<WorkerDataModel> GetAllWorkersByBirthDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
@@ -38,9 +41,9 @@ internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageC
_logger.LogInformation("GetAllWorkers params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
throw new IncorrectDatesException(fromDate, toDate, _localizer);
}
return _workerStorageContract.GetList(onlyActive, fromBirthDate: fromDate, toBirthDate: toDate) ?? throw new NullListException();
return _workerStorageContract.GetList(onlyActive, fromBirthDate: fromDate, toBirthDate: toDate);
}
public List<WorkerDataModel> GetAllWorkersByEmploymentDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
@@ -48,9 +51,9 @@ internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageC
_logger.LogInformation("GetAllWorkers params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
throw new IncorrectDatesException(fromDate, toDate, _localizer);
}
return _workerStorageContract.GetList(onlyActive, fromEmploymentDate: fromDate, toEmploymentDate: toDate) ?? throw new NullListException();
return _workerStorageContract.GetList(onlyActive, fromEmploymentDate: fromDate, toEmploymentDate: toDate);
}
public WorkerDataModel GetWorkerByData(string data)
@@ -62,16 +65,16 @@ internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageC
}
if (data.IsGuid())
{
return _workerStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return _workerStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data, _localizer);
}
return _workerStorageContract.GetElementByFIO(data) ?? throw new ElementNotFoundException(data);
return _workerStorageContract.GetElementByFIO(data) ?? throw new ElementNotFoundException(data, _localizer);
}
public void InsertWorker(WorkerDataModel workerDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(workerDataModel));
ArgumentNullException.ThrowIfNull(workerDataModel);
workerDataModel.Validate();
workerDataModel.Validate(_localizer);
_workerStorageContract.AddElement(workerDataModel);
}
@@ -79,7 +82,7 @@ internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageC
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(workerDataModel));
ArgumentNullException.ThrowIfNull(workerDataModel);
workerDataModel.Validate();
workerDataModel.Validate(_localizer);
_workerStorageContract.UpdElement(workerDataModel);
}
@@ -92,7 +95,7 @@ internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageC
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
}
_workerStorageContract.DelElement(id);
}

View File

@@ -2,7 +2,7 @@
namespace CatHasPawsContratcs.BusinessLogicsContracts;
public interface IBuyerBusinessLogicContract
internal interface IBuyerBusinessLogicContract
{
List<BuyerDataModel> GetAllBuyers();

View File

@@ -2,7 +2,7 @@
namespace CatHasPawsContratcs.BusinessLogicsContracts;
public interface IManufacturerBusinessLogicContract
internal interface IManufacturerBusinessLogicContract
{
List<ManufacturerDataModel> GetAllManufacturers();

View File

@@ -2,7 +2,7 @@
namespace CatHasPawsContratcs.BusinessLogicsContracts;
public interface IPostBusinessLogicContract
internal interface IPostBusinessLogicContract
{
List<PostDataModel> GetAllPosts();

View File

@@ -2,7 +2,7 @@
namespace CatHasPawsContratcs.BusinessLogicsContracts;
public interface IProductBusinessLogicContract
internal interface IProductBusinessLogicContract
{
List<ProductDataModel> GetAllProducts(bool onlyActive = true);

View File

@@ -2,7 +2,7 @@
namespace CatHasPawsContratcs.BusinessLogicsContracts;
public interface IReportContract
internal interface IReportContract
{
Task<List<ManufacturerProductDataModel>> GetDataProductsByManufacturerAsync(CancellationToken ct);

View File

@@ -2,7 +2,7 @@
namespace CatHasPawsContratcs.BusinessLogicsContracts;
public interface ISalaryBusinessLogicContract
internal interface ISalaryBusinessLogicContract
{
List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate);

View File

@@ -2,7 +2,7 @@
namespace CatHasPawsContratcs.BusinessLogicsContracts;
public interface ISaleBusinessLogicContract
internal interface ISaleBusinessLogicContract
{
List<SaleDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate);

View File

@@ -2,7 +2,7 @@
namespace CatHasPawsContratcs.BusinessLogicsContracts;
public interface IWorkerBusinessLogicContract
internal interface IWorkerBusinessLogicContract
{
List<WorkerDataModel> GetAllWorkers(bool onlyActive = true);

View File

@@ -9,6 +9,30 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.3.0" />
<PackageReference Include="Microsoft.Extensions.Localization.Abstractions" Version="9.0.4" />
</ItemGroup>
<ItemGroup>
<Compile Update="Resources\Messages.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Messages.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Resources\Messages.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Messages.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="CatHasPawsBusinessLogic" />
<InternalsVisibleTo Include="CatHasPawsDatabase" />
<InternalsVisibleTo Include="CatHasPawsWebApi" />
<InternalsVisibleTo Include="CatHasPawsTests" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
</Project>

View File

@@ -1,11 +1,13 @@
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Infrastructure;
using CatHasPawsContratcs.Resources;
using Microsoft.Extensions.Localization;
using System.Text.RegularExpressions;
namespace CatHasPawsContratcs.DataModels;
public class BuyerDataModel(string id, string fio, string phoneNumber, double discountSize) : IValidation
internal class BuyerDataModel(string id, string fio, string phoneNumber, double discountSize) : IValidation
{
public string Id { get; private set; } = id;
@@ -15,21 +17,23 @@ public class BuyerDataModel(string id, string fio, string phoneNumber, double di
public double DiscountSize { get; private set; } = discountSize;
public void Validate()
public BuyerDataModel() : this(string.Empty, string.Empty, string.Empty, 0) { }
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
if (FIO.IsEmpty())
throw new ValidationException("Field FIO is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "FIO"));
if (PhoneNumber.IsEmpty())
throw new ValidationException("Field PhoneNumber is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "PhoneNumber"));
if (!Regex.IsMatch(PhoneNumber, @"^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7,10}$"))
throw new ValidationException("Field PhoneNumber is not a phone number");
throw new ValidationException(localizer["ValidationExceptionMessageIncorrectPhoneNumber"]);
}
}

View File

@@ -1,10 +1,12 @@
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Infrastructure;
using CatHasPawsContratcs.Resources;
using Microsoft.Extensions.Localization;
namespace CatHasPawsContratcs.DataModels;
public class ManufacturerDataModel(string id, string manufacturerName, string? prevManufacturerName, string? prevPrevManufacturerName) : IValidation
internal class ManufacturerDataModel(string id, string manufacturerName, string? prevManufacturerName, string? prevPrevManufacturerName) : IValidation
{
public string Id { get; private set; } = id;
@@ -16,15 +18,15 @@ public class ManufacturerDataModel(string id, string manufacturerName, string? p
public ManufacturerDataModel(string id, string manufacturerName) : this(id, manufacturerName, null, null) { }
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
if (ManufacturerName.IsEmpty())
throw new ValidationException("Field ManufacturerName is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "ManufacturerName"));
}
}

View File

@@ -3,12 +3,15 @@ using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Infrastructure;
using CatHasPawsContratcs.Infrastructure.PostConfigurations;
using Newtonsoft.Json.Linq;
using CatHasPawsContratcs.Mapper;
using CatHasPawsContratcs.Resources;
using Microsoft.Extensions.Localization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace CatHasPawsContratcs.DataModels;
public class PostDataModel(string postId, string postName, PostType postType, PostConfiguration configuration) : IValidation
internal class PostDataModel(string postId, string postName, PostType postType, PostConfiguration configuration) : IValidation
{
public string Id { get; private set; } = postId;
@@ -16,40 +19,46 @@ public class PostDataModel(string postId, string postName, PostType postType, Po
public PostType PostType { get; private set; } = postType;
[AlternativeName("ConfigurationJson")]
[AlternativeName("Configuration")]
[PostProcessing(MappingCallMethodName = "ParseJson")]
public PostConfiguration ConfigurationModel { get; private set; } = configuration;
public PostDataModel(string postId, string postName, PostType postType, string configurationJson) : this(postId, postName, postType, (PostConfiguration)null)
{
var obj = JToken.Parse(configurationJson);
if (obj is not null)
{
ConfigurationModel = obj.Value<string>("Type") switch
{
nameof(CashierPostConfiguration) => JsonConvert.DeserializeObject<CashierPostConfiguration>(configurationJson)!,
nameof(SupervisorPostConfiguration) => JsonConvert.DeserializeObject<SupervisorPostConfiguration>(configurationJson)!,
_ => JsonConvert.DeserializeObject<PostConfiguration>(configurationJson)!,
};
}
}
public PostDataModel() : this(string.Empty, string.Empty, PostType.None, null) { }
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
if (PostName.IsEmpty())
throw new ValidationException("Field PostName is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "PostName"));
if (PostType == PostType.None)
throw new ValidationException("Field PostType is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "PostType"));
if (ConfigurationModel is null)
throw new ValidationException("Field ConfigurationModel is not initialized");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotInitialized"], "ConfigurationModel"));
if (ConfigurationModel!.Rate <= 0)
throw new ValidationException("Field Rate is less or equal zero");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Rate"));
}
private PostConfiguration? ParseJson(string json)
{
var obj = JToken.Parse(json);
if (obj is not null)
{
return obj.Value<string>("Type") switch
{
nameof(CashierPostConfiguration) => JsonConvert.DeserializeObject<CashierPostConfiguration>(json)!,
nameof(SupervisorPostConfiguration) => JsonConvert.DeserializeObject<SupervisorPostConfiguration>(json)!,
_ => JsonConvert.DeserializeObject<PostConfiguration>(json)!,
};
}
return null;
}
}

View File

@@ -2,10 +2,12 @@
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Infrastructure;
using CatHasPawsContratcs.Resources;
using Microsoft.Extensions.Localization;
namespace CatHasPawsContratcs.DataModels;
public class ProductDataModel(string id, string productName, ProductType productType, string manufacturerId, double price, bool isDeleted) : IValidation
internal class ProductDataModel(string id, string productName, ProductType productType, string manufacturerId, double price, bool isDeleted) : IValidation
{
private readonly ManufacturerDataModel? _manufacturer;
@@ -30,27 +32,27 @@ public class ProductDataModel(string id, string productName, ProductType product
public ProductDataModel(string id, string productName, ProductType productType, string manufacturerId, double price) : this(id, productName, productType, manufacturerId, price, false) { }
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
if (ProductName.IsEmpty())
throw new ValidationException("Field ProductName is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "ProductName"));
if (ProductType == ProductType.None)
throw new ValidationException("Field ProductType is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "ProductType"));
if (ManufacturerId.IsEmpty())
throw new ValidationException("Field ManufacturerId is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "ManufacturerId"));
if (!ManufacturerId.IsGuid())
throw new ValidationException("The value in the field ManufacturerId is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "ManufacturerId"));
if (Price <= 0)
throw new ValidationException("Field Price is less than or equal to 0");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Price"));
}
}

View File

@@ -1,10 +1,12 @@
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Infrastructure;
using CatHasPawsContratcs.Resources;
using Microsoft.Extensions.Localization;
namespace CatHasPawsContratcs.DataModels;
public class ProductHistoryDataModel(string productId, double oldPrice) : IValidation
internal class ProductHistoryDataModel(string productId, double oldPrice) : IValidation
{
private readonly ProductDataModel? _product;
@@ -22,15 +24,15 @@ public class ProductHistoryDataModel(string productId, double oldPrice) : IValid
_product = product;
}
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (ProductId.IsEmpty())
throw new ValidationException("Field ProductId is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "ProductId"));
if (!ProductId.IsGuid())
throw new ValidationException("The value in the field ProductId is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "ProductId"));
if (OldPrice <= 0)
throw new ValidationException("Field OldPrice is less than or equal to 0");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "OldPrice"));
}
}

View File

@@ -1,26 +1,28 @@
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Infrastructure;
using CatHasPawsContratcs.Resources;
using Microsoft.Extensions.Localization;
namespace CatHasPawsContratcs.DataModels;
public class SalaryDataModel(string workerId, DateTime salaryDate, double workerSalary) : IValidation
internal class SalaryDataModel(string workerId, DateTime salaryDate, double workerSalary) : IValidation
{
public string WorkerId { get; private set; } = workerId;
public DateTime SalaryDate { get; private set; } = salaryDate;
public DateTime SalaryDate { get; private set; } = salaryDate.ToUniversalTime();
public double Salary { get; private set; } = workerSalary;
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (WorkerId.IsEmpty())
throw new ValidationException("Field WorkerId is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "WorkerId"));
if (!WorkerId.IsGuid())
throw new ValidationException("The value in the field WorkerId is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "WorkerId"));
if (Salary <= 0)
throw new ValidationException("Field Salary is less than or equal to 0");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Salary"));
}
}

View File

@@ -2,10 +2,12 @@
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Infrastructure;
using CatHasPawsContratcs.Resources;
using Microsoft.Extensions.Localization;
namespace CatHasPawsContratcs.DataModels;
public class SaleDataModel : IValidation
internal class SaleDataModel : IValidation
{
private readonly BuyerDataModel? _buyer;
@@ -76,27 +78,32 @@ public class SaleDataModel : IValidation
public SaleDataModel(string id, string workerId, string? buyerId, int discountType, List<SaleProductDataModel> products) : this(id, workerId, buyerId, (DiscountType)discountType, false, products) { }
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
if (WorkerId.IsEmpty())
throw new ValidationException("Field WorkerId is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "WorkerId"));
if (!WorkerId.IsGuid())
throw new ValidationException("The value in the field WorkerId is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "WorkerId"));
if (!BuyerId?.IsGuid() ?? !BuyerId?.IsEmpty() ?? false)
throw new ValidationException("The value in the field BuyerId is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "BuyerId"));
if (Sum <= 0)
throw new ValidationException("Field Sum is less than or equal to 0");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Sum"));
if ((Products?.Count ?? 0) == 0)
throw new ValidationException("The sale must include products");
if (Products is null)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotInitialized"], "Products"));
if (Products.Count == 0)
throw new ValidationException(localizer["ValidationExceptionMessageNoProductsInSale"]);
Products.ForEach(x => x.Validate(localizer));
}
}

View File

@@ -1,10 +1,12 @@
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Infrastructure;
using CatHasPawsContratcs.Resources;
using Microsoft.Extensions.Localization;
namespace CatHasPawsContratcs.DataModels;
public class SaleProductDataModel(string saleId, string productId, int count, double price) : IValidation
internal class SaleProductDataModel(string saleId, string productId, int count, double price) : IValidation
{
private readonly ProductDataModel? _product;
@@ -23,24 +25,24 @@ public class SaleProductDataModel(string saleId, string productId, int count, do
_product = product;
}
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (SaleId.IsEmpty())
throw new ValidationException("Field SaleId is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "SaleId"));
if (!SaleId.IsGuid())
throw new ValidationException("The value in the field SaleId is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "SaleId"));
if (ProductId.IsEmpty())
throw new ValidationException("Field ProductId is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "IProductIdd"));
if (!ProductId.IsGuid())
throw new ValidationException("The value in the field ProductId is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "ProductId"));
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Count"));
if (Price <= 0)
throw new ValidationException("Field Price is less than or equal to 0");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Price"));
}
}

View File

@@ -1,10 +1,12 @@
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Infrastructure;
using CatHasPawsContratcs.Resources;
using Microsoft.Extensions.Localization;
namespace CatHasPawsContratcs.DataModels;
public class WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted) : IValidation
internal class WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted) : IValidation
{
private readonly PostDataModel? _post;
@@ -14,9 +16,9 @@ public class WorkerDataModel(string id, string fio, string postId, DateTime birt
public string PostId { get; private set; } = postId;
public DateTime BirthDate { get; private set; } = birthDate;
public DateTime BirthDate { get; private set; } = birthDate.ToUniversalTime();
public DateTime EmploymentDate { get; private set; } = employmentDate;
public DateTime EmploymentDate { get; private set; } = employmentDate.ToUniversalTime();
public bool IsDeleted { get; private set; } = isDeleted;
@@ -29,30 +31,32 @@ public class WorkerDataModel(string id, string fio, string postId, DateTime birt
public WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate) : this(id, fio, postId, birthDate, employmentDate, false) { }
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
if (FIO.IsEmpty())
throw new ValidationException("Field FIO is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "FIO"));
if (PostId.IsEmpty())
throw new ValidationException("Field PostId is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "PostId"));
if (!PostId.IsGuid())
throw new ValidationException("The value in the field PostId is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "PostId"));
if (BirthDate.Date > DateTime.Now.AddYears(-16).Date)
throw new ValidationException($"Minors cannot be hired (BirthDate = {BirthDate.ToShortDateString()})");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageMinorsBirthDate"], BirthDate.ToShortDateString()));
if (EmploymentDate.Date < BirthDate.Date)
throw new ValidationException("The date of employment cannot be less than the date of birth");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmploymentDateAndBirthDate"],
EmploymentDate.ToShortDateString(), BirthDate.ToShortDateString()));
if ((EmploymentDate - BirthDate).TotalDays / 365 < 16) // EmploymentDate.Year - BirthDate.Year
throw new ValidationException($"Minors cannot be hired (EmploymentDate - {EmploymentDate.ToShortDateString()}, BirthDate - {BirthDate.ToShortDateString()})");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageMinorsEmploymentDate"],
EmploymentDate.ToShortDateString(), BirthDate.ToShortDateString()));
}
}

View File

@@ -1,6 +1,8 @@
namespace CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Resources;
using Microsoft.Extensions.Localization;
public class ElementDeletedException : Exception
{
public ElementDeletedException(string id) : base($"Cannot modify a deleted item (id: {id})") { }
}
namespace CatHasPawsContratcs.Exceptions;
internal class ElementDeletedException(string id, IStringLocalizer<Messages> localizer) :
Exception(string.Format(localizer["ElementDeletedExceptionMessage"], id))
{ }

View File

@@ -1,14 +1,12 @@
namespace CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Resources;
using Microsoft.Extensions.Localization;
public class ElementExistsException : Exception
namespace CatHasPawsContratcs.Exceptions;
internal class ElementExistsException(string paramName, string paramValue, IStringLocalizer<Messages> localizer) :
Exception(string.Format(localizer["ElementExistsExceptionMessage"], paramValue, paramName))
{
public string ParamName { get; private set; }
public string ParamName { get; private set; } = paramName;
public string ParamValue { get; private set; }
public ElementExistsException(string paramName, string paramValue) : base($"There is already an element with value{paramValue} of parameter {paramName}")
{
ParamName = paramName;
ParamValue = paramValue;
}
public string ParamValue { get; private set; } = paramValue;
}

View File

@@ -1,11 +1,10 @@
namespace CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Resources;
using Microsoft.Extensions.Localization;
public class ElementNotFoundException : Exception
{
public string Value { get; private set; }
namespace CatHasPawsContratcs.Exceptions;
public ElementNotFoundException(string value) : base($"Element not found at value = {value}")
internal class ElementNotFoundException(string value, IStringLocalizer<Messages> localizer) :
Exception(string.Format(localizer["ElementNotFoundExceptionMessage"], value))
{
Value = value;
}
public string Value { get; private set; } = value;
}

View File

@@ -1,6 +1,8 @@
namespace CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Resources;
using Microsoft.Extensions.Localization;
public class IncorrectDatesException : Exception
{
public IncorrectDatesException(DateTime start, DateTime end) : base($"The end date must be later than the start date.. StartDate: {start:dd.MM.YYYY}. EndDate: {end:dd.MM.YYYY}") { }
}
namespace CatHasPawsContratcs.Exceptions;
internal class IncorrectDatesException(DateTime start, DateTime end, IStringLocalizer<Messages> localizer) :
Exception(string.Format(localizer["IncorrectDatesExceptionMessage"], start.ToShortDateString(), end.ToShortDateString()))
{ }

View File

@@ -1,6 +0,0 @@
namespace CatHasPawsContratcs.Exceptions;
public class NullListException : Exception
{
public NullListException() : base("The returned list is null") { }
}

View File

@@ -1,6 +1,8 @@
namespace CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Resources;
using Microsoft.Extensions.Localization;
public class StorageException : Exception
{
public StorageException(Exception ex) : base($"Error while working in storage: {ex.Message}", ex) { }
}
namespace CatHasPawsContratcs.Exceptions;
internal class StorageException(Exception ex, IStringLocalizer<Messages> localizer) :
Exception(string.Format(localizer["StorageExceptionMessage"], ex.Message), ex)
{ }

View File

@@ -1,5 +1,4 @@
namespace CatHasPawsContratcs.Exceptions;
public class ValidationException(string message) : Exception(message)
{
}
{ }

View File

@@ -1,6 +1,9 @@
namespace CatHasPawsContratcs.Infrastructure;
using CatHasPawsContratcs.Resources;
using Microsoft.Extensions.Localization;
public interface IValidation
namespace CatHasPawsContratcs.Infrastructure;
internal interface IValidation
{
void Validate();
void Validate(IStringLocalizer<Messages> localizer);
}

View File

@@ -1,8 +1,12 @@
namespace CatHasPawsContratcs.Infrastructure.PostConfigurations;
using System.Globalization;
namespace CatHasPawsContratcs.Infrastructure.PostConfigurations;
public class PostConfiguration
{
public virtual string Type => nameof(PostConfiguration);
public double Rate { get; set; }
public string CultureName { get; set; } = CultureInfo.CurrentCulture.Name;
}

View File

@@ -0,0 +1,7 @@
namespace CatHasPawsContratcs.Mapper;
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
class AlternativeNameAttribute(string alternativeName) : Attribute
{
public string AlternativeName { get; set; } = alternativeName;
}

View File

@@ -0,0 +1,159 @@
using System.Collections;
using System.Reflection;
namespace CatHasPawsContratcs.Mapper;
internal static class CustomMapper
{
public static To MapObject<To>(object obj, To newObject)
{
ArgumentNullException.ThrowIfNull(obj);
ArgumentNullException.ThrowIfNull(newObject);
var typeFrom = obj.GetType();
var typeTo = newObject.GetType();
var propertiesFrom = typeFrom.GetProperties().Where(x => x.CanRead).ToArray();
foreach (var property in typeTo.GetProperties().Where(x => x.CanWrite))
{
//ignore
var propertyFrom = TryGetPropertyFrom(property, propertiesFrom);
if (propertyFrom is null)
{
FindAndMapDefaultValue(property, newObject);
continue;
}
var fromValue = propertyFrom.GetValue(obj);
var postProcessingAttribute = property.GetCustomAttribute<PostProcessingAttribute>();
if (postProcessingAttribute is not null)
{
var value = PostProcessing(fromValue, postProcessingAttribute, newObject);
if (value is not null)
{
property.SetValue(newObject, value);
}
continue;
}
if (propertyFrom.PropertyType.IsGenericType && propertyFrom.PropertyType.Name.StartsWith("List") && fromValue is not null)
{
fromValue = MapListOfObjects(property, fromValue);
}
if (fromValue is not null)
{
// propertyFrom is enum && property is not enum ToString
// property is enum Enum.TryParse
property.SetValue(newObject, fromValue);
}
}
// fields
var classPostProcessing = typeTo.GetCustomAttribute<PostProcessingAttribute>();
if (classPostProcessing is not null && classPostProcessing.MappingCallMethodName is not null)
{
var methodInfo = typeTo.GetMethod(classPostProcessing.MappingCallMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
methodInfo?.Invoke(newObject, []);
}
return newObject;
}
public static To MapObject<To>(object obj) => MapObject(obj, Activator.CreateInstance<To>()!);
public static To? MapObjectWithNull<To>(object? obj) => obj is null ? default : MapObject(obj, Activator.CreateInstance<To>());
private static PropertyInfo? TryGetPropertyFrom(PropertyInfo propertyTo, PropertyInfo[] propertiesFrom)
{
var customAttribute = propertyTo.GetCustomAttributes<AlternativeNameAttribute>()?
.ToArray()
.FirstOrDefault(x => propertiesFrom.Any(y => y.Name == x.AlternativeName));
if (customAttribute is not null)
{
return propertiesFrom.FirstOrDefault(x => x.Name == customAttribute.AlternativeName);
}
return propertiesFrom.FirstOrDefault(x => x.Name == propertyTo.Name);
}
private static object? PostProcessing<T>(object? value, PostProcessingAttribute postProcessingAttribute, T newObject)
{
if (value is null || newObject is null)
{
return null;
}
if (!string.IsNullOrEmpty(postProcessingAttribute.MappingCallMethodName))
{
var methodInfo =
newObject.GetType().GetMethod(postProcessingAttribute.MappingCallMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
if (methodInfo is not null)
{
return methodInfo.Invoke(newObject, [value]);
}
}
else if (postProcessingAttribute.ActionType != PostProcessingType.None)
{
switch (postProcessingAttribute.ActionType)
{
case PostProcessingType.ToUniversalTime:
return ToUniversalTime(value);
case PostProcessingType.ToLocalTime:
return ToLocalTime(value);
}
}
return null;
}
private static object? ToLocalTime(object? obj)
{
if (obj is DateTime date)
return date.ToLocalTime();
return obj;
}
private static object? ToUniversalTime(object? obj)
{
if (obj is DateTime date)
return date.ToUniversalTime();
return obj;
}
private static void FindAndMapDefaultValue<T>(PropertyInfo property, T newObject)
{
var defaultValueAttribute = property.GetCustomAttribute<DefaultValueAttribute>();
if (defaultValueAttribute is null)
{
return;
}
if (defaultValueAttribute.DefaultValue is not null)
{
property.SetValue(newObject, defaultValueAttribute.DefaultValue);
return;
}
var value = defaultValueAttribute.FuncName switch
{
"UtcNow" => DateTime.UtcNow,
_ => (object?)null,
};
if (value is not null)
{
property.SetValue(newObject, value);
}
}
private static object? MapListOfObjects(PropertyInfo propertyTo, object list)
{
var listResult = Activator.CreateInstance(propertyTo.PropertyType);
foreach (var elem in (IEnumerable)list)
{
var newElem = MapObject(elem, Activator.CreateInstance(propertyTo.PropertyType.GenericTypeArguments[0])!);
if (newElem is not null)
{
propertyTo.PropertyType.GetMethod("Add")!.Invoke(listResult, [newElem]);
}
}
return listResult;
}
}

View File

@@ -0,0 +1,9 @@
namespace CatHasPawsContratcs.Mapper;
[AttributeUsage(AttributeTargets.Property)]
class DefaultValueAttribute : Attribute
{
public object? DefaultValue { get; set; }
public string? FuncName { get; set; }
}

View File

@@ -0,0 +1,9 @@
namespace CatHasPawsContratcs.Mapper;
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class)]
class PostProcessingAttribute : Attribute
{
public string? MappingCallMethodName { get; set; }
public PostProcessingType ActionType { get; set; } = PostProcessingType.None;
}

View File

@@ -0,0 +1,10 @@
namespace CatHasPawsContratcs.Mapper;
enum PostProcessingType
{
None = -1,
ToUniversalTime = 1,
ToLocalTime = 2
}

View File

@@ -0,0 +1,405 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CatHasPawsContratcs.Resources {
using System;
/// <summary>
/// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
/// </summary>
// Этот класс создан автоматически классом StronglyTypedResourceBuilder
// с помощью такого средства, как ResGen или Visual Studio.
// Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
// с параметром /str или перестройте свой проект VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Messages {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Messages() {
}
/// <summary>
/// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("CatHasPawsContratcs.Resources.Messages", typeof(Messages).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Элемент по данным: {0} был удален.
/// </summary>
internal static string AdapterMessageElementDeletedException {
get {
return ResourceManager.GetString("AdapterMessageElementDeletedException", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Не найден элемент по данным: {0}.
/// </summary>
internal static string AdapterMessageElementNotFoundException {
get {
return ResourceManager.GetString("AdapterMessageElementNotFoundException", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Данные пусты.
/// </summary>
internal static string AdapterMessageEmptyDate {
get {
return ResourceManager.GetString("AdapterMessageEmptyDate", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Неправильные даты: {0}.
/// </summary>
internal static string AdapterMessageIncorrectDatesException {
get {
return ResourceManager.GetString("AdapterMessageIncorrectDatesException", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Ошибка при обработке данных: {0}.
/// </summary>
internal static string AdapterMessageInvalidOperationException {
get {
return ResourceManager.GetString("AdapterMessageInvalidOperationException", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Ошибка при работе с хранилищем данных: {0}.
/// </summary>
internal static string AdapterMessageStorageException {
get {
return ResourceManager.GetString("AdapterMessageStorageException", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Переданы неверные данные: {0}.
/// </summary>
internal static string AdapterMessageValidationException {
get {
return ResourceManager.GetString("AdapterMessageValidationException", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Производитель.
/// </summary>
internal static string DocumentDocCaptionManufacturer {
get {
return ResourceManager.GetString("DocumentDocCaptionManufacturer", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Товар.
/// </summary>
internal static string DocumentDocCaptionProduct {
get {
return ResourceManager.GetString("DocumentDocCaptionProduct", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Продукты по производителям.
/// </summary>
internal static string DocumentDocHeader {
get {
return ResourceManager.GetString("DocumentDocHeader", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Сформировано на дату {0}.
/// </summary>
internal static string DocumentDocSubHeader {
get {
return ResourceManager.GetString("DocumentDocSubHeader", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Кол-во.
/// </summary>
internal static string DocumentExcelCaptionCount {
get {
return ResourceManager.GetString("DocumentExcelCaptionCount", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Дата.
/// </summary>
internal static string DocumentExcelCaptionDate {
get {
return ResourceManager.GetString("DocumentExcelCaptionDate", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Скидка.
/// </summary>
internal static string DocumentExcelCaptionDiscount {
get {
return ResourceManager.GetString("DocumentExcelCaptionDiscount", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Товар.
/// </summary>
internal static string DocumentExcelCaptionProduct {
get {
return ResourceManager.GetString("DocumentExcelCaptionProduct", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Сумма.
/// </summary>
internal static string DocumentExcelCaptionSum {
get {
return ResourceManager.GetString("DocumentExcelCaptionSum", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Всего.
/// </summary>
internal static string DocumentExcelCaptionTotal {
get {
return ResourceManager.GetString("DocumentExcelCaptionTotal", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Продажи за период.
/// </summary>
internal static string DocumentExcelHeader {
get {
return ResourceManager.GetString("DocumentExcelHeader", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на c {0} по {1}.
/// </summary>
internal static string DocumentExcelSubHeader {
get {
return ResourceManager.GetString("DocumentExcelSubHeader", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Начисления.
/// </summary>
internal static string DocumentPdfDiagramCaption {
get {
return ResourceManager.GetString("DocumentPdfDiagramCaption", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Зарплатная ведомость.
/// </summary>
internal static string DocumentPdfHeader {
get {
return ResourceManager.GetString("DocumentPdfHeader", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на за период с {0} по {1}.
/// </summary>
internal static string DocumentPdfSubHeader {
get {
return ResourceManager.GetString("DocumentPdfSubHeader", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Нельзя изменить удаленный элемент (идентификатор: {0}).
/// </summary>
internal static string ElementDeletedExceptionMessage {
get {
return ResourceManager.GetString("ElementDeletedExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Уже существует элемент со значением {0} параметра {1}.
/// </summary>
internal static string ElementExistsExceptionMessage {
get {
return ResourceManager.GetString("ElementExistsExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Элемент не найден по значению = {0}.
/// </summary>
internal static string ElementNotFoundExceptionMessage {
get {
return ResourceManager.GetString("ElementNotFoundExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Дата окончания должна быть позже даты начала. Дата начала: {0}. ​​Дата окончания: {1}.
/// </summary>
internal static string IncorrectDatesExceptionMessage {
get {
return ResourceManager.GetString("IncorrectDatesExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Недостаточно данных для обработки: {0}.
/// </summary>
internal static string NotEnoughDataToProcessExceptionMessage {
get {
return ResourceManager.GetString("NotEnoughDataToProcessExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Не найдены данные.
/// </summary>
internal static string NotFoundDataMessage {
get {
return ResourceManager.GetString("NotFoundDataMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Ошибка при работе в хранилище: {0}.
/// </summary>
internal static string StorageExceptionMessage {
get {
return ResourceManager.GetString("StorageExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Дата трудоустройства не может быть раньше даты рождения ({0}, {1}).
/// </summary>
internal static string ValidationExceptionMessageEmploymentDateAndBirthDate {
get {
return ResourceManager.GetString("ValidationExceptionMessageEmploymentDateAndBirthDate", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле {0} пусто.
/// </summary>
internal static string ValidationExceptionMessageEmptyField {
get {
return ResourceManager.GetString("ValidationExceptionMessageEmptyField", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле Телефонный номер не является телефонным номером.
/// </summary>
internal static string ValidationExceptionMessageIncorrectPhoneNumber {
get {
return ResourceManager.GetString("ValidationExceptionMessageIncorrectPhoneNumber", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле {0} меньше или равно 0.
/// </summary>
internal static string ValidationExceptionMessageLessOrEqualZero {
get {
return ResourceManager.GetString("ValidationExceptionMessageLessOrEqualZero", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Несовершеннолетние не могут быть приняты на работу (Дата рождения: {0}).
/// </summary>
internal static string ValidationExceptionMessageMinorsBirthDate {
get {
return ResourceManager.GetString("ValidationExceptionMessageMinorsBirthDate", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Несовершеннолетние не могут быть приняты на работу (Дата трудоустройства {0}, Дата рождения: {1}).
/// </summary>
internal static string ValidationExceptionMessageMinorsEmploymentDate {
get {
return ResourceManager.GetString("ValidationExceptionMessageMinorsEmploymentDate", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на В продаже должен быть хотя бы один товар.
/// </summary>
internal static string ValidationExceptionMessageNoProductsInSale {
get {
return ResourceManager.GetString("ValidationExceptionMessageNoProductsInSale", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле {0} не является типом уникального идентификатора.
/// </summary>
internal static string ValidationExceptionMessageNotAId {
get {
return ResourceManager.GetString("ValidationExceptionMessageNotAId", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле {0} не проиницализировано.
/// </summary>
internal static string ValidationExceptionMessageNotInitialized {
get {
return ResourceManager.GetString("ValidationExceptionMessageNotInitialized", resourceCulture);
}
}
}
}

View File

@@ -0,0 +1,234 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="DocumentDocCaptionManufacturer" xml:space="preserve">
<value>Manufacturer</value>
</data>
<data name="DocumentDocCaptionProduct" xml:space="preserve">
<value>Product</value>
</data>
<data name="DocumentDocHeader" xml:space="preserve">
<value>Products by Manufacturer</value>
</data>
<data name="DocumentDocSubHeader" xml:space="preserve">
<value>Generated on date {0}</value>
</data>
<data name="DocumentExcelCaptionCount" xml:space="preserve">
<value>Count</value>
</data>
<data name="DocumentExcelCaptionDate" xml:space="preserve">
<value>Date</value>
</data>
<data name="DocumentExcelCaptionDiscount" xml:space="preserve">
<value>Discount</value>
</data>
<data name="DocumentExcelCaptionProduct" xml:space="preserve">
<value>Product</value>
</data>
<data name="DocumentExcelCaptionSum" xml:space="preserve">
<value>Sum</value>
</data>
<data name="DocumentExcelCaptionTotal" xml:space="preserve">
<value>Total</value>
</data>
<data name="DocumentExcelHeader" xml:space="preserve">
<value>Sales for the period</value>
</data>
<data name="DocumentExcelSubHeader" xml:space="preserve">
<value>from {0} to {1}</value>
</data>
<data name="DocumentPdfHeader" xml:space="preserve">
<value>Payroll</value>
</data>
<data name="DocumentPdfSubHeader" xml:space="preserve">
<value>for the period from {0} to {1}</value>
</data>
<data name="DocumentPdfDiagramCaption" xml:space="preserve">
<value>Accruals</value>
</data>
<data name="NotFoundDataMessage" xml:space="preserve">
<value>No data found</value>
</data>
<data name="ValidationExceptionMessageNotAId" xml:space="preserve">
<value>The value in the {0} field is not a unique identifier type.</value>
</data>
<data name="ValidationExceptionMessageEmptyField" xml:space="preserve">
<value>The value in field {0} is empty</value>
</data>
<data name="ValidationExceptionMessageIncorrectPhoneNumber" xml:space="preserve">
<value>The value in the Phone Number field is not a phone number.</value>
</data>
<data name="ValidationExceptionMessageNotInitialized" xml:space="preserve">
<value>The value in field {0} is not initialized</value>
</data>
<data name="ValidationExceptionMessageLessOrEqualZero" xml:space="preserve">
<value>The value in field {0} is less than or equal to 0</value>
</data>
<data name="ValidationExceptionMessageNoProductsInSale" xml:space="preserve">
<value>There must be at least one item on sale</value>
</data>
<data name="ValidationExceptionMessageMinorsBirthDate" xml:space="preserve">
<value>Minors cannot be hired (BirthDate = {0})</value>
</data>
<data name="ValidationExceptionMessageMinorsEmploymentDate" xml:space="preserve">
<value>Minors cannot be hired (EmploymentDate: {0}, BirthDate {1})</value>
</data>
<data name="ValidationExceptionMessageEmploymentDateAndBirthDate" xml:space="preserve">
<value>Date of employment cannot be earlier than date of birth ({0}, {1})</value>
</data>
<data name="AdapterMessageStorageException" xml:space="preserve">
<value>Error while working with data storage: {0}</value>
</data>
<data name="AdapterMessageEmptyDate" xml:space="preserve">
<value>Data is empty</value>
</data>
<data name="AdapterMessageElementNotFoundException" xml:space="preserve">
<value>Not found element by data: {0}</value>
</data>
<data name="AdapterMessageValidationException" xml:space="preserve">
<value>Incorrect data transmitted: {0}</value>
</data>
<data name="AdapterMessageElementDeletedException" xml:space="preserve">
<value>Element by data: {0} was deleted</value>
</data>
<data name="AdapterMessageInvalidOperationException" xml:space="preserve">
<value>Error processing data: {0}</value>
</data>
<data name="AdapterMessageIncorrectDatesException" xml:space="preserve">
<value>Incorrect dates: {0}</value>
</data>
<data name="ElementDeletedExceptionMessage" xml:space="preserve">
<value>Cannot modify a deleted item (id: {0})</value>
</data>
<data name="ElementExistsExceptionMessage" xml:space="preserve">
<value>There is already an element with value {0} of parameter {1}</value>
</data>
<data name="ElementNotFoundExceptionMessage" xml:space="preserve">
<value>Element not found at value = {0}</value>
</data>
<data name="IncorrectDatesExceptionMessage" xml:space="preserve">
<value>The end date must be later than the start date.. StartDate: {0}. EndDate: {1}</value>
</data>
<data name="NotEnoughDataToProcessExceptionMessage" xml:space="preserve">
<value>Not enough data to process: {0}</value>
</data>
<data name="StorageExceptionMessage" xml:space="preserve">
<value>Error while working in storage: {0}</value>
</data>
</root>

View File

@@ -0,0 +1,234 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="DocumentDocCaptionManufacturer" xml:space="preserve">
<value>Производитель</value>
</data>
<data name="DocumentDocCaptionProduct" xml:space="preserve">
<value>Товар</value>
</data>
<data name="DocumentDocHeader" xml:space="preserve">
<value>Продукты по производителям</value>
</data>
<data name="DocumentDocSubHeader" xml:space="preserve">
<value>Сформировано на дату {0}</value>
</data>
<data name="DocumentExcelCaptionCount" xml:space="preserve">
<value>Кол-во</value>
</data>
<data name="DocumentExcelCaptionDate" xml:space="preserve">
<value>Дата</value>
</data>
<data name="DocumentExcelCaptionDiscount" xml:space="preserve">
<value>Скидка</value>
</data>
<data name="DocumentExcelCaptionProduct" xml:space="preserve">
<value>Товар</value>
</data>
<data name="DocumentExcelCaptionSum" xml:space="preserve">
<value>Сумма</value>
</data>
<data name="DocumentExcelCaptionTotal" xml:space="preserve">
<value>Всего</value>
</data>
<data name="DocumentExcelHeader" xml:space="preserve">
<value>Продажи за период</value>
</data>
<data name="DocumentExcelSubHeader" xml:space="preserve">
<value>c {0} по {1}</value>
</data>
<data name="DocumentPdfHeader" xml:space="preserve">
<value>Зарплатная ведомость</value>
</data>
<data name="DocumentPdfSubHeader" xml:space="preserve">
<value>за период с {0} по {1}</value>
</data>
<data name="DocumentPdfDiagramCaption" xml:space="preserve">
<value>Начисления</value>
</data>
<data name="NotFoundDataMessage" xml:space="preserve">
<value>Не найдены данные</value>
</data>
<data name="ValidationExceptionMessageNotAId" xml:space="preserve">
<value>Значение в поле {0} не является типом уникального идентификатора</value>
</data>
<data name="ValidationExceptionMessageEmptyField" xml:space="preserve">
<value>Значение в поле {0} пусто</value>
</data>
<data name="ValidationExceptionMessageIncorrectPhoneNumber" xml:space="preserve">
<value>Значение в поле Телефонный номер не является телефонным номером</value>
</data>
<data name="ValidationExceptionMessageNotInitialized" xml:space="preserve">
<value>Значение в поле {0} не проиницализировано</value>
</data>
<data name="ValidationExceptionMessageLessOrEqualZero" xml:space="preserve">
<value>Значение в поле {0} меньше или равно 0</value>
</data>
<data name="ValidationExceptionMessageNoProductsInSale" xml:space="preserve">
<value>В продаже должен быть хотя бы один товар</value>
</data>
<data name="ValidationExceptionMessageMinorsBirthDate" xml:space="preserve">
<value>Несовершеннолетние не могут быть приняты на работу (Дата рождения: {0})</value>
</data>
<data name="ValidationExceptionMessageMinorsEmploymentDate" xml:space="preserve">
<value>Несовершеннолетние не могут быть приняты на работу (Дата трудоустройства {0}, Дата рождения: {1})</value>
</data>
<data name="ValidationExceptionMessageEmploymentDateAndBirthDate" xml:space="preserve">
<value>Дата трудоустройства не может быть раньше даты рождения ({0}, {1})</value>
</data>
<data name="AdapterMessageStorageException" xml:space="preserve">
<value>Ошибка при работе с хранилищем данных: {0}</value>
</data>
<data name="AdapterMessageEmptyDate" xml:space="preserve">
<value>Данные пусты</value>
</data>
<data name="AdapterMessageElementNotFoundException" xml:space="preserve">
<value>Не найден элемент по данным: {0}</value>
</data>
<data name="AdapterMessageValidationException" xml:space="preserve">
<value>Переданы неверные данные: {0}</value>
</data>
<data name="AdapterMessageElementDeletedException" xml:space="preserve">
<value>Элемент по данным: {0} был удален</value>
</data>
<data name="AdapterMessageInvalidOperationException" xml:space="preserve">
<value>Ошибка при обработке данных: {0}</value>
</data>
<data name="AdapterMessageIncorrectDatesException" xml:space="preserve">
<value>Неправильные даты: {0}</value>
</data>
<data name="ElementDeletedExceptionMessage" xml:space="preserve">
<value>Нельзя изменить удаленный элемент (идентификатор: {0})</value>
</data>
<data name="ElementExistsExceptionMessage" xml:space="preserve">
<value>Уже существует элемент со значением {0} параметра {1}</value>
</data>
<data name="ElementNotFoundExceptionMessage" xml:space="preserve">
<value>Элемент не найден по значению = {0}</value>
</data>
<data name="IncorrectDatesExceptionMessage" xml:space="preserve">
<value>Дата окончания должна быть позже даты начала. Дата начала: {0}. ​​Дата окончания: {1}</value>
</data>
<data name="NotEnoughDataToProcessExceptionMessage" xml:space="preserve">
<value>Недостаточно данных для обработки: {0}</value>
</data>
<data name="StorageExceptionMessage" xml:space="preserve">
<value>Ошибка при работе в хранилище: {0}</value>
</data>
</root>

View File

@@ -2,7 +2,7 @@
namespace CatHasPawsContratcs.StoragesContracts;
public interface IBuyerStorageContract
internal interface IBuyerStorageContract
{
List<BuyerDataModel> GetList();

View File

@@ -2,7 +2,7 @@
namespace CatHasPawsContratcs.StoragesContracts;
public interface IManufacturerStorageContract
internal interface IManufacturerStorageContract
{
List<ManufacturerDataModel> GetList();

View File

@@ -2,7 +2,7 @@
namespace CatHasPawsContratcs.StoragesContracts;
public interface IPostStorageContract
internal interface IPostStorageContract
{
List<PostDataModel> GetList();

View File

@@ -2,7 +2,7 @@
namespace CatHasPawsContratcs.StoragesContracts;
public interface IProductStorageContract
internal interface IProductStorageContract
{
List<ProductDataModel> GetList(bool onlyActive = true, string? manufacturerId = null);

View File

@@ -2,7 +2,7 @@
namespace CatHasPawsContratcs.StoragesContracts;
public interface ISalaryStorageContract
internal interface ISalaryStorageContract
{
List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? workerId = null);

View File

@@ -2,7 +2,7 @@
namespace CatHasPawsContratcs.StoragesContracts;
public interface ISaleStorageContract
internal interface ISaleStorageContract
{
List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? workerId = null, string? buyerId = null, string? productId = null);

View File

@@ -2,7 +2,7 @@
namespace CatHasPawsContratcs.StoragesContracts;
public interface IWorkerStorageContract
internal interface IWorkerStorageContract
{
List<WorkerDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null);

View File

@@ -1,4 +1,8 @@
namespace CatHasPawsContratcs.ViewModels;
using CatHasPawsContratcs.Infrastructure.PostConfigurations;
using CatHasPawsContratcs.Mapper;
using System.Text.Json;
namespace CatHasPawsContratcs.ViewModels;
public class PostViewModel
{
@@ -8,5 +12,10 @@ public class PostViewModel
public required string PostType { get; set; }
[AlternativeName("ConfigurationModel")]
[PostProcessing(MappingCallMethodName = "ParseConfiguration")]
public required string Configuration { get; set; }
private string ParseConfiguration(PostConfiguration model) =>
JsonSerializer.Serialize(model, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
}

View File

@@ -14,8 +14,6 @@ internal class CatHasPawsDbContext : DbContext
public CatHasPawsDbContext(IConfigurationDatabase configurationDatabase)
{
_configurationDatabase = configurationDatabase;
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

View File

@@ -1,39 +1,30 @@
using AutoMapper;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Mapper;
using CatHasPawsContratcs.Resources;
using CatHasPawsContratcs.StoragesContracts;
using CatHasPawsDatabase.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
namespace CatHasPawsDatabase.Implementations;
internal class BuyerStorageContract : IBuyerStorageContract
internal class BuyerStorageContract(CatHasPawsDbContext catHasPawsDbContext, IStringLocalizer<Messages> localizer) : IBuyerStorageContract
{
private readonly CatHasPawsDbContext _dbContext;
private readonly Mapper _mapper;
public BuyerStorageContract(CatHasPawsDbContext catHasPawsDbContext)
{
_dbContext = catHasPawsDbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Buyer, BuyerDataModel>();
cfg.CreateMap<BuyerDataModel, Buyer>();
});
_mapper = new Mapper(config);
}
private readonly CatHasPawsDbContext _dbContext = catHasPawsDbContext;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<BuyerDataModel> GetList()
{
try
{
return [.. _dbContext.Buyers.Select(x => _mapper.Map<BuyerDataModel>(x))];
return [.. _dbContext.Buyers.Select(x => CustomMapper.MapObject<BuyerDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -41,12 +32,12 @@ internal class BuyerStorageContract : IBuyerStorageContract
{
try
{
return _mapper.Map<BuyerDataModel>(GetBuyerById(id));
return CustomMapper.MapObjectWithNull<BuyerDataModel>(GetBuyerById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -54,12 +45,12 @@ internal class BuyerStorageContract : IBuyerStorageContract
{
try
{
return _mapper.Map<BuyerDataModel>(_dbContext.Buyers.FirstOrDefault(x => x.FIO == fio));
return CustomMapper.MapObjectWithNull<BuyerDataModel>(_dbContext.Buyers.FirstOrDefault(x => x.FIO == fio));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -67,12 +58,12 @@ internal class BuyerStorageContract : IBuyerStorageContract
{
try
{
return _mapper.Map<BuyerDataModel>(_dbContext.Buyers.FirstOrDefault(x => x.PhoneNumber == phoneNumber));
return CustomMapper.MapObjectWithNull<BuyerDataModel>(_dbContext.Buyers.FirstOrDefault(x => x.PhoneNumber == phoneNumber));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -80,23 +71,28 @@ internal class BuyerStorageContract : IBuyerStorageContract
{
try
{
_dbContext.Buyers.Add(_mapper.Map<Buyer>(buyerDataModel));
_dbContext.Buyers.Add(CustomMapper.MapObject<Buyer>(buyerDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", buyerDataModel.Id);
throw new ElementExistsException("Id", buyerDataModel.Id, _localizer);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Buyers_PhoneNumber" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PhoneNumber", buyerDataModel.PhoneNumber);
throw new ElementExistsException("PhoneNumber", buyerDataModel.PhoneNumber, _localizer);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "PK_Buyers" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", buyerDataModel.Id, _localizer);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -104,8 +100,8 @@ internal class BuyerStorageContract : IBuyerStorageContract
{
try
{
var element = GetBuyerById(buyerDataModel.Id) ?? throw new ElementNotFoundException(buyerDataModel.Id);
_dbContext.Buyers.Update(_mapper.Map(buyerDataModel, element));
var element = GetBuyerById(buyerDataModel.Id) ?? throw new ElementNotFoundException(buyerDataModel.Id, _localizer);
_dbContext.Buyers.Update(CustomMapper.MapObject(buyerDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
@@ -116,12 +112,12 @@ internal class BuyerStorageContract : IBuyerStorageContract
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Buyers_PhoneNumber" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PhoneNumber", buyerDataModel.PhoneNumber);
throw new ElementExistsException("PhoneNumber", buyerDataModel.PhoneNumber, _localizer);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -129,7 +125,7 @@ internal class BuyerStorageContract : IBuyerStorageContract
{
try
{
var element = GetBuyerById(id) ?? throw new ElementNotFoundException(id);
var element = GetBuyerById(id) ?? throw new ElementNotFoundException(id, _localizer);
_dbContext.Buyers.Remove(element);
_dbContext.SaveChanges();
}
@@ -141,7 +137,7 @@ internal class BuyerStorageContract : IBuyerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}

View File

@@ -1,9 +1,11 @@
using AutoMapper;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Resources;
using CatHasPawsContratcs.StoragesContracts;
using CatHasPawsDatabase.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
namespace CatHasPawsDatabase.Implementations;
@@ -12,8 +14,9 @@ internal class ManufacturerStorageContract : IManufacturerStorageContract
{
private readonly CatHasPawsDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public ManufacturerStorageContract(CatHasPawsDbContext dbContext)
public ManufacturerStorageContract(CatHasPawsDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
@@ -22,6 +25,7 @@ internal class ManufacturerStorageContract : IManufacturerStorageContract
cfg.CreateMap<ManufacturerDataModel, Manufacturer>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<ManufacturerDataModel> GetList()
@@ -33,7 +37,7 @@ internal class ManufacturerStorageContract : IManufacturerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -46,7 +50,7 @@ internal class ManufacturerStorageContract : IManufacturerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -59,7 +63,7 @@ internal class ManufacturerStorageContract : IManufacturerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -73,7 +77,7 @@ internal class ManufacturerStorageContract : IManufacturerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -87,17 +91,22 @@ internal class ManufacturerStorageContract : IManufacturerStorageContract
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", manufacturerDataModel.Id);
throw new ElementExistsException("Id", manufacturerDataModel.Id, _localizer);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Manufacturers_ManufacturerName" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("ManufacturerName", manufacturerDataModel.ManufacturerName);
throw new ElementExistsException("ManufacturerName", manufacturerDataModel.ManufacturerName, _localizer);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "PK_Manufacturers" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", manufacturerDataModel.Id, _localizer);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -105,7 +114,7 @@ internal class ManufacturerStorageContract : IManufacturerStorageContract
{
try
{
var element = GetManufacturerById(manufacturerDataModel.Id) ?? throw new ElementNotFoundException(manufacturerDataModel.Id);
var element = GetManufacturerById(manufacturerDataModel.Id) ?? throw new ElementNotFoundException(manufacturerDataModel.Id, _localizer);
if (element.ManufacturerName != manufacturerDataModel.ManufacturerName)
{
element.PrevPrevManufacturerName = element.PrevManufacturerName;
@@ -123,12 +132,12 @@ internal class ManufacturerStorageContract : IManufacturerStorageContract
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Manufacturers_ManufacturerName" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("ManufacturerName", manufacturerDataModel.ManufacturerName);
throw new ElementExistsException("ManufacturerName", manufacturerDataModel.ManufacturerName, _localizer);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -136,7 +145,7 @@ internal class ManufacturerStorageContract : IManufacturerStorageContract
{
try
{
var element = GetManufacturerById(id) ?? throw new ElementNotFoundException(id);
var element = GetManufacturerById(id) ?? throw new ElementNotFoundException(id, _localizer);
_dbContext.Manufacturers.Remove(element);
_dbContext.SaveChanges();
}
@@ -148,7 +157,7 @@ internal class ManufacturerStorageContract : IManufacturerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}

View File

@@ -1,9 +1,11 @@
using AutoMapper;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Resources;
using CatHasPawsContratcs.StoragesContracts;
using CatHasPawsDatabase.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
namespace CatHasPawsDatabase.Implementations;
@@ -12,8 +14,9 @@ internal class PostStorageContract : IPostStorageContract
{
private readonly CatHasPawsDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public PostStorageContract(CatHasPawsDbContext dbContext)
public PostStorageContract(CatHasPawsDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
@@ -28,6 +31,7 @@ internal class PostStorageContract : IPostStorageContract
.ForMember(x => x.Configuration, x => x.MapFrom(src => src.ConfigurationModel));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<PostDataModel> GetList()
@@ -39,7 +43,7 @@ internal class PostStorageContract : IPostStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -52,7 +56,7 @@ internal class PostStorageContract : IPostStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -65,7 +69,7 @@ internal class PostStorageContract : IPostStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -78,7 +82,7 @@ internal class PostStorageContract : IPostStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -92,17 +96,17 @@ internal class PostStorageContract : IPostStorageContract
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostName", postDataModel.PostName);
throw new ElementExistsException("PostName", postDataModel.PostName, _localizer);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostId_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostId", postDataModel.Id);
throw new ElementExistsException("PostId", postDataModel.Id, _localizer);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -113,10 +117,10 @@ internal class PostStorageContract : IPostStorageContract
var transaction = _dbContext.Database.BeginTransaction();
try
{
var element = GetPostById(postDataModel.Id) ?? throw new ElementNotFoundException(postDataModel.Id);
var element = GetPostById(postDataModel.Id) ?? throw new ElementNotFoundException(postDataModel.Id, _localizer);
if (!element.IsActual)
{
throw new ElementDeletedException(postDataModel.Id);
throw new ElementDeletedException(postDataModel.Id, _localizer);
}
element.IsActual = false;
_dbContext.SaveChanges();
@@ -134,7 +138,7 @@ internal class PostStorageContract : IPostStorageContract
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostName", postDataModel.PostName);
throw new ElementExistsException("PostName", postDataModel.PostName, _localizer);
}
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
{
@@ -144,7 +148,7 @@ internal class PostStorageContract : IPostStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -152,10 +156,10 @@ internal class PostStorageContract : IPostStorageContract
{
try
{
var element = GetPostById(id) ?? throw new ElementNotFoundException(id);
var element = GetPostById(id) ?? throw new ElementNotFoundException(id, _localizer);
if (!element.IsActual)
{
throw new ElementDeletedException(id);
throw new ElementDeletedException(id, _localizer);
}
element.IsActual = false;
_dbContext.SaveChanges();
@@ -171,7 +175,7 @@ internal class PostStorageContract : IPostStorageContract
{
try
{
var element = GetPostById(id) ?? throw new ElementNotFoundException(id);
var element = GetPostById(id) ?? throw new ElementNotFoundException(id, _localizer);
element.IsActual = true;
_dbContext.SaveChanges();
}

View File

@@ -1,9 +1,11 @@
using AutoMapper;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Resources;
using CatHasPawsContratcs.StoragesContracts;
using CatHasPawsDatabase.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
namespace CatHasPawsDatabase.Implementations;
@@ -12,8 +14,9 @@ internal class ProductStorageContract : IProductStorageContract
{
private readonly CatHasPawsDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public ProductStorageContract(CatHasPawsDbContext dbContext)
public ProductStorageContract(CatHasPawsDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
@@ -25,6 +28,7 @@ internal class ProductStorageContract : IProductStorageContract
cfg.CreateMap<ProductHistory, ProductHistoryDataModel>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<ProductDataModel> GetList(bool onlyActive = true, string? manufacturerId = null)
@@ -45,7 +49,7 @@ internal class ProductStorageContract : IProductStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -58,7 +62,7 @@ internal class ProductStorageContract : IProductStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -71,7 +75,7 @@ internal class ProductStorageContract : IProductStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -84,7 +88,7 @@ internal class ProductStorageContract : IProductStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -97,7 +101,7 @@ internal class ProductStorageContract : IProductStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -111,17 +115,22 @@ internal class ProductStorageContract : IProductStorageContract
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", productDataModel.Id);
throw new ElementExistsException("Id", productDataModel.Id, _localizer);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Products_ProductName_IsDeleted" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("ProductName", productDataModel.ProductName);
throw new ElementExistsException("ProductName", productDataModel.ProductName, _localizer);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "PK_Products" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", productDataModel.Id, _localizer);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -132,7 +141,7 @@ internal class ProductStorageContract : IProductStorageContract
var transaction = _dbContext.Database.BeginTransaction();
try
{
var element = GetProductById(productDataModel.Id) ?? throw new ElementNotFoundException(productDataModel.Id);
var element = GetProductById(productDataModel.Id) ?? throw new ElementNotFoundException(productDataModel.Id, _localizer);
if (element.Price != productDataModel.Price)
{
_dbContext.ProductHistories.Add(new ProductHistory() { ProductId = element.Id, OldPrice = element.Price });
@@ -151,7 +160,7 @@ internal class ProductStorageContract : IProductStorageContract
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Products_ProductName_IsDeleted" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("ProductName", productDataModel.ProductName);
throw new ElementExistsException("ProductName", productDataModel.ProductName, _localizer);
}
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
{
@@ -161,7 +170,7 @@ internal class ProductStorageContract : IProductStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -169,7 +178,7 @@ internal class ProductStorageContract : IProductStorageContract
{
try
{
var element = GetProductById(id) ?? throw new ElementNotFoundException(id);
var element = GetProductById(id) ?? throw new ElementNotFoundException(id, _localizer);
element.IsDeleted = true;
_dbContext.SaveChanges();
}
@@ -181,7 +190,7 @@ internal class ProductStorageContract : IProductStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}

View File

@@ -1,9 +1,11 @@
using AutoMapper;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Resources;
using CatHasPawsContratcs.StoragesContracts;
using CatHasPawsDatabase.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
namespace CatHasPawsDatabase.Implementations;
@@ -11,8 +13,9 @@ internal class SalaryStorageContract : ISalaryStorageContract
{
private readonly CatHasPawsDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public SalaryStorageContract(CatHasPawsDbContext dbContext)
public SalaryStorageContract(CatHasPawsDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
@@ -22,6 +25,7 @@ internal class SalaryStorageContract : ISalaryStorageContract
.ForMember(dest => dest.WorkerSalary, opt => opt.MapFrom(src => src.Salary));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? workerId = null)
@@ -38,7 +42,7 @@ internal class SalaryStorageContract : ISalaryStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -51,7 +55,7 @@ internal class SalaryStorageContract : ISalaryStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -65,7 +69,7 @@ internal class SalaryStorageContract : ISalaryStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
}

View File

@@ -1,9 +1,11 @@
using AutoMapper;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Resources;
using CatHasPawsContratcs.StoragesContracts;
using CatHasPawsDatabase.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
namespace CatHasPawsDatabase.Implementations;
@@ -11,8 +13,9 @@ internal class SaleStorageContract : ISaleStorageContract
{
private readonly CatHasPawsDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public SaleStorageContract(CatHasPawsDbContext dbContext)
public SaleStorageContract(CatHasPawsDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
@@ -29,6 +32,7 @@ internal class SaleStorageContract : ISaleStorageContract
.ForMember(x => x.SaleProducts, x => x.MapFrom(src => src.Products));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? workerId = null, string? buyerId = null, string? productId = null)
@@ -57,7 +61,7 @@ internal class SaleStorageContract : ISaleStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -70,7 +74,7 @@ internal class SaleStorageContract : ISaleStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -83,7 +87,7 @@ internal class SaleStorageContract : ISaleStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -97,7 +101,7 @@ internal class SaleStorageContract : ISaleStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -105,10 +109,10 @@ internal class SaleStorageContract : ISaleStorageContract
{
try
{
var element = GetSaleById(id) ?? throw new ElementNotFoundException(id);
var element = GetSaleById(id) ?? throw new ElementNotFoundException(id, _localizer);
if (element.IsCancel)
{
throw new ElementDeletedException(id);
throw new ElementDeletedException(id, _localizer);
}
element.IsCancel = true;
_dbContext.SaveChanges();
@@ -121,7 +125,7 @@ internal class SaleStorageContract : ISaleStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}

View File

@@ -1,8 +1,12 @@
using AutoMapper;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Resources;
using CatHasPawsContratcs.StoragesContracts;
using CatHasPawsDatabase.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
namespace CatHasPawsDatabase.Implementations;
@@ -10,8 +14,9 @@ internal class WorkerStorageContract : IWorkerStorageContract
{
private readonly CatHasPawsDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public WorkerStorageContract(CatHasPawsDbContext dbContext)
public WorkerStorageContract(CatHasPawsDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
@@ -22,6 +27,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
cfg.CreateMap<WorkerDataModel, Worker>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<WorkerDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null)
@@ -50,7 +56,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -63,7 +69,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -76,7 +82,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -90,12 +96,17 @@ internal class WorkerStorageContract : IWorkerStorageContract
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", workerDataModel.Id);
throw new ElementExistsException("Id", workerDataModel.Id, _localizer);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "PK_Workers" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", workerDataModel.Id, _localizer);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -103,7 +114,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
{
try
{
var element = GetWorkerById(workerDataModel.Id) ?? throw new ElementNotFoundException(workerDataModel.Id);
var element = GetWorkerById(workerDataModel.Id) ?? throw new ElementNotFoundException(workerDataModel.Id, _localizer);
_dbContext.Workers.Update(_mapper.Map(workerDataModel, element));
_dbContext.SaveChanges();
}
@@ -115,7 +126,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -123,7 +134,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
{
try
{
var element = GetWorkerById(id) ?? throw new ElementNotFoundException(id);
var element = GetWorkerById(id) ?? throw new ElementNotFoundException(id, _localizer);
element.IsDeleted = true;
element.DateOfDelete = DateTime.UtcNow;
_dbContext.SaveChanges();
@@ -136,7 +147,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -151,7 +162,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}

View File

@@ -1,5 +1,6 @@
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Infrastructure.PostConfigurations;
using CatHasPawsContratcs.Mapper;
namespace CatHasPawsDatabase.Models;
@@ -13,9 +14,12 @@ internal class Post
public PostType PostType { get; set; }
[AlternativeName("ConfigurationModel")]
public required PostConfiguration Configuration { get; set; }
[DefaultValue(DefaultValue = true)]
public bool IsActual { get; set; }
[DefaultValue(FuncName = "UtcNow")]
public DateTime ChangeDate { get; set; }
}

View File

@@ -2,6 +2,7 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.StoragesContracts;
using CatHasPawsTests.Infrastructure;
using Microsoft.Extensions.Logging;
using Moq;
@@ -17,7 +18,7 @@ internal class BuyerBusinessLogicContractTests
public void OneTimeSetUp()
{
_buyerStorageContract = new Mock<IBuyerStorageContract>();
_buyerBusinessLogicContract = new BuyerBusinessLogicContract(_buyerStorageContract.Object, new Mock<ILogger>().Object);
_buyerBusinessLogicContract = new BuyerBusinessLogicContract(_buyerStorageContract.Object, StringLocalizerMockCreator.GetObject(), new Mock<ILogger>().Object);
}
[SetUp]
@@ -57,19 +58,11 @@ internal class BuyerBusinessLogicContractTests
_buyerStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllBuyers_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.GetAllBuyers(), Throws.TypeOf<NullListException>());
_buyerStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllBuyers_StorageThrowError_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
_buyerStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.GetAllBuyers(), Throws.TypeOf<StorageException>());
_buyerStorageContract.Verify(x => x.GetList(), Times.Once);
@@ -165,9 +158,9 @@ internal class BuyerBusinessLogicContractTests
public void GetBuyerByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_buyerStorageContract.Setup(x => x.GetElementByFIO(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_buyerStorageContract.Setup(x => x.GetElementByPhoneNumber(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_buyerStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_buyerStorageContract.Setup(x => x.GetElementByFIO(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_buyerStorageContract.Setup(x => x.GetElementByPhoneNumber(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.GetBuyerByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _buyerBusinessLogicContract.GetBuyerByData("fio"), Throws.TypeOf<StorageException>());
@@ -200,7 +193,7 @@ internal class BuyerBusinessLogicContractTests
public void InsertBuyer_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.AddElement(It.IsAny<BuyerDataModel>())).Throws(new ElementExistsException("Data", "Data"));
_buyerStorageContract.Setup(x => x.AddElement(It.IsAny<BuyerDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.InsertBuyer(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0)), Throws.TypeOf<ElementExistsException>());
_buyerStorageContract.Verify(x => x.AddElement(It.IsAny<BuyerDataModel>()), Times.Once);
@@ -226,7 +219,7 @@ internal class BuyerBusinessLogicContractTests
public void InsertBuyer_StorageThrowError_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.AddElement(It.IsAny<BuyerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
_buyerStorageContract.Setup(x => x.AddElement(It.IsAny<BuyerDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.InsertBuyer(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0)), Throws.TypeOf<StorageException>());
_buyerStorageContract.Verify(x => x.AddElement(It.IsAny<BuyerDataModel>()), Times.Once);
@@ -255,7 +248,7 @@ internal class BuyerBusinessLogicContractTests
public void UpdateBuyer_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.UpdElement(It.IsAny<BuyerDataModel>())).Throws(new ElementNotFoundException(""));
_buyerStorageContract.Setup(x => x.UpdElement(It.IsAny<BuyerDataModel>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.UpdateBuyer(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0)), Throws.TypeOf<ElementNotFoundException>());
_buyerStorageContract.Verify(x => x.UpdElement(It.IsAny<BuyerDataModel>()), Times.Once);
@@ -265,7 +258,7 @@ internal class BuyerBusinessLogicContractTests
public void UpdateBuyer_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.UpdElement(It.IsAny<BuyerDataModel>())).Throws(new ElementExistsException("Data", "Data"));
_buyerStorageContract.Setup(x => x.UpdElement(It.IsAny<BuyerDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.UpdateBuyer(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0)), Throws.TypeOf<ElementExistsException>());
_buyerStorageContract.Verify(x => x.UpdElement(It.IsAny<BuyerDataModel>()), Times.Once);
@@ -291,7 +284,7 @@ internal class BuyerBusinessLogicContractTests
public void UpdateBuyer_StorageThrowError_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.UpdElement(It.IsAny<BuyerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
_buyerStorageContract.Setup(x => x.UpdElement(It.IsAny<BuyerDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.UpdateBuyer(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0)), Throws.TypeOf<StorageException>());
_buyerStorageContract.Verify(x => x.UpdElement(It.IsAny<BuyerDataModel>()), Times.Once);
@@ -315,7 +308,7 @@ internal class BuyerBusinessLogicContractTests
public void DeleteBuyer_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(""));
_buyerStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.DeleteBuyer(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_buyerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
@@ -342,7 +335,7 @@ internal class BuyerBusinessLogicContractTests
public void DeleteBuyer_StorageThrowError_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_buyerStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.DeleteBuyer(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_buyerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);

View File

@@ -2,6 +2,7 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.StoragesContracts;
using CatHasPawsTests.Infrastructure;
using Microsoft.Extensions.Logging;
using Moq;
@@ -17,7 +18,7 @@ internal class ManufacturerBusinessLogicContractTests
public void OneTimeSetUp()
{
_manufacturerStorageContract = new Mock<IManufacturerStorageContract>();
_manufacturerBusinessLogicContract = new ManufacturerBusinessLogicContract(_manufacturerStorageContract.Object, new Mock<ILogger>().Object);
_manufacturerBusinessLogicContract = new ManufacturerBusinessLogicContract(_manufacturerStorageContract.Object, StringLocalizerMockCreator.GetObject(), new Mock<ILogger>().Object);
}
[SetUp]
@@ -57,19 +58,11 @@ internal class ManufacturerBusinessLogicContractTests
_manufacturerStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllManufacturers_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.GetAllManufacturers(), Throws.TypeOf<NullListException>());
_manufacturerStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllManufacturers_StorageThrowError_ThrowException_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
_manufacturerStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.GetAllManufacturers(), Throws.TypeOf<StorageException>());
_manufacturerStorageContract.Verify(x => x.GetList(), Times.Once);
@@ -156,8 +149,8 @@ internal class ManufacturerBusinessLogicContractTests
public void GetManufacturerByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_manufacturerStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_manufacturerStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_manufacturerStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.GetManufacturerByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _manufacturerBusinessLogicContract.GetManufacturerByData("name"), Throws.TypeOf<StorageException>());
@@ -170,7 +163,7 @@ internal class ManufacturerBusinessLogicContractTests
public void GetManufacturerByData_GetByOldName_StorageThrowError_ThrowException_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x => x.GetElementByOldName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_manufacturerStorageContract.Setup(x => x.GetElementByOldName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.GetManufacturerByData("name"), Throws.TypeOf<StorageException>());
_manufacturerStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
@@ -199,7 +192,7 @@ internal class ManufacturerBusinessLogicContractTests
public void InsertManufacturer_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x => x.AddElement(It.IsAny<ManufacturerDataModel>())).Throws(new ElementExistsException("Data", "Data"));
_manufacturerStorageContract.Setup(x => x.AddElement(It.IsAny<ManufacturerDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.InsertManufacturer(new(Guid.NewGuid().ToString(), "name", null, null)), Throws.TypeOf<ElementExistsException>());
_manufacturerStorageContract.Verify(x => x.AddElement(It.IsAny<ManufacturerDataModel>()), Times.Once);
@@ -225,7 +218,7 @@ internal class ManufacturerBusinessLogicContractTests
public void InsertManufacturer_StorageThrowError_ThrowException_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x => x.AddElement(It.IsAny<ManufacturerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
_manufacturerStorageContract.Setup(x => x.AddElement(It.IsAny<ManufacturerDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.InsertManufacturer(new(Guid.NewGuid().ToString(), "name", null, null)), Throws.TypeOf<StorageException>());
_manufacturerStorageContract.Verify(x => x.AddElement(It.IsAny<ManufacturerDataModel>()), Times.Once);
@@ -253,7 +246,7 @@ internal class ManufacturerBusinessLogicContractTests
public void UpdateManufacturer_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x => x.UpdElement(It.IsAny<ManufacturerDataModel>())).Throws(new ElementNotFoundException(""));
_manufacturerStorageContract.Setup(x => x.UpdElement(It.IsAny<ManufacturerDataModel>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.UpdateManufacturer(new(Guid.NewGuid().ToString(), "name", null, null)), Throws.TypeOf<ElementNotFoundException>());
_manufacturerStorageContract.Verify(x => x.UpdElement(It.IsAny<ManufacturerDataModel>()), Times.Once);
@@ -263,7 +256,7 @@ internal class ManufacturerBusinessLogicContractTests
public void UpdateManufacturer_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x => x.UpdElement(It.IsAny<ManufacturerDataModel>())).Throws(new ElementExistsException("Data", "Data"));
_manufacturerStorageContract.Setup(x => x.UpdElement(It.IsAny<ManufacturerDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.UpdateManufacturer(new(Guid.NewGuid().ToString(), "name", null, null)), Throws.TypeOf<ElementExistsException>());
_manufacturerStorageContract.Verify(x => x.UpdElement(It.IsAny<ManufacturerDataModel>()), Times.Once);
@@ -289,7 +282,7 @@ internal class ManufacturerBusinessLogicContractTests
public void UpdateManufacturer_StorageThrowError_ThrowException_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x => x.UpdElement(It.IsAny<ManufacturerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
_manufacturerStorageContract.Setup(x => x.UpdElement(It.IsAny<ManufacturerDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.UpdateManufacturer(new(Guid.NewGuid().ToString(), "name", null, null)), Throws.TypeOf<StorageException>());
_manufacturerStorageContract.Verify(x => x.UpdElement(It.IsAny<ManufacturerDataModel>()), Times.Once);
@@ -314,7 +307,7 @@ internal class ManufacturerBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
_manufacturerStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
_manufacturerStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.DeleteManufacturer(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_manufacturerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
@@ -341,7 +334,7 @@ internal class ManufacturerBusinessLogicContractTests
public void DeleteManufacturer_StorageThrowError_ThrowException_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_manufacturerStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _manufacturerBusinessLogicContract.DeleteManufacturer(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_manufacturerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);

View File

@@ -4,6 +4,7 @@ using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Infrastructure.PostConfigurations;
using CatHasPawsContratcs.StoragesContracts;
using CatHasPawsTests.Infrastructure;
using Microsoft.Extensions.Logging;
using Moq;
@@ -19,7 +20,7 @@ internal class PostBusinessLogicContractTests
public void OneTimeSetUp()
{
_postStorageContract = new Mock<IPostStorageContract>();
_postBusinessLogicContract = new PostBusinessLogicContract(_postStorageContract.Object, new Mock<ILogger>().Object);
_postBusinessLogicContract = new PostBusinessLogicContract(_postStorageContract.Object, StringLocalizerMockCreator.GetObject(), new Mock<ILogger>().Object);
}
[SetUp]
@@ -65,19 +66,11 @@ internal class PostBusinessLogicContractTests
});
}
[Test]
public void GetAllPosts_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllPosts(), Throws.TypeOf<NullListException>());
_postStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllPosts_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllPosts(), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetList(), Times.Once);
@@ -132,19 +125,11 @@ internal class PostBusinessLogicContractTests
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllDataOfPost_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(Guid.NewGuid().ToString()), Throws.TypeOf<NullListException>());
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllDataOfPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
@@ -212,8 +197,8 @@ internal class PostBusinessLogicContractTests
public void GetPostByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_postStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _postBusinessLogicContract.GetPostByData("name"), Throws.TypeOf<StorageException>());
@@ -243,7 +228,7 @@ internal class PostBusinessLogicContractTests
public void InsertPost_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Supervisor, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
@@ -269,7 +254,7 @@ internal class PostBusinessLogicContractTests
public void InsertPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Supervisor, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
@@ -297,7 +282,7 @@ internal class PostBusinessLogicContractTests
public void UpdatePost_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementNotFoundException(""));
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Supervisor, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
@@ -307,7 +292,7 @@ internal class PostBusinessLogicContractTests
public void UpdatePost_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.Supervisor, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
@@ -333,7 +318,7 @@ internal class PostBusinessLogicContractTests
public void UpdatePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Supervisor, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
@@ -358,7 +343,7 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
_postStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
@@ -385,7 +370,7 @@ internal class PostBusinessLogicContractTests
public void DeletePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
@@ -410,7 +395,7 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
_postStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);
@@ -437,7 +422,7 @@ internal class PostBusinessLogicContractTests
public void RestorePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);

View File

@@ -3,6 +3,7 @@ using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.StoragesContracts;
using CatHasPawsTests.Infrastructure;
using Microsoft.Extensions.Logging;
using Moq;
@@ -18,7 +19,7 @@ internal class ProductBusinessLogicContractTests
public void OneTimeSetUp()
{
_productStorageContract = new Mock<IProductStorageContract>();
_productBusinessLogicContract = new ProductBusinessLogicContract(_productStorageContract.Object, new Mock<ILogger>().Object);
_productBusinessLogicContract = new ProductBusinessLogicContract(_productStorageContract.Object, StringLocalizerMockCreator.GetObject(), new Mock<ILogger>().Object);
}
[SetUp]
@@ -72,19 +73,11 @@ internal class ProductBusinessLogicContractTests
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), null), Times.Exactly(2));
}
[Test]
public void GetAllProducts_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetAllProducts(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllProducts_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_productStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetAllProducts(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>()), Times.Once);
@@ -154,19 +147,11 @@ internal class ProductBusinessLogicContractTests
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllProductsByManufacturer_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetAllProductsByManufacturer(Guid.NewGuid().ToString(), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllProductsByManufacturer_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_productStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetAllProductsByManufacturer(Guid.NewGuid().ToString(), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>()), Times.Once);
@@ -222,19 +207,11 @@ internal class ProductBusinessLogicContractTests
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetProductHistoryByProduct_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(Guid.NewGuid().ToString()), Throws.TypeOf<NullListException>());
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductHistoryByProduct_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetHistoryByProductId(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_productStorageContract.Setup(x => x.GetHistoryByProductId(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Once);
@@ -300,8 +277,8 @@ internal class ProductBusinessLogicContractTests
public void GetProductByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_productStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_productStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_productStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _productBusinessLogicContract.GetProductByData("name"), Throws.TypeOf<StorageException>());
@@ -332,7 +309,7 @@ internal class ProductBusinessLogicContractTests
public void InsertProduct_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.AddElement(It.IsAny<ProductDataModel>())).Throws(new ElementExistsException("Data", "Data"));
_productStorageContract.Setup(x => x.AddElement(It.IsAny<ProductDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.InsertProduct(new(Guid.NewGuid().ToString(), "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false)), Throws.TypeOf<ElementExistsException>());
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Once);
@@ -358,7 +335,7 @@ internal class ProductBusinessLogicContractTests
public void InsertProduct_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.AddElement(It.IsAny<ProductDataModel>())).Throws(new StorageException(new InvalidOperationException()));
_productStorageContract.Setup(x => x.AddElement(It.IsAny<ProductDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.InsertProduct(new(Guid.NewGuid().ToString(), "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false)), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Once);
@@ -387,7 +364,7 @@ internal class ProductBusinessLogicContractTests
public void UpdateProduct_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new ElementNotFoundException(""));
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(new(Guid.NewGuid().ToString(), "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false)), Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
@@ -397,7 +374,7 @@ internal class ProductBusinessLogicContractTests
public void UpdateProduct_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new ElementExistsException("Data", "Data"));
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(new(Guid.NewGuid().ToString(), "anme", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false)), Throws.TypeOf<ElementExistsException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
@@ -423,7 +400,7 @@ internal class ProductBusinessLogicContractTests
public void UpdateProduct_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new StorageException(new InvalidOperationException()));
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(new(Guid.NewGuid().ToString(), "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false)), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
@@ -448,7 +425,7 @@ internal class ProductBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
_productStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
_productStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.DeleteProduct(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
@@ -475,7 +452,7 @@ internal class ProductBusinessLogicContractTests
public void DeleteProduct_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_productStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.DeleteProduct(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);

View File

@@ -4,6 +4,7 @@ using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.StoragesContracts;
using CatHasPawsTests.Infrastructure;
using Microsoft.Extensions.Logging;
using Moq;
@@ -29,7 +30,7 @@ internal class ReportContractTests
_baseWordBuilder = new Mock<BaseWordBuilder>();
_baseExcelBuilder = new Mock<BaseExcelBuilder>();
_basePdfBuilder = new Mock<BasePdfBuilder>();
_reportContract = new ReportContract(_productStorageContract.Object, _saleStorageContract.Object, _salaryStorageContract.Object, _baseWordBuilder.Object, _baseExcelBuilder.Object, _basePdfBuilder.Object, new Mock<ILogger>().Object);
_reportContract = new ReportContract(_productStorageContract.Object, _saleStorageContract.Object, _salaryStorageContract.Object, _baseWordBuilder.Object, _baseExcelBuilder.Object, _basePdfBuilder.Object, StringLocalizerMockCreator.GetObject(), new Mock<ILogger>().Object);
}
[SetUp]
@@ -84,7 +85,7 @@ internal class ReportContractTests
public void GetDataProductsByManufacturer_WhenStorageThrowError_ShouldFail_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetListAsync(It.IsAny<CancellationToken>())).Throws(new StorageException(new InvalidOperationException()));
_productStorageContract.Setup(x => x.GetListAsync(It.IsAny<CancellationToken>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(async () => await _reportContract.GetDataProductsByManufacturerAsync(CancellationToken.None), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.GetListAsync(It.IsAny<CancellationToken>()), Times.Once);
@@ -134,7 +135,7 @@ internal class ReportContractTests
public void GetDataBySalesByPeriod_WhenStorageThrowError_ShouldFail_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>())).Throws(new StorageException(new InvalidOperationException()));
_saleStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(async () => await _reportContract.GetDataSaleByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
@@ -202,7 +203,7 @@ internal class ReportContractTests
public void GetDataSalaryByPeriod_WhenStorageThrowError_ShouldFail_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>())).Throws(new StorageException(new InvalidOperationException()));
_salaryStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(async () => await _reportContract.GetDataSalaryByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None), Throws.TypeOf<StorageException>());
_salaryStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
@@ -231,8 +232,8 @@ internal class ReportContractTests
.Callback((int[] widths, List<string[]> data) =>
{
countRows = data.Count;
firstRow = data[0];
secondRow = data[1];
firstRow = data[1];
secondRow = data[2];
})
.Returns(_baseWordBuilder.Object);
//Act
@@ -245,7 +246,7 @@ internal class ReportContractTests
_baseWordBuilder.Verify(x => x.Build(), Times.Once);
Assert.Multiple(() =>
{
Assert.That(countRows, Is.EqualTo(7));
Assert.That(countRows, Is.EqualTo(8));
Assert.That(firstRow, Has.Length.EqualTo(2));
Assert.That(secondRow, Has.Length.EqualTo(2));
});
@@ -277,8 +278,8 @@ internal class ReportContractTests
.Callback((int[] widths, List<string[]> data) =>
{
countRows = data.Count;
firstRow = data[0];
secondRow = data[1];
firstRow = data[1];
secondRow = data[2];
})
.Returns(_baseExcelBuilder.Object);
//Act
@@ -286,7 +287,7 @@ internal class ReportContractTests
//Assert
Assert.Multiple(() =>
{
Assert.That(countRows, Is.EqualTo(5));
Assert.That(countRows, Is.EqualTo(7));
Assert.That(firstRow, Is.Not.EqualTo(default));
Assert.That(secondRow, Is.Not.EqualTo(default));
});
@@ -334,8 +335,8 @@ internal class ReportContractTests
.Callback((string header, List<(string, double)> data) =>
{
countRows = data.Count;
firstRow = data[0];
secondRow = data[1];
firstRow = data.First(x => x.Item1 == worker1.Id);
secondRow = data.First(x => x.Item1 == worker2.Id);
})
.Returns(_basePdfBuilder.Object);
//Act

View File

@@ -28,7 +28,8 @@ internal class SalaryBusinessLogicContractTests
_postStorageContract = new Mock<IPostStorageContract>();
_workerStorageContract = new Mock<IWorkerStorageContract>();
_salaryBusinessLogicContract = new SalaryBusinessLogicContract(_salaryStorageContract.Object,
_saleStorageContract.Object, _postStorageContract.Object, _workerStorageContract.Object, new Mock<ILogger>().Object, _salaryConfigurationTest);
_saleStorageContract.Object, _postStorageContract.Object, _workerStorageContract.Object,
StringLocalizerMockCreator.GetObject(), new Mock<ILogger>().Object, _salaryConfigurationTest);
}
[SetUp]
@@ -85,19 +86,11 @@ internal class SalaryBusinessLogicContractTests
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalaries_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalaries_StorageThrowError_ThrowException_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
@@ -166,19 +159,11 @@ internal class SalaryBusinessLogicContractTests
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalariesByWorker_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), Guid.NewGuid().ToString()), Throws.TypeOf<NullListException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalariesByWorker_StorageThrowError_ThrowException_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
@@ -260,52 +245,13 @@ internal class SalaryBusinessLogicContractTests
Assert.That(sum, Is.EqualTo(rate));
}
[Test]
public void CalculateSalaryByMounth_SaleStorageReturnNull_ThrowException_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, new PostConfiguration() { Rate = 100 }));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
[Test]
public void CalculateSalaryByMounth_PostStorageReturnNull_ThrowException_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, DiscountType.None, false, [])]);
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
[Test]
public void CalculateSalaryByMounth_WorkerStorageReturnNull_ThrowException_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, DiscountType.None, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, new PostConfiguration() { Rate = 100 }));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
[Test]
public void CalculateSalaryByMounth_SaleStorageThrowException_ThrowException_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
.Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, new PostConfiguration() { Rate = 100 }));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
@@ -322,7 +268,7 @@ internal class SalaryBusinessLogicContractTests
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, DiscountType.None, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
.Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
@@ -339,7 +285,7 @@ internal class SalaryBusinessLogicContractTests
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, new PostConfiguration() { Rate = 100 }));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Throws(new StorageException(new InvalidOperationException()));
.Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
}

View File

@@ -3,6 +3,7 @@ using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.StoragesContracts;
using CatHasPawsTests.Infrastructure;
using Microsoft.Extensions.Logging;
using Moq;
@@ -18,7 +19,7 @@ internal class SaleBusinessLogicContractTests
public void OneTimeSetUp()
{
_saleStorageContract = new Mock<ISaleStorageContract>();
_saleBusinessLogicContract = new SaleBusinessLogicContract(_saleStorageContract.Object, new Mock<ILogger>().Object);
_saleBusinessLogicContract = new SaleBusinessLogicContract(_saleStorageContract.Object, StringLocalizerMockCreator.GetObject(), new Mock<ILogger>().Object);
}
[SetUp]
@@ -72,19 +73,11 @@ internal class SaleBusinessLogicContractTests
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
@@ -153,19 +146,11 @@ internal class SaleBusinessLogicContractTests
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByWorkerByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByWorkerByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
@@ -234,19 +219,11 @@ internal class SaleBusinessLogicContractTests
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByBuyerByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByBuyerByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
@@ -315,19 +292,11 @@ internal class SaleBusinessLogicContractTests
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByProductByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByProductByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
@@ -378,7 +347,7 @@ internal class SaleBusinessLogicContractTests
public void GetSaleByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_saleStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetSaleByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
@@ -412,7 +381,7 @@ internal class SaleBusinessLogicContractTests
public void InsertSale_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new ElementExistsException("Data", "Data"));
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), DiscountType.None, false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])), Throws.TypeOf<ElementExistsException>());
@@ -439,7 +408,7 @@ internal class SaleBusinessLogicContractTests
public void InsertSale_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new StorageException(new InvalidOperationException()));
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), DiscountType.None, false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])), Throws.TypeOf<StorageException>());
@@ -465,7 +434,7 @@ internal class SaleBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
_saleStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.CancelSale(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
@@ -492,7 +461,7 @@ internal class SaleBusinessLogicContractTests
public void CancelSale_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_saleStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.CancelSale(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);

View File

@@ -2,6 +2,7 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.StoragesContracts;
using CatHasPawsTests.Infrastructure;
using Microsoft.Extensions.Logging;
using Moq;
@@ -17,7 +18,7 @@ internal class WorkerBusinessLogicContractTests
public void OneTimeSetUp()
{
_workerStorageContract = new Mock<IWorkerStorageContract>();
_workerBusinessLogicContract = new WorkerBusinessLogicContract(_workerStorageContract.Object, new Mock<ILogger>().Object);
_workerBusinessLogicContract = new WorkerBusinessLogicContract(_workerStorageContract.Object, StringLocalizerMockCreator.GetObject(), new Mock<ILogger>().Object);
}
[SetUp]
@@ -71,19 +72,11 @@ internal class WorkerBusinessLogicContractTests
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), null, null, null, null, null), Times.Exactly(2));
}
[Test]
public void GetAllWorkers_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkers(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkers_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkers(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), null, null, null, null, null), Times.Once);
@@ -152,19 +145,11 @@ internal class WorkerBusinessLogicContractTests
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllWorkersByPost_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByPost(Guid.NewGuid().ToString(), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkersByPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByPost(Guid.NewGuid().ToString(), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
@@ -228,19 +213,11 @@ internal class WorkerBusinessLogicContractTests
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllWorkersByBirthDate_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByBirthDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkersByBirthDate_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByBirthDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
@@ -304,19 +281,11 @@ internal class WorkerBusinessLogicContractTests
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllWorkersByEmploymentDate_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkersByEmploymentDate_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
@@ -384,8 +353,8 @@ internal class WorkerBusinessLogicContractTests
public void GetWorkerByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.GetElementByFIO(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_workerStorageContract.Setup(x => x.GetElementByFIO(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData("fio"), Throws.TypeOf<StorageException>());
@@ -416,7 +385,7 @@ internal class WorkerBusinessLogicContractTests
public void InsertWorker_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>())).Throws(new ElementExistsException("Data", "Data"));
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementExistsException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Once);
@@ -442,7 +411,7 @@ internal class WorkerBusinessLogicContractTests
public void InsertWorker_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Once);
@@ -471,7 +440,7 @@ internal class WorkerBusinessLogicContractTests
public void UpdateWorker_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>())).Throws(new ElementNotFoundException(""));
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Once);
@@ -497,7 +466,7 @@ internal class WorkerBusinessLogicContractTests
public void UpdateWorker_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Once);
@@ -522,7 +491,7 @@ internal class WorkerBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
_workerStorageContract.Setup(x => x.DelElement(It.Is((string x) => x != id))).Throws(new ElementNotFoundException(id));
_workerStorageContract.Setup(x => x.DelElement(It.Is((string x) => x != id))).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.DeleteWorker(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
@@ -549,7 +518,7 @@ internal class WorkerBusinessLogicContractTests
public void DeleteWorker_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.DeleteWorker(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);

View File

@@ -1,5 +1,6 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsTests.Infrastructure;
namespace CatHasPawsTests.DataModelsTests;
@@ -10,41 +11,41 @@ internal class BuyerDataModelTests
public void IdIsNullOrEmptyTest()
{
var buyer = CreateDataModel(null, "fio", "number", 10);
Assert.That(() => buyer.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => buyer.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
buyer = CreateDataModel(string.Empty, "fio", "number", 10);
Assert.That(() => buyer.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => buyer.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var buyer = CreateDataModel("id", "fio", "number", 10);
Assert.That(() => buyer.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => buyer.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void FIOIsNullOrEmptyTest()
{
var buyer = CreateDataModel(Guid.NewGuid().ToString(), null, "number", 10);
Assert.That(() => buyer.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => buyer.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
buyer = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, "number", 10);
Assert.That(() => buyer.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => buyer.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void PhoneNumberIsNullOrEmptyTest()
{
var buyer = CreateDataModel(Guid.NewGuid().ToString(), "fio", null, 10);
Assert.That(() => buyer.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => buyer.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
buyer = CreateDataModel(Guid.NewGuid().ToString(), "fio", string.Empty, 10);
Assert.That(() => buyer.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => buyer.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void PhoneNumberIsIncorrectTest()
{
var buyer = CreateDataModel(Guid.NewGuid().ToString(), "fio", "777", 10);
Assert.That(() => buyer.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => buyer.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -55,7 +56,7 @@ internal class BuyerDataModelTests
var phoneNumber = "+7-777-777-77-77";
var discountSize = 11;
var buyer = CreateDataModel(buyerId, fio, phoneNumber, discountSize);
Assert.That(() => buyer.Validate(), Throws.Nothing);
Assert.That(() => buyer.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(buyer.Id, Is.EqualTo(buyerId));

View File

@@ -1,5 +1,6 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsTests.Infrastructure;
namespace CatHasPawsTests.DataModelsTests;
@@ -10,25 +11,25 @@ internal class ManufacturerDataModelTests
public void IdIsNullEmptyTest()
{
var manufacturer = CreateDataModel(null, "name");
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => manufacturer.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
manufacturer = CreateDataModel(string.Empty, "name");
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => manufacturer.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var manufacturer = CreateDataModel("id", "name");
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => manufacturer.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void ManufacturerNameIsNullOrEmptyTest()
{
var manufacturer = CreateDataModel(Guid.NewGuid().ToString(), null);
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => manufacturer.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
manufacturer = CreateDataModel(Guid.NewGuid().ToString(), string.Empty);
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => manufacturer.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -39,7 +40,7 @@ internal class ManufacturerDataModelTests
var prevManufacturerName = "prevManufacturerName";
var prevPrevManufacturerName = "prevPrevManufacturerName";
var manufacturer = CreateDataModel(manufacturerId, manufacturerName, prevManufacturerName, prevPrevManufacturerName);
Assert.That(() => manufacturer.Validate(), Throws.Nothing);
Assert.That(() => manufacturer.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(manufacturer.Id, Is.EqualTo(manufacturerId));

View File

@@ -2,6 +2,7 @@
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Infrastructure.PostConfigurations;
using CatHasPawsTests.Infrastructure;
namespace CatHasPawsTests.DataModelsTests;
@@ -12,39 +13,39 @@ internal class PostDataModelTests
public void IdIsNullOrEmptyTest()
{
var post = CreateDataModel(null, "name", PostType.Assistant, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => post.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
post = CreateDataModel(string.Empty, "name", PostType.Assistant, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => post.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var post = CreateDataModel("id", "name", PostType.Assistant, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => post.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostNameIsEmptyTest()
{
var manufacturer = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Assistant, new PostConfiguration() { Rate = 10 });
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => manufacturer.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
manufacturer = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Assistant, new PostConfiguration() { Rate = 10 });
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => manufacturer.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostTypeIsNoneTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.None, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => post.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void ConfigurationModelIsNullTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, null);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => post.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
@@ -52,9 +53,9 @@ internal class PostDataModelTests
public void RateIsLessOrZeroTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, new PostConfiguration() { Rate = 0 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => post.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, new PostConfiguration() { Rate = -10 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => post.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -65,7 +66,7 @@ internal class PostDataModelTests
var postType = PostType.Assistant;
var configuration = new PostConfiguration() { Rate = 10 };
var post = CreateDataModel(postId, postName, postType, configuration);
Assert.That(() => post.Validate(), Throws.Nothing);
Assert.That(() => post.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(post.Id, Is.EqualTo(postId));
@@ -73,6 +74,7 @@ internal class PostDataModelTests
Assert.That(post.PostType, Is.EqualTo(postType));
Assert.That(post.ConfigurationModel, Is.EqualTo(configuration));
Assert.That(post.ConfigurationModel.Rate, Is.EqualTo(configuration.Rate));
Assert.That(post.ConfigurationModel.CultureName, Is.Not.Empty);
});
}

View File

@@ -1,6 +1,7 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsTests.Infrastructure;
namespace CatHasPawsTests.DataModelsTests;
@@ -11,57 +12,57 @@ internal class ProductDataModelTests
public void IdIsNullOrEmptyTest()
{
var product = CreateDataModel(null, "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
product = CreateDataModel(string.Empty, "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var product = CreateDataModel("id", "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductNameIsEmptyTest()
{
var product = CreateDataModel(Guid.NewGuid().ToString(), null, ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
product = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductTypeIsNoneTest()
{
var product = CreateDataModel(Guid.NewGuid().ToString(), null, ProductType.None, Guid.NewGuid().ToString(), 10, false);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void ManufacturerIdIsNullOrEmptyTest()
{
var product = CreateDataModel(Guid.NewGuid().ToString(), "name", ProductType.Accessory, null, 10, false);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
product = CreateDataModel(Guid.NewGuid().ToString(), "name", ProductType.Accessory, string.Empty, 10, false);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void ManufacturerIdIsNotGuidTest()
{
var product = CreateDataModel(Guid.NewGuid().ToString(), "name", ProductType.Accessory, "manufacturerId", 10, false);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void PriceIsLessOrZeroTest()
{
var product = CreateDataModel(Guid.NewGuid().ToString(), "name", ProductType.Accessory, Guid.NewGuid().ToString(), 0, false);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
product = CreateDataModel(Guid.NewGuid().ToString(), "name", ProductType.Accessory, Guid.NewGuid().ToString(), -10, false);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -74,7 +75,7 @@ internal class ProductDataModelTests
var productPrice = 10;
var productIsDelete = false;
var product = CreateDataModel(productId, productName, productType, productManufacturerId, productPrice, productIsDelete);
Assert.That(() => product.Validate(), Throws.Nothing);
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(product.Id, Is.EqualTo(productId));

View File

@@ -1,5 +1,6 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsTests.Infrastructure;
namespace CatHasPawsTests.DataModelsTests;
@@ -10,25 +11,25 @@ internal class ProductHistoryDataModelTests
public void ProductIdIsNullOrEmptyTest()
{
var product = CreateDataModel(null, 10);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
product = CreateDataModel(string.Empty, 10);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductIdIsNotGuidTest()
{
var product = CreateDataModel("id", 10);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void OldPriceIsLessOrZeroTest()
{
var product = CreateDataModel(Guid.NewGuid().ToString(), 0);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
product = CreateDataModel(Guid.NewGuid().ToString(), -10);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -37,7 +38,7 @@ internal class ProductHistoryDataModelTests
var productId = Guid.NewGuid().ToString();
var oldPrice = 10;
var productHistory = CreateDataModel(productId, oldPrice);
Assert.That(() => productHistory.Validate(), Throws.Nothing);
Assert.That(() => productHistory.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(productHistory.ProductId, Is.EqualTo(productId));

View File

@@ -1,5 +1,6 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsTests.Infrastructure;
namespace CatHasPawsTests.DataModelsTests;
@@ -10,25 +11,25 @@ internal class SalaryDataModelTests
public void WorkerIdIsEmptyTest()
{
var salary = CreateDataModel(null, DateTime.Now, 10);
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => salary.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
salary = CreateDataModel(string.Empty, DateTime.Now, 10);
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => salary.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void WorkerIdIsNotGuidTest()
{
var salary = CreateDataModel("workerId", DateTime.Now, 10);
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => salary.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void PriceIsLessOrZeroTest()
{
var salary = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0);
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => salary.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
salary = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now, -10);
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => salary.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -38,11 +39,11 @@ internal class SalaryDataModelTests
var salaryDate = DateTime.Now.AddDays(-3).AddMinutes(-5);
var workerSalary = 10;
var salary = CreateDataModel(workerId, salaryDate, workerSalary);
Assert.That(() => salary.Validate(), Throws.Nothing);
Assert.That(() => salary.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(salary.WorkerId, Is.EqualTo(workerId));
Assert.That(salary.SalaryDate, Is.EqualTo(salaryDate));
Assert.That(salary.SalaryDate, Is.EqualTo(salaryDate.ToUniversalTime()));
Assert.That(salary.Salary, Is.EqualTo(workerSalary));
});
}

View File

@@ -1,6 +1,7 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsTests.Infrastructure;
namespace CatHasPawsTests.DataModelsTests;
@@ -11,47 +12,47 @@ internal class SaleDataModelTests
public void IdIsNullOrEmptyTest()
{
var sale = CreateDataModel(null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
sale = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var sale = CreateDataModel("id", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void WorkerIdIsNullOrEmptyTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), null, Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
sale = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void WorkerIdIsNotGuidTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), "workerId", Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void BuyerIdIsNotGuidTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "buyerId", DiscountType.OnSale, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductsIsNullOrEmptyTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.OnSale, false, null);
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.OnSale, false, []);
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -109,7 +110,7 @@ internal class SaleDataModelTests
var isCancel = true;
var products = CreateSubDataModel();
var sale = CreateDataModel(saleId, workerId, buyerId, discountType, isCancel, products);
Assert.That(() => sale.Validate(), Throws.Nothing);
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(sale.Id, Is.EqualTo(saleId));

View File

@@ -1,5 +1,6 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsTests.Infrastructure;
namespace CatHasPawsTests.DataModelsTests;
@@ -10,50 +11,50 @@ internal class SaleProductDataModelTests
public void SaleIdIsNullOrEmptyTest()
{
var saleProduct = CreateDataModel(null, Guid.NewGuid().ToString(), 10, 1.1);
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => saleProduct.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
saleProduct = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10, 1.1);
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => saleProduct.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void SaleIdIsNotGuidTest()
{
var saleProduct = CreateDataModel("saleId", Guid.NewGuid().ToString(), 10, 1.1);
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => saleProduct.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductIdIsNullOrEmptyTest()
{
var saleProduct = CreateDataModel(Guid.NewGuid().ToString(), null, 10, 1.1);
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => saleProduct.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
saleProduct = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10, 1.1);
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => saleProduct.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductIdIsNotGuidTest()
{
var saleProduct = CreateDataModel(Guid.NewGuid().ToString(), "productId", 10, 1.1);
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => saleProduct.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void CountIsLessOrZeroTest()
{
var saleProduct = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0, 1.1);
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => saleProduct.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
saleProduct = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -10, 1.1);
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => saleProduct.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void PriceIsLessOrZeroTest()
{
var saleProduct = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 0);
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => saleProduct.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
saleProduct = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, -10);
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => saleProduct.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -64,7 +65,7 @@ internal class SaleProductDataModelTests
var count = 10;
var price = 1.2;
var saleProduct = CreateDataModel(saleId, productId, count, price);
Assert.That(() => saleProduct.Validate(), Throws.Nothing);
Assert.That(() => saleProduct.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(saleProduct.SaleId, Is.EqualTo(saleId));

View File

@@ -1,5 +1,6 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsTests.Infrastructure;
namespace CatHasPawsTests.DataModelsTests;
@@ -10,57 +11,57 @@ internal class WorkerDataModelTests
public void IdIsNullOrEmptyTest()
{
var worker = CreateDataModel(null, "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
worker = CreateDataModel(string.Empty, "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var worker = CreateDataModel("id", "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void FIOIsNullOrEmptyTest()
{
var worker = CreateDataModel(Guid.NewGuid().ToString(), null, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
worker = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostIdIsNullOrEmptyTest()
{
var worker = CreateDataModel(Guid.NewGuid().ToString(), "fio", null, DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
worker = CreateDataModel(Guid.NewGuid().ToString(), "fio", string.Empty, DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostIdIsNotGuidTest()
{
var worker = CreateDataModel(Guid.NewGuid().ToString(), "fio", "postId", DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void BirthDateIsNotCorrectTest()
{
var worker = CreateDataModel(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(1), DateTime.Now, false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void BirthDateAndEmploymentDateIsNotCorrectTest()
{
var worker = CreateDataModel(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now.AddYears(-18).AddDays(-1), false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
worker = CreateDataModel(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now.AddYears(-16), false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -73,14 +74,14 @@ internal class WorkerDataModelTests
var employmentDate = DateTime.Now;
var isDelete = false;
var worker = CreateDataModel(workerId, fio, postId, birthDate, employmentDate, isDelete);
Assert.That(() => worker.Validate(), Throws.Nothing);
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(worker.Id, Is.EqualTo(workerId));
Assert.That(worker.FIO, Is.EqualTo(fio));
Assert.That(worker.PostId, Is.EqualTo(postId));
Assert.That(worker.BirthDate, Is.EqualTo(birthDate));
Assert.That(worker.EmploymentDate, Is.EqualTo(employmentDate));
Assert.That(worker.BirthDate, Is.EqualTo(birthDate.ToUniversalTime()));
Assert.That(worker.EmploymentDate, Is.EqualTo(employmentDate.ToUniversalTime()));
Assert.That(worker.IsDeleted, Is.EqualTo(isDelete));
});
}

View File

@@ -0,0 +1,20 @@
using CatHasPawsContratcs.Resources;
using Microsoft.Extensions.Localization;
using Moq;
namespace CatHasPawsTests.Infrastructure;
internal static class StringLocalizerMockCreator
{
private static Mock<IStringLocalizer<Messages>>? _mockObject = null;
public static IStringLocalizer<Messages> GetObject()
{
if (_mockObject is null)
{
_mockObject = new Mock<IStringLocalizer<Messages>>();
_mockObject.Setup(_ => _[It.IsAny<string>()]).Returns(new LocalizedString("name", "value"));
}
return _mockObject!.Object;
}
}

View File

@@ -0,0 +1,299 @@
using CatHasPawsContratcs.BindingModels;
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Infrastructure.PostConfigurations;
using CatHasPawsDatabase;
using CatHasPawsTests.Infrastructure;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using Serilog;
using System.Net;
using System.Text;
using System.Text.Json;
namespace CatHasPawsTests.LocalizationTests;
internal abstract class BaseLocalizationControllerTest
{
protected abstract string GetLocale();
private WebApplicationFactory<Program> _webApplication;
protected HttpClient HttpClient { get; private set; }
protected static CatHasPawsDbContext CatHasPawsDbContext { get; private set; }
protected static readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNameCaseInsensitive = true };
private static string _manufacturerId;
private static string _buyerId;
private static string _workerId;
private static string _productId;
private static string _postId;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_webApplication = new CustomWebApplicationFactory<Program>();
HttpClient = _webApplication
.WithWebHostBuilder(builder =>
{
builder.ConfigureTestServices(services =>
{
using var loggerFactory = new LoggerFactory();
loggerFactory.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build())
.CreateLogger());
services.AddSingleton(loggerFactory);
});
})
.CreateClient();
var request = HttpClient.GetAsync("/login/user").GetAwaiter().GetResult();
var data = request.Content.ReadAsStringAsync().GetAwaiter().GetResult();
HttpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {data}");
HttpClient.DefaultRequestHeaders.Add("Accept-Language", GetLocale());
CatHasPawsDbContext = _webApplication.Services.GetRequiredService<CatHasPawsDbContext>();
CatHasPawsDbContext.Database.EnsureDeleted();
CatHasPawsDbContext.Database.EnsureCreated();
}
[SetUp]
public void SetUp()
{
_buyerId = CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn(fio: "Buyer", phoneNumber: "+6-666-666-66-66").Id;
_workerId = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "Worker").Id;
_manufacturerId = CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerName: "Manufacturer").Id;
_productId = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productName: "Product").Id;
_postId = CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postName: "Post").PostId;
}
[TearDown]
public void TearDown()
{
CatHasPawsDbContext.RemoveSalariesFromDatabase();
CatHasPawsDbContext.RemoveSalesFromDatabase();
CatHasPawsDbContext.RemoveWorkersFromDatabase();
CatHasPawsDbContext.RemovePostsFromDatabase();
CatHasPawsDbContext.RemoveBuyersFromDatabase();
CatHasPawsDbContext.RemoveProductsFromDatabase();
CatHasPawsDbContext.RemoveManufacturersFromDatabase();
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
CatHasPawsDbContext?.Database.EnsureDeleted();
CatHasPawsDbContext?.Dispose();
HttpClient?.Dispose();
_webApplication?.Dispose();
}
[Test]
public async Task LoadProducts_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var manufacturer1 = CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerName: "name 1");
var manufacturer2 = CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerName: "name 2");
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(manufacturer1.Id, productName: "name 1.1");
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(manufacturer1.Id, productName: "name 1.2");
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(manufacturer1.Id, productName: "name 1.3");
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(manufacturer2.Id, productName: "name 2.1");
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(manufacturer2.Id, productName: "name 2.2");
//Act
var response = await HttpClient.GetAsync("/api/report/LoadProducts");
//Assert
await AssertStreamAsync(response, $"file-{GetLocale()}.docx");
}
[Test]
public async Task LoadSales_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var worker = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn();
var manufacturerId = CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn();
var product1 = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(manufacturerId.Id, productName: "name 1");
var product2 = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(manufacturerId.Id, productName: "name 2");
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(worker.Id, products: [(product1.Id, 10, 1.1), (product2.Id, 10, 1.1)]);
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(worker.Id, products: [(product1.Id, 10, 1.1)]);
//Act
var response = await HttpClient.GetAsync($"/api/report/loadsales?fromDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
await AssertStreamAsync(response, $"file-{GetLocale()}.xlsx");
}
[Test]
public async Task LoadSalary_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var post = CatHasPawsDbContext.InsertPostToDatabaseAndReturn();
var worker1 = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: post.PostId).AddPost(post);
var worker2 = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: post.PostId).AddPost(post);
CatHasPawsDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, workerSalary: 100, salaryDate: DateTime.UtcNow.AddDays(-10));
CatHasPawsDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, workerSalary: 1000, salaryDate: DateTime.UtcNow.AddDays(-5));
CatHasPawsDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, workerSalary: 200, salaryDate: DateTime.UtcNow.AddDays(5));
CatHasPawsDbContext.InsertSalaryToDatabaseAndReturn(worker2.Id, workerSalary: 500, salaryDate: DateTime.UtcNow.AddDays(-5));
CatHasPawsDbContext.InsertSalaryToDatabaseAndReturn(worker2.Id, workerSalary: 300, salaryDate: DateTime.UtcNow.AddDays(-3));
//Act
var response = await HttpClient.GetAsync($"/api/report/loadsalary?fromDate={DateTime.Now.AddDays(-7):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
//Assert
await AssertStreamAsync(response, $"file-{GetLocale()}.pdf");
}
private static async Task AssertStreamAsync(HttpResponseMessage response, string fileNameForSave = "")
{
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
using var data = await response.Content.ReadAsStreamAsync();
Assert.That(data, Is.Not.Null);
Assert.That(data.Length, Is.GreaterThan(0));
await SaveStreamAsync(data, fileNameForSave);
}
private static async Task SaveStreamAsync(Stream stream, string fileName)
{
if (string.IsNullOrEmpty(fileName))
{
return;
}
var path = Path.Combine(Directory.GetCurrentDirectory(), fileName);
if (File.Exists(path))
{
File.Delete(path);
}
stream.Position = 0;
using var fileStream = new FileStream(path, FileMode.OpenOrCreate);
await stream.CopyToAsync(fileStream);
}
protected abstract string MessageElementNotFound();
[TestCase("buyers")]
[TestCase("manufacturers")]
[TestCase("posts")]
[TestCase("products/getrecord")]
[TestCase("sales/getrecord")]
[TestCase("workers/getrecord")]
public async Task Api_GetElement_NotFound_Test(string path)
{
//Act
var response = await HttpClient.GetAsync($"/api/{path}/{Guid.NewGuid()}");
//Assert
Assert.That(JToken.Parse(await response.Content.ReadAsStringAsync()).ToString(), Does.StartWith(MessageElementNotFound()));
}
private static IEnumerable<TestCaseData> TestDataElementExists()
{
yield return new TestCaseData(() => {
var model = CreateBuyerBindingModel();
CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn(model.Id);
return model;
}, "buyers");
yield return new TestCaseData(() => {
var model = CreateManufacturerModel();
CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn(model.Id);
return model;
}, "manufacturers");
yield return new TestCaseData(() => {
var model = CreatePostModel();
CatHasPawsDbContext.InsertPostToDatabaseAndReturn(model.Id);
return model;
}, "posts");
yield return new TestCaseData(() => {
var model = CreateProductModel(_manufacturerId);
CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, model.Id);
return model;
}, "products/register");
yield return new TestCaseData(() => {
var model = CreateWorkerModel(_manufacturerId);
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(model.Id, postId: _postId);
return model;
}, "workers/register");
}
protected abstract string MessageElementExists();
[TestCaseSource(nameof(TestDataElementExists))]
public async Task Api_Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test(Func<object> createModel, string path)
{
//Arrange
var model = createModel();
//Act
var response = await HttpClient.PostAsync($"/api/{path}", MakeContent(model));
//Assert
Assert.That(JToken.Parse(await response.Content.ReadAsStringAsync()).ToString(), Does.StartWith(MessageElementExists()));
}
private static async Task<T?> GetModelFromResponseAsync<T>(HttpResponseMessage response) =>
JsonSerializer.Deserialize<T>(await response.Content.ReadAsStringAsync(), JsonSerializerOptions);
private static StringContent MakeContent(object model) =>
new(JsonSerializer.Serialize(model), Encoding.UTF8, "application/json");
private static BuyerBindingModel CreateBuyerBindingModel(string? id = null, string fio = "fio", string phoneNumber = "+7-666-666-66-66", double discountSize = 10) =>
new()
{
Id = id ?? Guid.NewGuid().ToString(),
FIO = fio,
PhoneNumber = phoneNumber,
DiscountSize = discountSize
};
private static ManufacturerBindingModel CreateManufacturerModel(string? id = null, string manufacturerName = "name")
=> new()
{
Id = id ?? Guid.NewGuid().ToString(),
ManufacturerName = manufacturerName
};
private static PostBindingModel CreatePostModel(string? postId = null, string postName = "name", PostType postType = PostType.Assistant, string? configuration = null)
=> new()
{
Id = postId ?? Guid.NewGuid().ToString(),
PostName = postName,
PostType = postType.ToString(),
ConfigurationJson = configuration ?? JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 })
};
private static ProductBindingModel CreateProductModel(string manufacturerId, string? id = null, string productName = "name", ProductType productType = ProductType.Feed, double price = 1)
=> new()
{
Id = id ?? Guid.NewGuid().ToString(),
ManufacturerId = manufacturerId,
ProductName = productName,
ProductType = productType.ToString(),
Price = price
};
private static SaleBindingModel CreateSaleModel(string workerId, string? buyerId, string productId, string? id = null, DiscountType discountType = DiscountType.OnSale, int count = 1, double price = 1.1)
{
var saleId = id ?? Guid.NewGuid().ToString();
return new()
{
Id = saleId,
WorkerId = workerId,
BuyerId = buyerId,
DiscountType = (int)discountType,
Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = productId, Count = count, Price = price }]
};
}
private static WorkerBindingModel CreateWorkerModel(string postId, string? id = null, string fio = "fio", DateTime? birthDate = null, DateTime? employmentDate = null)
{
return new()
{
Id = id ?? Guid.NewGuid().ToString(),
FIO = fio,
BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-22),
EmploymentDate = employmentDate ?? DateTime.UtcNow.AddDays(-5),
PostId = postId
};
}
}

View File

@@ -0,0 +1,12 @@
namespace CatHasPawsTests.LocalizationTests;
[TestFixture]
internal class DefaultTests : BaseLocalizationControllerTest
{
protected override string GetLocale() => "bla-BLA";
protected override string MessageElementExists() => "Уже существует элемент со значением";
protected override string MessageElementNotFound() => "Не найден элемент по данным";
}

View File

@@ -0,0 +1,11 @@
namespace CatHasPawsTests.LocalizationTests;
[TestFixture]
internal class EnUSTests : BaseLocalizationControllerTest
{
protected override string GetLocale() => "en-US";
protected override string MessageElementExists() => "There is already an element with value";
protected override string MessageElementNotFound() => "Not found element by data";
}

View File

@@ -0,0 +1,11 @@
namespace CatHasPawsTests.LocalizationTests;
[TestFixture]
internal class RuRUTests : BaseLocalizationControllerTest
{
protected override string GetLocale() => "ru-RU";
protected override string MessageElementExists() => "Уже существует элемент со значением";
protected override string MessageElementNotFound() => "Не найден элемент по данным";
}

View File

@@ -14,7 +14,7 @@ internal class BuyerStorageContractTests : BaseStorageContractTest
[SetUp]
public void SetUp()
{
_buyerStorageContract = new BuyerStorageContract(CatHasPawsDbContext);
_buyerStorageContract = new BuyerStorageContract(CatHasPawsDbContext, StringLocalizerMockCreator.GetObject());
}
[TearDown]

View File

@@ -15,7 +15,7 @@ internal class ManufacturerStorageContractTests : BaseStorageContractTest
[SetUp]
public void SetUp()
{
_manufacturerStorageContract = new ManufacturerStorageContract(CatHasPawsDbContext);
_manufacturerStorageContract = new ManufacturerStorageContract(CatHasPawsDbContext, StringLocalizerMockCreator.GetObject());
}
[TearDown]

View File

@@ -16,7 +16,7 @@ internal class PostStorageContractTests : BaseStorageContractTest
[SetUp]
public void SetUp()
{
_postStorageContract = new PostStorageContract(CatHasPawsDbContext);
_postStorageContract = new PostStorageContract(CatHasPawsDbContext, StringLocalizerMockCreator.GetObject());
}
[TearDown]

View File

@@ -16,7 +16,7 @@ internal class ProductStorageContractTests : BaseStorageContractTest
[SetUp]
public void SetUp()
{
_productStorageContract = new ProductStorageContract(CatHasPawsDbContext);
_productStorageContract = new ProductStorageContract(CatHasPawsDbContext, StringLocalizerMockCreator.GetObject());
_manufacturer = CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn();
}

View File

@@ -15,7 +15,7 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
[SetUp]
public void SetUp()
{
_salaryStorageContract = new SalaryStorageContract(CatHasPawsDbContext);
_salaryStorageContract = new SalaryStorageContract(CatHasPawsDbContext, StringLocalizerMockCreator.GetObject());
_worker = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn();
}

View File

@@ -19,7 +19,7 @@ internal class SaleStorageContractTests : BaseStorageContractTest
[SetUp]
public void SetUp()
{
_saletStorageContract = new SaleStorageContract(CatHasPawsDbContext);
_saletStorageContract = new SaleStorageContract(CatHasPawsDbContext, StringLocalizerMockCreator.GetObject());
_manufacturer = CatHasPawsDbContext.InsertManufacturerToDatabaseAndReturn();
_buyer = CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn();
_worker = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn();

View File

@@ -14,7 +14,7 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
[SetUp]
public void SetUp()
{
_workerStorageContract = new WorkerStorageContract(CatHasPawsDbContext);
_workerStorageContract = new WorkerStorageContract(CatHasPawsDbContext, StringLocalizerMockCreator.GetObject());
}
[TearDown]

View File

@@ -303,7 +303,7 @@ internal class ManufacturerControllerTests : BaseWebApiControllerTest
//Act
var response = await HttpClient.DeleteAsync($"/api/manufacturers/{manufacturerId}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.InternalServerError));
}
[Test]

View File

@@ -506,7 +506,7 @@ internal class ProductControllerTests : BaseWebApiControllerTest
{
Assert.That(actual.ProductName, Is.EqualTo(expected.Product!.ProductName));
Assert.That(actual.OldPrice, Is.EqualTo(expected.OldPrice));
Assert.That(actual.ChangeDate.ToString(), Is.EqualTo(expected.ChangeDate.ToString()));
Assert.That(actual.ChangeDate.ToUniversalTime().ToString(), Is.EqualTo(expected.ChangeDate.ToString()));
});
}

View File

@@ -55,7 +55,7 @@ internal class ReportControllerTests : BaseWebApiControllerTest
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(worker.Id, products: [(product1.Id, 10, 1.1), (product2.Id, 10, 1.1)]);
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(worker.Id, products: [(product1.Id, 10, 1.1)]);
//Act
var response = await HttpClient.GetAsync($"/api/report/getsales?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
var response = await HttpClient.GetAsync($"/api/report/getsales?fromDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
@@ -70,7 +70,7 @@ internal class ReportControllerTests : BaseWebApiControllerTest
public async Task GetSales_WhenDateIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/report/getsales?fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
var response = await HttpClient.GetAsync($"/api/report/getsales?fromDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
@@ -88,7 +88,7 @@ internal class ReportControllerTests : BaseWebApiControllerTest
CatHasPawsDbContext.InsertSalaryToDatabaseAndReturn(worker2.Id, workerSalary: 500, salaryDate: DateTime.UtcNow.AddDays(-5));
CatHasPawsDbContext.InsertSalaryToDatabaseAndReturn(worker2.Id, workerSalary: 300, salaryDate: DateTime.UtcNow.AddDays(-3));
//Act
var response = await HttpClient.GetAsync($"/api/report/getsalary?fromDate={DateTime.UtcNow.AddDays(-7):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
var response = await HttpClient.GetAsync($"/api/report/getsalary?fromDate={DateTime.Now.AddDays(-7):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<WorkerSalaryByPeriodViewModel>>(response);
@@ -105,7 +105,7 @@ internal class ReportControllerTests : BaseWebApiControllerTest
public async Task GetSalary_WhenDateIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/report/getsalary?fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
var response = await HttpClient.GetAsync($"/api/report/getsalary?fromDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
@@ -139,7 +139,7 @@ internal class ReportControllerTests : BaseWebApiControllerTest
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(worker.Id, products: [(product1.Id, 10, 1.1), (product2.Id, 10, 1.1)]);
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(worker.Id, products: [(product1.Id, 10, 1.1)]);
//Act
var response = await HttpClient.GetAsync($"/api/report/loadsales?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
var response = await HttpClient.GetAsync($"/api/report/loadsales?fromDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
await AssertStreamAsync(response, "file.xlsx");
}
@@ -148,7 +148,7 @@ internal class ReportControllerTests : BaseWebApiControllerTest
public async Task LoadSales_WhenDateIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/report/loadsales?fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
var response = await HttpClient.GetAsync($"/api/report/loadsales?fromDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
@@ -166,7 +166,7 @@ internal class ReportControllerTests : BaseWebApiControllerTest
CatHasPawsDbContext.InsertSalaryToDatabaseAndReturn(worker2.Id, workerSalary: 500, salaryDate: DateTime.UtcNow.AddDays(-5));
CatHasPawsDbContext.InsertSalaryToDatabaseAndReturn(worker2.Id, workerSalary: 300, salaryDate: DateTime.UtcNow.AddDays(-3));
//Act
var response = await HttpClient.GetAsync($"/api/report/loadsalary?fromDate={DateTime.UtcNow.AddDays(-7):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
var response = await HttpClient.GetAsync($"/api/report/loadsalary?fromDate={DateTime.Now.AddDays(-7):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
//Assert
await AssertStreamAsync(response, "file.pdf");
}
@@ -175,7 +175,7 @@ internal class ReportControllerTests : BaseWebApiControllerTest
public async Task LoadSalary_WhenDateIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/report/loadsalary?fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
var response = await HttpClient.GetAsync($"/api/report/loadsalary?fromDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}

View File

@@ -42,7 +42,7 @@ internal class SaleControllerTests : BaseWebApiControllerTest
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, products: [(_productId, 10, 1.1)]);
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, products: [(_productId, 10, 1.1)]);
//Act
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
@@ -58,7 +58,7 @@ internal class SaleControllerTests : BaseWebApiControllerTest
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
@@ -78,7 +78,7 @@ internal class SaleControllerTests : BaseWebApiControllerTest
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_productId, 1, 1.1)]);
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(3), products: [(_productId, 1, 1.1)]);
//Act
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
@@ -93,7 +93,7 @@ internal class SaleControllerTests : BaseWebApiControllerTest
public async Task GetList_ByPeriod_WhenDateIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
@@ -107,7 +107,7 @@ internal class SaleControllerTests : BaseWebApiControllerTest
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, products: [(_productId, 1, 1.1)]);
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(worker.Id, null, products: [(_productId, 1, 1.1)]);
//Act
var response = await HttpClient.GetAsync($"/api/sales/getworkerrecords?id={_workerId}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
var response = await HttpClient.GetAsync($"/api/sales/getworkerrecords?id={_workerId}&fromDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
@@ -126,7 +126,7 @@ internal class SaleControllerTests : BaseWebApiControllerTest
var worker = CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "Other worker");
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, products: [(_productId, 1, 1.1)]);
//Act
var response = await HttpClient.GetAsync($"/api/sales/getworkerrecords?id={worker.Id}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
var response = await HttpClient.GetAsync($"/api/sales/getworkerrecords?id={worker.Id}&fromDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
@@ -138,7 +138,7 @@ internal class SaleControllerTests : BaseWebApiControllerTest
public async Task GetList_ByWorkerId_WhenDateIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/sales/getworkerrecords?id={_workerId}&fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
var response = await HttpClient.GetAsync($"/api/sales/getworkerrecords?id={_workerId}&fromDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
@@ -147,7 +147,7 @@ internal class SaleControllerTests : BaseWebApiControllerTest
public async Task GetList_ByWorkerId_WhenIdIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/sales/getworkerrecords?id=Id&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
var response = await HttpClient.GetAsync($"/api/sales/getworkerrecords?id=Id&fromDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
@@ -162,7 +162,7 @@ internal class SaleControllerTests : BaseWebApiControllerTest
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, buyer.Id, products: [(_productId, 1, 1.1)]);
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, null, products: [(_productId, 1, 1.1)]);
//Act
var response = await HttpClient.GetAsync($"/api/sales/getbuyerrecords?id={_buyerId}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
var response = await HttpClient.GetAsync($"/api/sales/getbuyerrecords?id={_buyerId}&fromDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
@@ -181,7 +181,7 @@ internal class SaleControllerTests : BaseWebApiControllerTest
var buyer = CatHasPawsDbContext.InsertBuyerToDatabaseAndReturn(fio: "Other buyer", phoneNumber: "+8-888-888-88-88");
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, products: [(_productId, 1, 1.1)]);
//Act
var response = await HttpClient.GetAsync($"/api/sales/getbuyerrecords?id={buyer.Id}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
var response = await HttpClient.GetAsync($"/api/sales/getbuyerrecords?id={buyer.Id}&fromDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
@@ -193,7 +193,7 @@ internal class SaleControllerTests : BaseWebApiControllerTest
public async Task GetList_ByBuyerId_WhenDateIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/sales/getbuyerrecords?id={_buyerId}&fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
var response = await HttpClient.GetAsync($"/api/sales/getbuyerrecords?id={_buyerId}&fromDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
@@ -202,7 +202,7 @@ internal class SaleControllerTests : BaseWebApiControllerTest
public async Task GetList_ByBuyerId_WhenIdIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/sales/getbuyerrecords?id=Id&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
var response = await HttpClient.GetAsync($"/api/sales/getbuyerrecords?id=Id&fromDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
@@ -217,7 +217,7 @@ internal class SaleControllerTests : BaseWebApiControllerTest
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, null, products: [(product.Id, 1, 1.1)]);
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, null, products: [(product.Id, 1, 1.1), (_productId, 1, 1.1)]);
//Act
var response = await HttpClient.GetAsync($"/api/sales/getproductrecords?id={_productId}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
var response = await HttpClient.GetAsync($"/api/sales/getproductrecords?id={_productId}&fromDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
@@ -236,7 +236,7 @@ internal class SaleControllerTests : BaseWebApiControllerTest
var product = CatHasPawsDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productName: "Other product");
CatHasPawsDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, products: [(_productId, 1, 1.1)]);
//Act
var response = await HttpClient.GetAsync($"/api/sales/getproductrecords?id={product.Id}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
var response = await HttpClient.GetAsync($"/api/sales/getproductrecords?id={product.Id}&fromDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
@@ -248,7 +248,7 @@ internal class SaleControllerTests : BaseWebApiControllerTest
public async Task GetList_ByProductId_WhenDateIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/sales/getproductrecords?id={_productId}&fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
var response = await HttpClient.GetAsync($"/api/sales/getproductrecords?id={_productId}&fromDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
@@ -257,7 +257,7 @@ internal class SaleControllerTests : BaseWebApiControllerTest
public async Task GetList_ByProductId_WhenIdIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/sales/getproductrecords?id=Id&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
var response = await HttpClient.GetAsync($"/api/sales/getproductrecords?id=Id&fromDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}

View File

@@ -155,7 +155,7 @@ internal class WorkerControllerTests : BaseWebApiControllerTest
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", birthDate: DateTime.UtcNow.AddYears(-20), isDeleted: true);
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", birthDate: DateTime.UtcNow.AddYears(-19));
//Act
var response = await HttpClient.GetAsync($"/api/workers/getbirthdaterecords?fromDate={DateTime.UtcNow.AddYears(-21).AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddYears(-20).AddMinutes(1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true");
var response = await HttpClient.GetAsync($"/api/workers/getbirthdaterecords?fromDate={DateTime.Now.AddYears(-21).AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddYears(-20).AddMinutes(1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(response);
@@ -170,7 +170,7 @@ internal class WorkerControllerTests : BaseWebApiControllerTest
public async Task GetList_ByBirthDate_WhenDateIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/workers/getbirthdaterecords?fromDate={DateTime.UtcNow.AddMinutes(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true");
var response = await HttpClient.GetAsync($"/api/workers/getbirthdaterecords?fromDate={DateTime.Now.AddMinutes(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
@@ -184,7 +184,7 @@ internal class WorkerControllerTests : BaseWebApiControllerTest
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", employmentDate: DateTime.UtcNow.AddDays(1), isDeleted: true);
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", employmentDate: DateTime.UtcNow.AddDays(2));
//Act
var response = await HttpClient.GetAsync($"/api/workers/getemploymentrecords?fromDate={DateTime.UtcNow.AddDays(-1).AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1).AddMinutes(1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true");
var response = await HttpClient.GetAsync($"/api/workers/getemploymentrecords?fromDate={DateTime.Now.AddDays(-1).AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(1).AddMinutes(1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(response);
@@ -199,7 +199,7 @@ internal class WorkerControllerTests : BaseWebApiControllerTest
public async Task GetList_ByEmploymentDate_WhenDateIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/workers/getemploymentrecords?fromDate={DateTime.UtcNow.AddMinutes(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true");
var response = await HttpClient.GetAsync($"/api/workers/getemploymentrecords?fromDate={DateTime.Now.AddMinutes(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
@@ -474,8 +474,8 @@ internal class WorkerControllerTests : BaseWebApiControllerTest
Assert.That(actual.PostId, Is.EqualTo(expected.PostId));
Assert.That(actual.PostName, Is.EqualTo(expected.Post!.PostName));
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
Assert.That(actual.BirthDate.ToString(), Is.EqualTo(expected.BirthDate.ToString()));
Assert.That(actual.EmploymentDate.ToString(), Is.EqualTo(expected.EmploymentDate.ToString()));
Assert.That(actual.BirthDate.ToUniversalTime().ToString(), Is.EqualTo(expected.BirthDate.ToString()));
Assert.That(actual.EmploymentDate.ToUniversalTime().ToString(), Is.EqualTo(expected.EmploymentDate.ToString()));
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
});
}

View File

@@ -1,49 +1,34 @@
using AutoMapper;
using CatHasPawsContratcs.AdapterContracts;
using CatHasPawsContratcs.AdapterContracts;
using CatHasPawsContratcs.AdapterContracts.OperationResponses;
using CatHasPawsContratcs.BindingModels;
using CatHasPawsContratcs.BusinessLogicsContracts;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Mapper;
using CatHasPawsContratcs.Resources;
using CatHasPawsContratcs.ViewModels;
using Microsoft.Extensions.Localization;
namespace CatHasPawsWebApi.Adapters;
public class BuyerAdapter : IBuyerAdapter
internal class BuyerAdapter(IBuyerBusinessLogicContract buyerBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<BuyerAdapter> logger) : IBuyerAdapter
{
private readonly IBuyerBusinessLogicContract _buyerBusinessLogicContract;
private readonly IBuyerBusinessLogicContract _buyerBusinessLogicContract = buyerBusinessLogicContract;
private readonly ILogger _logger;
private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly Mapper _mapper;
public BuyerAdapter(IBuyerBusinessLogicContract buyerBusinessLogicContract, ILogger<BuyerAdapter> logger)
{
_buyerBusinessLogicContract = buyerBusinessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<BuyerBindingModel, BuyerDataModel>();
cfg.CreateMap<BuyerDataModel, BuyerViewModel>();
});
_mapper = new Mapper(config);
}
private readonly ILogger _logger = logger;
public BuyerOperationResponse GetList()
{
try
{
return BuyerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllBuyers().Select(x => _mapper.Map<BuyerViewModel>(x))]);
}
catch (NullListException)
{
_logger.LogError("NullListException");
return BuyerOperationResponse.NotFound("The list is not initialized");
return BuyerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllBuyers().Select(x => CustomMapper.MapObject<BuyerViewModel>(x))]);
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return BuyerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return BuyerOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -56,22 +41,22 @@ public class BuyerAdapter : IBuyerAdapter
{
try
{
return BuyerOperationResponse.OK(_mapper.Map<BuyerViewModel>(_buyerBusinessLogicContract.GetBuyerByData(data)));
return BuyerOperationResponse.OK(CustomMapper.MapObject<BuyerViewModel>(_buyerBusinessLogicContract.GetBuyerByData(data)));
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return BuyerOperationResponse.BadRequest("Data is empty");
return BuyerOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return BuyerOperationResponse.NotFound($"Not found element by data {data}");
return BuyerOperationResponse.NotFound(string.Format(_localizer["AdapterMessageElementNotFoundException"], data));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return BuyerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return BuyerOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -84,18 +69,18 @@ public class BuyerAdapter : IBuyerAdapter
{
try
{
_buyerBusinessLogicContract.InsertBuyer(_mapper.Map<BuyerDataModel>(buyerModel));
_buyerBusinessLogicContract.InsertBuyer(CustomMapper.MapObject<BuyerDataModel>(buyerModel));
return BuyerOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return BuyerOperationResponse.BadRequest("Data is empty");
return BuyerOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return BuyerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return BuyerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementExistsException ex)
{
@@ -105,7 +90,7 @@ public class BuyerAdapter : IBuyerAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return BuyerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return BuyerOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -118,23 +103,23 @@ public class BuyerAdapter : IBuyerAdapter
{
try
{
_buyerBusinessLogicContract.UpdateBuyer(_mapper.Map<BuyerDataModel>(buyerModel));
_buyerBusinessLogicContract.UpdateBuyer(CustomMapper.MapObject<BuyerDataModel>(buyerModel));
return BuyerOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return BuyerOperationResponse.BadRequest("Data is empty");
return BuyerOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return BuyerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return BuyerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return BuyerOperationResponse.BadRequest($"Not found element by Id {buyerModel.Id}");
return BuyerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], buyerModel.Id));
}
catch (ElementExistsException ex)
{
@@ -144,7 +129,7 @@ public class BuyerAdapter : IBuyerAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return BuyerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return BuyerOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -163,22 +148,22 @@ public class BuyerAdapter : IBuyerAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return BuyerOperationResponse.BadRequest("Id is empty");
return BuyerOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return BuyerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return BuyerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return BuyerOperationResponse.BadRequest($"Not found element by id: {id}");
return BuyerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], id));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return BuyerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return BuyerOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{

View File

@@ -5,19 +5,23 @@ using CatHasPawsContratcs.BindingModels;
using CatHasPawsContratcs.BusinessLogicsContracts;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Resources;
using CatHasPawsContratcs.ViewModels;
using Microsoft.Extensions.Localization;
namespace CatHasPawsWebApi.Adapters;
public class ManufacturerAdapter : IManufacturerAdapter
internal class ManufacturerAdapter : IManufacturerAdapter
{
private readonly IManufacturerBusinessLogicContract _manufacturerBusinessLogicContract;
private readonly IStringLocalizer<Messages> _localizer;
private readonly ILogger _logger;
private readonly Mapper _mapper;
public ManufacturerAdapter(IManufacturerBusinessLogicContract manufacturerBusinessLogicContract, ILogger<ManufacturerAdapter> logger)
public ManufacturerAdapter(IManufacturerBusinessLogicContract manufacturerBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<ManufacturerAdapter> logger)
{
_manufacturerBusinessLogicContract = manufacturerBusinessLogicContract;
_logger = logger;
@@ -27,6 +31,7 @@ public class ManufacturerAdapter : IManufacturerAdapter
cfg.CreateMap<ManufacturerDataModel, ManufacturerViewModel>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public ManufacturerOperationResponse GetList()
@@ -35,15 +40,10 @@ public class ManufacturerAdapter : IManufacturerAdapter
{
return ManufacturerOperationResponse.OK([.. _manufacturerBusinessLogicContract.GetAllManufacturers().Select(x => _mapper.Map<ManufacturerViewModel>(x))]);
}
catch (NullListException)
{
_logger.LogError("NullListException");
return ManufacturerOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ManufacturerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return ManufacturerOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -61,17 +61,17 @@ public class ManufacturerAdapter : IManufacturerAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return ManufacturerOperationResponse.BadRequest("Data is empty");
return ManufacturerOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return ManufacturerOperationResponse.NotFound($"Not found element by data {data}");
return ManufacturerOperationResponse.NotFound(string.Format(_localizer["AdapterMessageElementNotFoundException"], data));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ManufacturerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return ManufacturerOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -90,12 +90,12 @@ public class ManufacturerAdapter : IManufacturerAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return ManufacturerOperationResponse.BadRequest("Data is empty");
return ManufacturerOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return ManufacturerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return ManufacturerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementExistsException ex)
{
@@ -105,7 +105,7 @@ public class ManufacturerAdapter : IManufacturerAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ManufacturerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return ManufacturerOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -124,17 +124,17 @@ public class ManufacturerAdapter : IManufacturerAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return ManufacturerOperationResponse.BadRequest("Data is empty");
return ManufacturerOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return ManufacturerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return ManufacturerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return ManufacturerOperationResponse.BadRequest($"Not found element by Id {manufacturerModel.Id}");
return ManufacturerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], manufacturerModel.Id));
}
catch (ElementExistsException ex)
{
@@ -144,7 +144,7 @@ public class ManufacturerAdapter : IManufacturerAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ManufacturerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return ManufacturerOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -163,22 +163,22 @@ public class ManufacturerAdapter : IManufacturerAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return ManufacturerOperationResponse.BadRequest("Id is empty");
return ManufacturerOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return ManufacturerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return ManufacturerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return ManufacturerOperationResponse.BadRequest($"Not found element by id: {id}");
return ManufacturerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], id));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ManufacturerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return ManufacturerOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{

View File

@@ -1,53 +1,37 @@
using AutoMapper;
using CatHasPawsContratcs.AdapterContracts;
using CatHasPawsContratcs.AdapterContracts.OperationResponses;
using CatHasPawsContratcs.AdapterContracts;
using CatHasPawsContratcs.BindingModels;
using CatHasPawsContratcs.BusinessLogicsContracts;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Mapper;
using CatHasPawsContratcs.Resources;
using CatHasPawsContratcs.ViewModels;
using Microsoft.Extensions.Localization;
using System.Text.Json;
namespace CatHasPawsWebApi.Adapters;
public class PostAdapter : IPostAdapter
internal class PostAdapter(IPostBusinessLogicContract postBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<PostAdapter> logger) : IPostAdapter
{
private readonly IPostBusinessLogicContract _postBusinessLogicContract;
private readonly IPostBusinessLogicContract _postBusinessLogicContract = postBusinessLogicContract;
private readonly ILogger _logger;
private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly Mapper _mapper;
private readonly ILogger _logger = logger;
private readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNameCaseInsensitive = true };
public PostAdapter(IPostBusinessLogicContract postBusinessLogicContract, ILogger<PostAdapter> logger)
{
_postBusinessLogicContract = postBusinessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<PostBindingModel, PostDataModel>();
cfg.CreateMap<PostDataModel, PostViewModel>()
.ForMember(x => x.Configuration, x => x.MapFrom(src => JsonSerializer.Serialize(src.ConfigurationModel, JsonSerializerOptions)));
});
_mapper = new Mapper(config);
}
public PostOperationResponse GetList()
{
try
{
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllPosts().Select(x => _mapper.Map<PostViewModel>(x))]);
}
catch (NullListException)
{
_logger.LogError("NullListException");
return PostOperationResponse.NotFound("The list is not initialized");
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllPosts().Select(x => CustomMapper.MapObject<PostViewModel>(x))]);
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -60,22 +44,22 @@ public class PostAdapter : IPostAdapter
{
try
{
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllDataOfPost(id).Select(x => _mapper.Map<PostViewModel>(x))]);
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllDataOfPost(id).Select(x => CustomMapper.MapObject<PostViewModel>(x))]);
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest("Data is empty");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -88,27 +72,27 @@ public class PostAdapter : IPostAdapter
{
try
{
return PostOperationResponse.OK(_mapper.Map<PostViewModel>(_postBusinessLogicContract.GetPostByData(data)));
return PostOperationResponse.OK(CustomMapper.MapObject<PostViewModel>(_postBusinessLogicContract.GetPostByData(data)));
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest("Data is empty");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return PostOperationResponse.NotFound($"Not found element by data {data}");
return PostOperationResponse.NotFound(string.Format(_localizer["AdapterMessageElementNotFoundException"], data));
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return PostOperationResponse.BadRequest($"Element by data: {data} was deleted");
return PostOperationResponse.NotFound(string.Format(_localizer["AdapterMessageElementDeletedException"], data));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -121,18 +105,18 @@ public class PostAdapter : IPostAdapter
{
try
{
_postBusinessLogicContract.InsertPost(_mapper.Map<PostDataModel>(postModel));
_postBusinessLogicContract.InsertPost(CustomMapper.MapObject<PostDataModel>(postModel));
return PostOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest("Data is empty");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementExistsException ex)
{
@@ -142,7 +126,7 @@ public class PostAdapter : IPostAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -155,23 +139,23 @@ public class PostAdapter : IPostAdapter
{
try
{
_postBusinessLogicContract.UpdatePost(_mapper.Map<PostDataModel>(postModel));
_postBusinessLogicContract.UpdatePost(CustomMapper.MapObject<PostDataModel>(postModel));
return PostOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest("Data is empty");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return PostOperationResponse.BadRequest($"Not found element by Id {postModel.Id}");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], postModel.Id));
}
catch (ElementExistsException ex)
{
@@ -181,12 +165,12 @@ public class PostAdapter : IPostAdapter
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return PostOperationResponse.BadRequest($"Element by id: {postModel.Id} was deleted");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], postModel.Id));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -205,27 +189,27 @@ public class PostAdapter : IPostAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest("Id is empty");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return PostOperationResponse.BadRequest($"Not found element by id: {id}");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], id));
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return PostOperationResponse.BadRequest($"Element by id: {id} was deleted");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], id));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -244,22 +228,22 @@ public class PostAdapter : IPostAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest("Id is empty");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return PostOperationResponse.BadRequest($"Not found element by id: {id}");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], id));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{

View File

@@ -6,18 +6,22 @@ using CatHasPawsContratcs.BusinessLogicsContracts;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.ViewModels;
using CatHasPawsContratcs.Resources;
using Microsoft.Extensions.Localization;
namespace CatHasPawsWebApi.Adapters;
public class ProductAdapter : IProductAdapter
internal class ProductAdapter : IProductAdapter
{
private readonly IProductBusinessLogicContract _productBusinessLogicContract;
private readonly IStringLocalizer<Messages> _localizer;
private readonly ILogger _logger;
private readonly Mapper _mapper;
public ProductAdapter(IProductBusinessLogicContract productBusinessLogicContract, ILogger<ProductAdapter> logger)
public ProductAdapter(IProductBusinessLogicContract productBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<ProductAdapter> logger)
{
_productBusinessLogicContract = productBusinessLogicContract;
_logger = logger;
@@ -25,9 +29,11 @@ public class ProductAdapter : IProductAdapter
{
cfg.CreateMap<ProductBindingModel, ProductDataModel>();
cfg.CreateMap<ProductDataModel, ProductViewModel>();
cfg.CreateMap<ProductHistoryDataModel, ProductHistoryViewModel>();
cfg.CreateMap<ProductHistoryDataModel, ProductHistoryViewModel>()
.ForMember(x => x.ChangeDate, x => x.MapFrom(src => src.ChangeDate.ToLocalTime()));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public ProductOperationResponse GetList(bool includeDeleted)
@@ -36,15 +42,10 @@ public class ProductAdapter : IProductAdapter
{
return ProductOperationResponse.OK([.. _productBusinessLogicContract.GetAllProducts(!includeDeleted).Select(x => _mapper.Map<ProductViewModel>(x))]);
}
catch (NullListException)
{
_logger.LogError("NullListException");
return ProductOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ProductOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return ProductOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -59,25 +60,15 @@ public class ProductAdapter : IProductAdapter
{
return ProductOperationResponse.OK([.. _productBusinessLogicContract.GetAllProductsByManufacturer(id, !includeDeleted).Select(x => _mapper.Map<ProductViewModel>(x))]);
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return ProductOperationResponse.BadRequest("Data is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return ProductOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return ProductOperationResponse.NotFound("The list is not initialized");
return ProductOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ProductOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return ProductOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -95,17 +86,12 @@ public class ProductAdapter : IProductAdapter
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return ProductOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return ProductOperationResponse.NotFound("The list is not initialized");
return ProductOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ProductOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return ProductOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -123,22 +109,22 @@ public class ProductAdapter : IProductAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return ProductOperationResponse.BadRequest("Data is empty");
return ProductOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return ProductOperationResponse.NotFound($"Not found element by data {data}");
return ProductOperationResponse.NotFound(string.Format(_localizer["AdapterMessageElementNotFoundException"], data));
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return ProductOperationResponse.BadRequest($"Element by data: {data} was deleted");
return ProductOperationResponse.NotFound(string.Format(_localizer["AdapterMessageElementDeletedException"], data));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ProductOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return ProductOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -157,12 +143,12 @@ public class ProductAdapter : IProductAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return ProductOperationResponse.BadRequest("Data is empty");
return ProductOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return ProductOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return ProductOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementExistsException ex)
{
@@ -172,7 +158,7 @@ public class ProductAdapter : IProductAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ProductOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return ProductOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -191,17 +177,17 @@ public class ProductAdapter : IProductAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return ProductOperationResponse.BadRequest("Data is empty");
return ProductOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return ProductOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return ProductOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return ProductOperationResponse.BadRequest($"Not found element by Id {productModel.Id}");
return ProductOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], productModel.Id));
}
catch (ElementExistsException ex)
{
@@ -211,12 +197,12 @@ public class ProductAdapter : IProductAdapter
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return ProductOperationResponse.BadRequest($"Element by id: {productModel.Id} was deleted");
return ProductOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], productModel.Id));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ProductOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return ProductOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -235,27 +221,27 @@ public class ProductAdapter : IProductAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return ProductOperationResponse.BadRequest("Id is empty");
return ProductOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return ProductOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return ProductOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return ProductOperationResponse.BadRequest($"Not found element by id: {id}");
return ProductOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], id));
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return ProductOperationResponse.BadRequest($"Element by id: {id} was deleted");
return ProductOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], id));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ProductOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return ProductOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{

View File

@@ -4,109 +4,35 @@ using CatHasPawsContratcs.AdapterContracts.OperationResponses;
using CatHasPawsContratcs.BusinessLogicsContracts;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Resources;
using CatHasPawsContratcs.ViewModels;
using Microsoft.Extensions.Localization;
namespace CatHasPawsWebApi.Adapters;
public class ReportAdapter : IReportAdapter
internal class ReportAdapter : IReportAdapter
{
private readonly IReportContract _reportContract;
private readonly IStringLocalizer<Messages> _localizer;
private readonly ILogger _logger;
private readonly Mapper _mapper;
public ReportAdapter(IReportContract reportContract, ILogger<ProductAdapter> logger)
public ReportAdapter(IReportContract reportContract, IStringLocalizer<Messages> localizer, ILogger logger)
{
_reportContract = reportContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<ManufacturerProductDataModel, ManufacturerProductViewModel>();
cfg.CreateMap<WorkerSalaryByPeriodDataModel, WorkerSalaryByPeriodViewModel>();
cfg.CreateMap<SaleDataModel, SaleViewModel>();
cfg.CreateMap<SaleProductDataModel, SaleProductViewModel>();
cfg.CreateMap<WorkerSalaryByPeriodDataModel, WorkerSalaryByPeriodViewModel>();
});
_mapper = new Mapper(config);
}
public async Task<ReportOperationResponse> GetDataProductsByManufacturerAsync(CancellationToken ct)
{
try
{
return ReportOperationResponse.OK([.. (await _reportContract.GetDataProductsByManufacturerAsync(ct)).Select(x => _mapper.Map<ManufacturerProductViewModel>(x))]);
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "InvalidOperationException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return ReportOperationResponse.InternalServerError(ex.Message);
}
}
public async Task<ReportOperationResponse> GetDataSaleByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
try
{
return ReportOperationResponse.OK((await _reportContract.GetDataSaleByPeriodAsync(dateStart, dateFinish, ct)).Select(x => _mapper.Map<SaleViewModel>(x)).ToList());
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "InvalidOperationException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return ReportOperationResponse.InternalServerError(ex.Message);
}
}
public async Task<ReportOperationResponse> GetDataSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
try
{
return ReportOperationResponse.OK((await _reportContract.GetDataSalaryByPeriodAsync(dateStart, dateFinish, ct)).Select(x => _mapper.Map<WorkerSalaryByPeriodViewModel>(x)).ToList());
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "InvalidOperationException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return ReportOperationResponse.InternalServerError(ex.Message);
}
_localizer = localizer;
}
public async Task<ReportOperationResponse> CreateDocumentProductsByManufacturerAsync(CancellationToken ct)
@@ -118,40 +44,12 @@ public class ReportAdapter : IReportAdapter
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "InvalidOperationException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageInvalidOperationException"], ex.InnerException!.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return ReportOperationResponse.InternalServerError(ex.Message);
}
}
public async Task<ReportOperationResponse> CreateDocumentSalesByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
try
{
return SendStream(await _reportContract.CreateDocumentSalesByPeriodAsync(dateStart, dateFinish, ct), "sales.xslx");
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "InvalidOperationException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -164,22 +62,129 @@ public class ReportAdapter : IReportAdapter
{
try
{
return SendStream(await _reportContract.CreateDocumentSalaryByPeriodAsync(dateStart, dateFinish, ct), "salary.pdf");
return SendStream(await _reportContract.CreateDocumentSalaryByPeriodAsync(dateStart.ToUniversalTime(), dateFinish.ToUniversalTime(), ct), "salary.pdf");
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
return ReportOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageIncorrectDatesException"], ex.Message));
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "InvalidOperationException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageInvalidOperationException"], ex.InnerException!.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return ReportOperationResponse.InternalServerError(ex.Message);
}
}
public async Task<ReportOperationResponse> CreateDocumentSalesByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
try
{
return SendStream(await _reportContract.CreateDocumentSalesByPeriodAsync(dateStart.ToUniversalTime(), dateFinish.ToUniversalTime(), ct), "sales.xslx");
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return ReportOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageIncorrectDatesException"], ex.Message));
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "InvalidOperationException");
return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageInvalidOperationException"], ex.InnerException!.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return ReportOperationResponse.InternalServerError(ex.Message);
}
}
public async Task<ReportOperationResponse> GetDataProductsByManufacturerAsync(CancellationToken ct)
{
try
{
return ReportOperationResponse.OK((await _reportContract.GetDataProductsByManufacturerAsync(ct)).Select(x => _mapper.Map<ManufacturerProductViewModel>(x)).ToList());
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "InvalidOperationException");
return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageInvalidOperationException"], ex.InnerException!.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return ReportOperationResponse.InternalServerError(ex.Message);
}
}
public async Task<ReportOperationResponse> GetDataSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
try
{
return ReportOperationResponse.OK((await _reportContract.GetDataSalaryByPeriodAsync(dateStart.ToUniversalTime(), dateFinish.ToUniversalTime(), ct)).Select(x => _mapper.Map<WorkerSalaryByPeriodViewModel>(x)).ToList());
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return ReportOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageIncorrectDatesException"], ex.Message));
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "InvalidOperationException");
return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageInvalidOperationException"], ex.InnerException!.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return ReportOperationResponse.InternalServerError(ex.Message);
}
}
public async Task<ReportOperationResponse> GetDataSaleByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
try
{
return ReportOperationResponse.OK((await _reportContract.GetDataSaleByPeriodAsync(dateStart.ToUniversalTime(), dateFinish.ToUniversalTime(), ct)).Select(x => _mapper.Map<SaleViewModel>(x)).ToList());
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return ReportOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageIncorrectDatesException"], ex.Message));
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "InvalidOperationException");
return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageInvalidOperationException"], ex.InnerException!.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{

View File

@@ -5,52 +5,53 @@ using CatHasPawsContratcs.BindingModels;
using CatHasPawsContratcs.BusinessLogicsContracts;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Resources;
using CatHasPawsContratcs.ViewModels;
using Microsoft.Extensions.Localization;
namespace CatHasPawsWebApi.Adapters;
public class SaleAdapter : ISaleAdapter
internal class SaleAdapter : ISaleAdapter
{
private readonly ISaleBusinessLogicContract _saleBusinessLogicContract;
private readonly IStringLocalizer<Messages> _localizer;
private readonly ILogger _logger;
private readonly Mapper _mapper;
public SaleAdapter(ISaleBusinessLogicContract saleBusinessLogicContract, ILogger<SaleAdapter> logger)
public SaleAdapter(ISaleBusinessLogicContract saleBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<SaleAdapter> logger)
{
_saleBusinessLogicContract = saleBusinessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<SaleBindingModel, SaleDataModel>();
cfg.CreateMap<SaleDataModel, SaleViewModel>();
cfg.CreateMap<SaleDataModel, SaleViewModel>()
.ForMember(x => x.SaleDate, x => x.MapFrom(src => src.SaleDate.ToLocalTime()));
cfg.CreateMap<SaleProductBindingModel, SaleProductDataModel>();
cfg.CreateMap<SaleProductDataModel, SaleProductViewModel>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public SaleOperationResponse GetList(DateTime fromDate, DateTime toDate)
{
try
{
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByPeriod(fromDate, toDate).Select(x => _mapper.Map<SaleViewModel>(x))]);
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByPeriod(fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => _mapper.Map<SaleViewModel>(x))]);
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return SaleOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return SaleOperationResponse.NotFound("The list is not initialized");
return SaleOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageIncorrectDatesException"], ex.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return SaleOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -63,27 +64,22 @@ public class SaleAdapter : ISaleAdapter
{
try
{
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(id, fromDate, toDate).Select(x => _mapper.Map<SaleViewModel>(x))]);
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(id, fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => _mapper.Map<SaleViewModel>(x))]);
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return SaleOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
return SaleOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageIncorrectDatesException"], ex.Message));
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return SaleOperationResponse.NotFound("The list is not initialized");
return SaleOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return SaleOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -96,27 +92,22 @@ public class SaleAdapter : ISaleAdapter
{
try
{
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(id, fromDate, toDate).Select(x => _mapper.Map<SaleViewModel>(x))]);
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(id, fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => _mapper.Map<SaleViewModel>(x))]);
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return SaleOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
return SaleOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageIncorrectDatesException"], ex.Message));
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return SaleOperationResponse.NotFound("The list is not initialized");
return SaleOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return SaleOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -129,27 +120,22 @@ public class SaleAdapter : ISaleAdapter
{
try
{
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByProductByPeriod(id, fromDate, toDate).Select(x => _mapper.Map<SaleViewModel>(x))]);
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByProductByPeriod(id, fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => _mapper.Map<SaleViewModel>(x))]);
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return SaleOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
return SaleOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageIncorrectDatesException"], ex.Message));
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return SaleOperationResponse.NotFound("The list is not initialized");
return SaleOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return SaleOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -167,22 +153,22 @@ public class SaleAdapter : ISaleAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return SaleOperationResponse.BadRequest("Data is empty");
return SaleOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return SaleOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return SaleOperationResponse.NotFound($"Not found element by data {id}");
return SaleOperationResponse.NotFound(string.Format(_localizer["AdapterMessageElementNotFoundException"], id));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return SaleOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -202,17 +188,17 @@ public class SaleAdapter : ISaleAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return SaleOperationResponse.BadRequest("Data is empty");
return SaleOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return SaleOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return SaleOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return SaleOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -231,27 +217,27 @@ public class SaleAdapter : ISaleAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return SaleOperationResponse.BadRequest("Id is empty");
return SaleOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return SaleOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return SaleOperationResponse.BadRequest($"Not found element by id: {id}");
return SaleOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], id));
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return SaleOperationResponse.BadRequest($"Element by id: {id} was deleted");
return SaleOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], id));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return SaleOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return SaleOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{

Some files were not shown because too many files have changed in this diff Show More