2 Commits

Author SHA1 Message Date
50a0807cdf семафор 2025-05-21 12:43:59 +04:00
4abc5ebcfb забыл тесты раскомитить 2025-05-21 12:26:01 +04:00
109 changed files with 1048 additions and 4719 deletions

View File

@@ -1,10 +1,8 @@
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging;
using SladkieBulkiContrakts.BusinessLogicsContracts;
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Resources;
using SladkieBulkiContrakts.StoragesContarcts;
using System;
using System.Collections.Generic;
@@ -15,16 +13,15 @@ using System.Threading.Tasks;
namespace SladkieBulkiBusinessLogic.Implementations;
internal class IngredientBusinessLogicContract (IIngredientStorageContract ingredientStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : IIngredientBusinessLogicContract
internal class IngredientBusinessLogicContract (IIngredientStorageContract ingredientStorageContract, ILogger logger) : IIngredientBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IIngredientStorageContract _ingredientStorageContract = ingredientStorageContract;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<IngredientDataModel> GetAllIngredients()
{
_logger.LogInformation("GetAllBuyers");
return _ingredientStorageContract.GetList();
return _ingredientStorageContract.GetList() ?? throw new NullListException();
}
public List<IngredientDataModel> GetIngredientsBySizeUnit(string sizeUnit)
@@ -38,7 +35,7 @@ internal class IngredientBusinessLogicContract (IIngredientStorageContract ingre
var list = _ingredientStorageContract.GetElementBySizeUnit(sizeUnit);
if (list == null)
{
throw new NullListException();
}
return list.Where(x => x.SizeInit == sizeUnit).ToList();
@@ -55,10 +52,10 @@ internal class IngredientBusinessLogicContract (IIngredientStorageContract ingre
if (!id.IsGuid())
{
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
throw new ValidationException("Id is not a unique identifier");
}
return _ingredientStorageContract.GetElementById(id) ?? throw new ElementNotFoundException(id, _localizer);
return _ingredientStorageContract.GetElementById(id) ?? throw new ElementNotFoundException(id);
}
public IngredientDataModel? GetIngredientByName(string name)
@@ -70,7 +67,7 @@ internal class IngredientBusinessLogicContract (IIngredientStorageContract ingre
throw new ArgumentNullException(nameof(name));
}
return _ingredientStorageContract.GetElementByName(name) ?? throw new ElementNotFoundException(name, _localizer);
return _ingredientStorageContract.GetElementByName(name) ?? throw new ElementNotFoundException(name);
}
public void InsertIngredient(IngredientDataModel ingredientDataModel)
@@ -78,7 +75,7 @@ internal class IngredientBusinessLogicContract (IIngredientStorageContract ingre
_logger.LogInformation("New ingredient: {json}", JsonSerializer.Serialize(ingredientDataModel));
ArgumentNullException.ThrowIfNull(ingredientDataModel);
ingredientDataModel.Validate(_localizer);
ingredientDataModel.Validate();
_ingredientStorageContract.AddElement(ingredientDataModel);
}
@@ -88,7 +85,7 @@ internal class IngredientBusinessLogicContract (IIngredientStorageContract ingre
_logger.LogInformation("Update ingredient: {json}", JsonSerializer.Serialize(ingredientDataModel));
ArgumentNullException.ThrowIfNull(ingredientDataModel);
ingredientDataModel.Validate(_localizer);
ingredientDataModel.Validate();
_ingredientStorageContract.UpdElement(ingredientDataModel);
}

View File

@@ -1,24 +1,22 @@
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging;
using SladkieBulkiContrakts.BusinessLogicsContracts;
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Resources;
using SladkieBulkiContrakts.StoragesContarcts;
using System.Text.Json;
namespace SladkieBulkiBusinessLogic.Implementations;
internal class PostBusinessLogicContract(IPostStorageContract postStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : IPostBusinessLogicContract
internal class PostBusinessLogicContract(IPostStorageContract postStorageContract, 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();
return _postStorageContract.GetList() ?? throw new NullListException();
}
public List<PostDataModel> GetAllDataOfPost(string postId)
@@ -30,9 +28,9 @@ internal class PostBusinessLogicContract(IPostStorageContract postStorageContrac
}
if (!postId.IsGuid())
{
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "postId"));
throw new ValidationException("The value in the field postId is not a unique identifier.");
}
return _postStorageContract.GetPostWithHistory(postId);
return _postStorageContract.GetPostWithHistory(postId) ?? throw new NullListException();
}
public PostDataModel GetPostByData(string data)
@@ -44,16 +42,16 @@ internal class PostBusinessLogicContract(IPostStorageContract postStorageContrac
}
if (data.IsGuid())
{
return _postStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data, _localizer);
return _postStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
return _postStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data, _localizer);
return _postStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data);
}
public void InsertPost(PostDataModel postDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(postDataModel));
ArgumentNullException.ThrowIfNull(postDataModel);
postDataModel.Validate( _localizer);
postDataModel.Validate();
_postStorageContract.AddElement(postDataModel);
}
@@ -61,7 +59,7 @@ internal class PostBusinessLogicContract(IPostStorageContract postStorageContrac
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(postDataModel));
ArgumentNullException.ThrowIfNull(postDataModel);
postDataModel.Validate( _localizer);
postDataModel.Validate();
_postStorageContract.UpdElement(postDataModel);
}
@@ -74,7 +72,7 @@ internal class PostBusinessLogicContract(IPostStorageContract postStorageContrac
}
if (!id.IsGuid())
{
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
throw new ValidationException("Id is not a unique identifier");
}
_postStorageContract.DelElement(id);
}
@@ -88,7 +86,7 @@ internal class PostBusinessLogicContract(IPostStorageContract postStorageContrac
}
if (!id.IsGuid())
{
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
throw new ValidationException("Id is not a unique identifier");
}
_postStorageContract.ResElement(id);
}

View File

@@ -1,26 +1,24 @@
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging;
using SladkieBulkiContrakts.BusinessLogicsContracts;
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Resources;
using SladkieBulkiContrakts.StoragesContarcts;
using System.Text.Json;
namespace SladkieBulkiBusinessLogic.Implementations;
internal class ProductBusinessLogicContract(IProductStorageContract productStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : IProductBusinessLogicContract
internal class ProductBusinessLogicContract(IProductStorageContract productStorageContract, 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);
return _productStorageContract.GetList(onlyActive) ?? throw new NullListException();
//return [];
}
@@ -34,9 +32,9 @@ internal class ProductBusinessLogicContract(IProductStorageContract productStora
}
if (!productId.IsGuid())
{
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "productId"));
throw new ValidationException("The value in the field productId is not a unique identifier.");
}
return _productStorageContract.GetHistoryByProductId(productId);
return _productStorageContract.GetHistoryByProductId(productId) ?? throw new NullListException();
//return [];
}
@@ -50,9 +48,9 @@ internal class ProductBusinessLogicContract(IProductStorageContract productStora
}
if (data.IsGuid())
{
return _productStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data, _localizer);
return _productStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
return _productStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data, _localizer);
return _productStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data);
//return new("", "", "", 0, [], 0, false);
}
@@ -61,7 +59,7 @@ internal class ProductBusinessLogicContract(IProductStorageContract productStora
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(productDataModel));
ArgumentNullException.ThrowIfNull(productDataModel);
productDataModel.Validate( _localizer);
productDataModel.Validate();
_productStorageContract.AddElement(productDataModel);
}
@@ -69,7 +67,7 @@ internal class ProductBusinessLogicContract(IProductStorageContract productStora
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(productDataModel));
ArgumentNullException.ThrowIfNull(productDataModel);
productDataModel.Validate( _localizer);
productDataModel.Validate();
_productStorageContract.UpdElement(productDataModel);
}
public void DeleteProduct(string id)
@@ -81,7 +79,7 @@ internal class ProductBusinessLogicContract(IProductStorageContract productStora
}
if (!id.IsGuid())
{
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
throw new ValidationException("Id is not a unique identifier");
}
_productStorageContract.DelElement(id);
}

View File

@@ -1,29 +1,27 @@
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging;
using SladkieBulkiContrakts.BusinessLogicsContracts;
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Resources;
using SladkieBulkiContrakts.StoragesContarcts;
using System.Text.Json;
namespace SladkieBulkiBusinessLogic.Implementations;
internal class ProductionBusinessLogicContract(IProductionStorageContract productionStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : IProductionBusinessLogicContract
internal class ProductionBusinessLogicContract(IProductionStorageContract productionStorageContract,ILogger logger) : IProductionBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IProductionStorageContract _productionStorageContract = productionStorageContract;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<ProductionDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllProductionsByPeriod params: {fromDate}, {toDate}", fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate, _localizer);
throw new IncorrectDatesException(fromDate, toDate);
}
return _productionStorageContract.GetList(fromDate, toDate);
return _productionStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
}
public List<ProductionDataModel> GetAllSalesByProductByPeriod(string productId, DateTime fromDate, DateTime toDate)
@@ -31,7 +29,7 @@ internal class ProductionBusinessLogicContract(IProductionStorageContract produc
_logger.LogInformation("GetAllProductionsByProduct params: {productId}, {fromDate}, {toDate}", productId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate, _localizer);
throw new IncorrectDatesException(fromDate, toDate);
}
if (productId.IsEmpty())
{
@@ -39,9 +37,9 @@ internal class ProductionBusinessLogicContract(IProductionStorageContract produc
}
if (!productId.IsGuid())
{
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "productId"));
throw new ValidationException("The value in the field productId is not a unique identifier.");
}
return _productionStorageContract.GetList(fromDate, toDate, productId: productId);
return _productionStorageContract.GetList(fromDate, toDate, productId: productId) ?? throw new NullListException();
}
public List<ProductionDataModel> GetAllSalesByWorkerByPeriod(string workerId, DateTime fromDate, DateTime toDate)
@@ -49,7 +47,7 @@ internal class ProductionBusinessLogicContract(IProductionStorageContract produc
_logger.LogInformation("GetAllProductionsByWorker params: {workerId}, {fromDate}, {toDate}", workerId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate, _localizer);
throw new IncorrectDatesException(fromDate, toDate);
}
if (workerId.IsEmpty())
{
@@ -57,9 +55,9 @@ internal class ProductionBusinessLogicContract(IProductionStorageContract produc
}
if (!workerId.IsGuid())
{
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "workerId"));
throw new ValidationException("The value in the field workerId is not a unique identifier.");
}
return _productionStorageContract.GetList(fromDate, toDate, workerId: workerId);
return _productionStorageContract.GetList(fromDate, toDate, workerId: workerId) ?? throw new NullListException();
}
public ProductionDataModel GetProductionByData(string data)
@@ -71,16 +69,16 @@ internal class ProductionBusinessLogicContract(IProductionStorageContract produc
}
if (!data.IsGuid())
{
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
throw new ValidationException("Id is not a unique identifier");
}
return _productionStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data, _localizer);
return _productionStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
public void InsertProduction(ProductionDataModel productionDataModel)
{
_logger.LogInformation("InsertProduction: {json}", JsonSerializer.Serialize(productionDataModel));
ArgumentNullException.ThrowIfNull(productionDataModel);
productionDataModel.Validate( _localizer);
productionDataModel.Validate();
_productionStorageContract.AddElement(productionDataModel);
}
@@ -93,7 +91,7 @@ internal class ProductionBusinessLogicContract(IProductionStorageContract produc
}
if (!id.IsGuid())
{
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
throw new ValidationException("Id is not a unique identifier");
}
_productionStorageContract.DelElement(id);
}

View File

@@ -1,275 +0,0 @@
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using SladkieBulkiBusinessLogic.OfficePackage;
using SladkieBulkiContrakts.BusinessLogicsContracts;
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Resources;
using SladkieBulkiContrakts.StoragesContarcts;
using SladkieBulkiContrakts.ViewModels;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiBusinessLogic.Implementations;
internal class ReportContract : IReportContract
{
private readonly IProductStorageContract _productStorageContract;
private readonly IIngredientStorageContract _ingredientStorageContract;
private readonly IProductionStorageContract _productionStorageContract;
private readonly ISalaryStorageContract _salaryStorageContract;
private readonly IWorkerStorageContract _workerStorageContract;
private readonly IStringLocalizer<Messages> _localizer;
private readonly BaseWordBuilder _baseWordBuilder;
private readonly BaseExcelBuilder _baseExcelBuilder;
private readonly BasePdfBuilder _basePdfBuilder;
private readonly ILogger _logger;
internal readonly string[] _productDocumentHeader;
internal readonly string[] _productionDocumentHeader;
public ReportContract(IProductStorageContract productStorageContract, IStringLocalizer<Messages> localizer, IIngredientStorageContract ingredientStorageContract, IProductionStorageContract productionStorageContract, ISalaryStorageContract salaryStorageContract,IWorkerStorageContract workerStorageContract, BaseWordBuilder baseWordBuilder, BaseExcelBuilder baseExcelBuilder, BasePdfBuilder basePdfBuilder, ILogger logger)
{
_productStorageContract = productStorageContract;
_ingredientStorageContract = ingredientStorageContract;
_productionStorageContract = productionStorageContract;
_salaryStorageContract = salaryStorageContract;
_workerStorageContract = workerStorageContract;
_localizer = localizer;
_baseWordBuilder = baseWordBuilder;
_baseExcelBuilder = baseExcelBuilder;
_basePdfBuilder = basePdfBuilder;
_logger = logger;
_productDocumentHeader = [ _localizer["DocumentDocCaptionProduct"], _localizer["DocumentDocCaptionDesc"], _localizer["DocumentDocCaptionProdType"], _localizer["DocumentDocCaptionPrice"], _localizer["DocumentDocCaptionIngred"], _localizer["DocumentDocCaptionSize"], _localizer["DocumentDocCaptionUnitPrice"], _localizer["DocumentDocCaptionCount"]];
_productionDocumentHeader = [_localizer["DocumentExcelCaptionDate"],
_localizer["DocumentDocCaptionProduct"],
_localizer["DocumentExcelCaptionCount"],
_localizer["DocumentExcelCaptionSum"],
_localizer["DocumentExcelCaptionWorkerFIO"]];
}
public async Task<Stream> CreateDocumentSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
_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(_localizer["DocumentPdfHeader"])
.AddParagraph(string.Format(_localizer["DocumentPdfSubHeader"], dateStart.ToShortDateString(), dateFinish.ToShortDateString()))
.AddPieChart(_localizer["DocumentPdfDiagramCaption"], [.. data.Select(x => (x.WorkerFIO, x.TotalSalary))])
.Build();
}
public async Task<Stream> CreateDocumentProductsWithIngredientsAsync(CancellationToken ct)
{
_logger.LogInformation("Create report ProductsWithIngredients");
var data = await GetDataByProductsAsync(ct);
// Генерируем строки таблицы
var tableRows = new List<string[]>();
// Добавляем заголовок
tableRows.Add(_productDocumentHeader);
foreach (var product in data)
{
// Если нет ингредиентов — пустые колонки для ингредиентов
if (product.Ingredients == null || product.Ingredients.Count == 0)
{
tableRows.Add(new[]
{
product.Name,
product.Description,
product.ProductType,
product.UnitPrice.ToString("F2"),
"-", "-", "-", "-"
});
}
else
{
// Первая строка — продукт + первый ингредиент
var first = product.Ingredients[0];
tableRows.Add(new[]
{
product.Name,
product.Description,
product.ProductType,
product.UnitPrice.ToString("F2", CultureInfo.InvariantCulture),
first.NameIngredients,
first.SizeUnit,
first.InitPrice.ToString("F2", CultureInfo.InvariantCulture),
first.Count.ToString()
});
// Остальные строки — только ингредиенты, без продукта
for (int i = 1; i < product.Ingredients.Count; i++)
{
var ing = product.Ingredients[i];
tableRows.Add(new[]
{
"", "", "", "",
ing.NameIngredients,
ing.SizeUnit,
ing.InitPrice.ToString("F2"),
ing.Count.ToString()
});
}
}
}
// Пример ширин столбцов — можно подогнать под свой Word шаблон
int[] widths = { 3000, 4000, 2000, 2000, 2000, 2000, 2000, 1500 };
return _baseWordBuilder
.AddHeader(_localizer["DocumentDocHeader"])
.AddParagraph(string.Format(_localizer["DocumentDocSubHeader"], DateTime.Now))
.AddTable(widths, tableRows)
.Build();
}
public async Task<Stream> CreateDocumentProductionsByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
_logger.LogInformation("Create report ProductionsByPeriod from {dateStart} to {dateFinish}", dateStart, dateFinish);
// Получаем данные о производстве (ProductionDataModel)
var data = await GetDataByProductionsAsync(dateStart, dateFinish, ct);
// Для получения названий продуктов и работников — собираем все нужные Id и получаем имена
var productIds = data.Select(x => x.ProductId).Distinct().ToList();
var workerIds = data.Select(x => x.WorkerId).Distinct().ToList();
var products = new List<ProductDataModel>();
foreach (var productId in productIds)
{
var product = _productStorageContract.GetElementById(productId);
if (product != null) products.Add(product);
}
var workers = new List<WorkerDataModel>();
foreach (var workerId in workerIds)
{
var worker = _workerStorageContract.GetElementById(workerId);
if (worker != null) workers.Add(worker);
}
// Генерируем строки для таблицы
var tableRows = new List<string[]>();
// Заголовок
tableRows.Add(_productionDocumentHeader);
foreach (var prod in data)
{
var product = products.FirstOrDefault(p => p.Id == prod.ProductId);
var worker = workers.FirstOrDefault(w => w.Id == prod.WorkerId);
tableRows.Add(new[]
{
prod.ProductionDate.ToString("dd.MM.yyyy"),
product?.Name ?? "",
prod.Count.ToString(),
prod.Sum.ToString("F2", CultureInfo.InvariantCulture),
worker?.FIO ?? ""
});
}
// Подсчёт итогов
var totalCount = data.Sum(x => x.Count);
var totalSum = data.Sum(x => x.Sum);
// Итоговая строка
tableRows.Add(new[]
{
"", // Пусто в "Дата"
_localizer["DocumentExcelCaptionTotal"],
totalCount.ToString(),
totalSum.ToString("F2", CultureInfo.InvariantCulture),
"" // Пусто для колонки "Работник"
});
// Пример ширины столбцов, можно подогнать
int[] widths = { 15, 25, 10, 12, 20 };
return _baseExcelBuilder
.AddHeader(_localizer["DocumentExcelHeader"], 0, 5)
.AddParagraph(string.Format(_localizer["DocumentExcelSubHeader"], dateStart.ToShortDateString(), dateFinish.ToShortDateString()), 1)
.AddTable(widths, tableRows)
.Build();
}
public Task<List<WorkerSalaryByPeriodDataModel>> GetDataSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
_logger.LogInformation("Get data SalaryByPeriod from {dateStart} to {dateFinish}", dateStart, dateFinish);
return GetDataBySalaryAsync(dateStart, dateFinish, ct);
}
public Task<List<ProductWithIngredientsReportDataModel>> GetProductsWithIngredientsAsync(CancellationToken ct)
{
_logger.LogInformation("Get data ProductsWithIngredients");
return GetDataByProductsAsync(ct);
}
public Task<List<ProductionDataModel>> GetDataProductionsByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
_logger.LogInformation("Get data SalesByPeriod from {dateStart} to {dateFinish}", dateStart, dateFinish);
return GetDataByProductionsAsync(dateStart, dateFinish, ct);
}
private async Task<List<ProductWithIngredientsReportDataModel>> GetDataByProductsAsync(CancellationToken ct)
{
// Получаем все продукты
var products = await _productStorageContract.GetListAsync(ct);
// Получаем все ингредиенты одним запросом для сопоставления по id (оптимально!)
var allIngredients = await _ingredientStorageContract.GetListAsync(ct);
var result = products.Select(p => new ProductWithIngredientsReportDataModel
{
ProductId = p.Id,
Name = p.Name,
Description = p.Description,
ProductType = p.ProductType.ToString(),
UnitPrice = p.UnitPrice,
Ingredients = (p.Ingredients ?? Enumerable.Empty<ProductIngredientDataModel>())
.Select(pi =>
{
var ingredient = allIngredients.FirstOrDefault(x => x.Id == pi.IngredientId);
return ingredient == null ? null : new IngredientInProductDto
{
NameIngredients = ingredient.NameIngredients,
SizeUnit = ingredient.SizeInit,
InitPrice = ingredient.InitPrice,
Count = pi.Count
};
})
.Where(x => x != null)
.ToList()!
}).ToList();
return result;
}
private async Task<List<ProductionDataModel>> GetDataByProductionsAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
if (dateStart >= dateFinish)
throw new IncorrectDatesException(dateStart, dateFinish, _localizer);
var productions = await _productionStorageContract.GetListAsync(dateStart, dateFinish, ct);
return productions.OrderBy(x => x.ProductionDate).ToList();
}
private async Task<List<WorkerSalaryByPeriodDataModel>> GetDataBySalaryAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
if (dateStart.IsDateNotOlder(dateFinish))
{
throw new IncorrectDatesException(dateStart, dateFinish, _localizer);
}
return [.. (await _salaryStorageContract.GetListAsync(dateStart, dateFinish, ct)).GroupBy(x => x.WorkerFIO).Select(x => new WorkerSalaryByPeriodDataModel { WorkerFIO = x.Key, TotalSalary = x.Sum(y => y.WorkerSalary), FromPeriod = x.Min(y => y.SalaryDate), ToPeriod = x.Max(y => y.SalaryDate) }).OrderBy(x => x.WorkerFIO)];
}
}

View File

@@ -8,12 +8,10 @@ using SladkieBulkiContrakts.Infrastructure.PostConfigurations;
using SladkieBulkiContrakts.StoragesContarcts;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Localization;
using SladkieBulkiContrakts.Resources;
namespace SladkieBulkiBusinessLogic.Implementations;
internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract, IStringLocalizer<Messages> localizer, IProductionStorageContract productionStorageContract, IPostStorageContract postStorageContract, IWorkerStorageContract workerStorageContract, ILogger logger, IConfigurationSalary сonfiguration) : ISalaryBusinessLogicContract
internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract, IProductionStorageContract productionStorageContract, IPostStorageContract postStorageContract, IWorkerStorageContract workerStorageContract, ILogger logger, IConfigurationSalary сonfiguration) : ISalaryBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISalaryStorageContract _salaryStorageContract =
@@ -25,23 +23,23 @@ internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageC
workerStorageContract;
private readonly IConfigurationSalary _salaryConfiguration = сonfiguration;
private readonly object _lockObject = new();
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSalaries params: {fromDate}, {toDate}", fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate, _localizer);
throw new IncorrectDatesException(fromDate, toDate);
}
return _salaryStorageContract.GetList(fromDate, toDate);
return _salaryStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
}
public List<SalaryDataModel> GetAllSalariesByPeriodByWorker(DateTime fromDate, DateTime toDate, string workerId)
{
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate, _localizer);
throw new IncorrectDatesException(fromDate, toDate);
}
if (workerId.IsEmpty())
{
@@ -49,10 +47,10 @@ internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageC
}
if (!workerId.IsGuid())
{
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "workerId"));
throw new ValidationException("The value in the field workerId is not a unique identifier.");
}
_logger.LogInformation("GetAllSalaries params: {fromDate}, {toDate}, {workerId}", fromDate, toDate, workerId);
return _salaryStorageContract.GetList(fromDate, toDate, workerId);
return _salaryStorageContract.GetList(fromDate, toDate, workerId) ?? throw new NullListException();
}
public void CalculateSalaryByMounth(DateTime date)
@@ -60,11 +58,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() ;
var workers = _workerStorageContract.GetList() ?? throw new NullListException();
foreach (var worker in workers)
{
var sales = _productionStorageContract.GetList(startDate, finishDate, workerId: worker.Id);
var post = _postStorageContract.GetElementById(worker.PostId);
var sales = _productionStorageContract.GetList(startDate, finishDate, workerId: worker.Id) ?? throw new NullListException();
var post = _postStorageContract.GetElementById(worker.PostId) ?? throw new NullListException();
var salary = post.ConfigurationModel switch
{
null => 0,
@@ -79,41 +77,61 @@ internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageC
private double CalculateSalaryForCashier(List<ProductionDataModel> sales, DateTime startDate, DateTime finishDate, ManufacturerPostConfiguration config)
{
int maxConcurrency = сonfiguration.MaxParallelThreads;
var semaphore = new SemaphoreSlim(maxConcurrency);
var tasks = new List<Task>();
var calcPercent = 0.0;
for (var date = startDate; date < finishDate; date = date.AddDays(1))
{
tasks.Add(Task.Factory.StartNew((object? obj) =>
var dateCopy = date; // Нужно, чтобы замыкание захватило корректную дату
tasks.Add(Task.Run(async () =>
{
var dateInTask = (DateTime)obj!;
var salesInDay = sales.Where(x => x.ProductionDate >= dateInTask && x.ProductionDate < dateInTask.AddDays(1)).ToArray();
if (salesInDay.Length > 0)
await semaphore.WaitAsync();
try
{
lock (_lockObject)
var salesInDay = sales
.Where(x => x.ProductionDate >= dateCopy && x.ProductionDate < dateCopy.AddDays(1))
.ToArray();
if (salesInDay.Length > 0)
{
calcPercent += (salesInDay.Sum(x => x.Sum) / salesInDay.Length) * config.SalePercent;
lock (_lockObject)
{
calcPercent += (salesInDay.Sum(x => x.Sum) / salesInDay.Length) * config.SalePercent;
}
}
}
}, date));
finally
{
semaphore.Release();
}
}));
}
var calcBonusTask = Task.Run(() =>
{
return sales.Where(x => x.Sum > _salaryConfiguration.ExtraSaleSum).Sum(x => x.Sum) * config.BonusForExtraSales;
});
try
{
Task.WaitAll([Task.WhenAll(tasks), calcBonusTask]);
Task.WaitAll(tasks.ToArray()); // Ждём завершения всех задач по дням
calcBonusTask.Wait(); // Ждём завершения бонуса
}
catch (AggregateException agEx)
{
foreach (var ex in agEx.InnerExceptions)
{
_logger.LogError(ex, "Error in the cashier payroll process");
}
return 0;
}
return config.Rate + calcPercent + calcBonusTask.Result;
}
private double CalculateSalaryForSupervisor(DateTime startDate, DateTime finishDate, PackerPostConfiguration config)
{
try

View File

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

View File

@@ -1,18 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiBusinessLogic.OfficePackage;
public abstract class BaseExcelBuilder
{
public abstract BaseExcelBuilder AddHeader(string header, int startIndex, int count);
public abstract BaseExcelBuilder AddParagraph(string text, int columnIndex);
public abstract BaseExcelBuilder AddTable(int[] columnsWidths, List<string[]> data);
public abstract Stream Build();
}

View File

@@ -1,18 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiBusinessLogic.OfficePackage;
public abstract class BasePdfBuilder
{
public abstract BasePdfBuilder AddHeader(string header);
public abstract BasePdfBuilder AddParagraph(string text);
public abstract BasePdfBuilder AddPieChart(string title, List<(string Caption, double Value)> data);
public abstract Stream Build();
}

View File

@@ -1,18 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiBusinessLogic.OfficePackage;
public abstract class BaseWordBuilder
{
public abstract BaseWordBuilder AddHeader(string header);
public abstract BaseWordBuilder AddParagraph(string text);
public abstract BaseWordBuilder AddTable(int[] widths, List<string[]> data);
public abstract Stream Build();
}

View File

@@ -1,85 +0,0 @@
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Shapes.Charts;
using MigraDoc.Rendering;
using System.Text;
namespace SladkieBulkiBusinessLogic.OfficePackage;
internal class MigraDocPdfBuilder : BasePdfBuilder
{
private readonly Document _document;
public MigraDocPdfBuilder()
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
_document = new Document();
DefineStyles();
}
public override BasePdfBuilder AddHeader(string header)
{
_document.AddSection().AddParagraph(header, "NormalBold");
return this;
}
public override BasePdfBuilder AddParagraph(string text)
{
_document.LastSection.AddParagraph(text, "Normal");
return this;
}
public override BasePdfBuilder AddPieChart(string title, List<(string Caption, double Value)> data)
{
if (data == null || data.Count == 0)
{
return this;
}
var chart = new Chart(ChartType.Pie2D);
var series = chart.SeriesCollection.AddSeries();
series.Add(data.Select(x => x.Value).ToArray());
var xseries = chart.XValues.AddXSeries();
xseries.Add(data.Select(x => x.Caption).ToArray());
chart.DataLabel.Type = DataLabelType.Percent;
chart.DataLabel.Position = DataLabelPosition.OutsideEnd;
chart.Width = Unit.FromCentimeter(16);
chart.Height = Unit.FromCentimeter(12);
chart.TopArea.AddParagraph(title);
chart.XAxis.MajorTickMark = TickMarkType.Outside;
chart.YAxis.MajorTickMark = TickMarkType.Outside;
chart.YAxis.HasMajorGridlines = true;
chart.PlotArea.LineFormat.Width = 1;
chart.PlotArea.LineFormat.Visible = true;
chart.TopArea.AddLegend();
_document.LastSection.Add(chart);
return this;
}
public override Stream Build()
{
var stream = new MemoryStream();
var renderer = new PdfDocumentRenderer(true)
{
Document = _document
};
renderer.RenderDocument();
renderer.PdfDocument.Save(stream);
return stream;
}
private void DefineStyles()
{
var style = _document.Styles.AddStyle("NormalBold", "Normal");
style.Font.Bold = true;
}
}

View File

@@ -1,308 +0,0 @@
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiBusinessLogic.OfficePackage;
internal class OpenXmlExcelBuilder : BaseExcelBuilder
{
private readonly SheetData _sheetData;
private readonly MergeCells _mergeCells;
private readonly Columns _columns;
private uint _rowIndex = 0;
public OpenXmlExcelBuilder()
{
_sheetData = new SheetData();
_mergeCells = new MergeCells();
_columns = new Columns();
_rowIndex = 1;
}
public override BaseExcelBuilder AddHeader(string header, int startIndex, int count)
{
CreateCell(startIndex, _rowIndex, header, StyleIndex.BoldTextWithoutBorder);
for (int i = startIndex + 1; i < startIndex + count; ++i)
{
CreateCell(i, _rowIndex, "", StyleIndex.SimpleTextWithoutBorder);
}
_mergeCells.Append(new MergeCell()
{
Reference =
new StringValue($"{GetExcelColumnName(startIndex)}{_rowIndex}:{GetExcelColumnName(startIndex + count - 1)}{_rowIndex}")
});
_rowIndex++;
return this;
}
public override BaseExcelBuilder AddParagraph(string text, int columnIndex)
{
CreateCell(columnIndex, _rowIndex++, text, StyleIndex.SimpleTextWithoutBorder);
return this;
}
public override BaseExcelBuilder AddTable(int[] columnsWidths, List<string[]> data)
{
if (columnsWidths == null || columnsWidths.Length == 0)
{
throw new ArgumentNullException(nameof(columnsWidths));
}
if (data == null || data.Count == 0)
{
throw new ArgumentNullException(nameof(data));
}
if (data.Any(x => x.Length != columnsWidths.Length))
{
throw new InvalidOperationException("widths.Length != data.Length");
}
uint counter = 1;
int coef = 2;
_columns.Append(columnsWidths.Select(x => new Column
{
Min = counter,
Max = counter++,
Width = x * coef,
CustomWidth = true
}));
for (var j = 0; j < data.First().Length; ++j)
{
CreateCell(j, _rowIndex, data.First()[j], StyleIndex.BoldTextWithBorder);
}
_rowIndex++;
for (var i = 1; i < data.Count - 1; ++i)
{
for (var j = 0; j < data[i].Length; ++j)
{
CreateCell(j, _rowIndex, data[i][j], StyleIndex.SimpleTextWithBorder);
}
_rowIndex++;
}
for (var j = 0; j < data.Last().Length; ++j)
{
CreateCell(j, _rowIndex, data.Last()[j], StyleIndex.BoldTextWithBorder);
}
_rowIndex++;
return this;
}
public override Stream Build()
{
var stream = new MemoryStream();
using var spreadsheetDocument = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook);
var workbookpart = spreadsheetDocument.AddWorkbookPart();
GenerateStyle(workbookpart);
workbookpart.Workbook = new Workbook();
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
if (_columns.HasChildren)
{
worksheetPart.Worksheet.Append(_columns);
}
worksheetPart.Worksheet.Append(_sheetData);
var sheets = spreadsheetDocument.WorkbookPart!.Workbook.AppendChild(new Sheets());
var sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Лист 1"
};
sheets.Append(sheet);
if (_mergeCells.HasChildren)
{
worksheetPart.Worksheet.InsertAfter(_mergeCells, worksheetPart.Worksheet.Elements<SheetData>().First());
}
return stream;
}
private static void GenerateStyle(WorkbookPart workbookPart)
{
var workbookStylesPart = workbookPart.AddNewPart<WorkbookStylesPart>();
workbookStylesPart.Stylesheet = new Stylesheet();
var fonts = new Fonts() { Count = 2, KnownFonts = BooleanValue.FromBoolean(true) };
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
{
FontSize = new FontSize() { Val = 11 },
FontName = new FontName() { Val = "Calibri" },
FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 },
FontScheme = new FontScheme() { Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor) }
});
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
{
FontSize = new FontSize() { Val = 11 },
FontName = new FontName() { Val = "Calibri" },
FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 },
FontScheme = new FontScheme() { Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor) },
Bold = new Bold()
});
workbookStylesPart.Stylesheet.Append(fonts);
// Default Fill
var fills = new Fills() { Count = 1 };
fills.Append(new Fill
{
PatternFill = new PatternFill() { PatternType = new EnumValue<PatternValues>(PatternValues.None) }
});
workbookStylesPart.Stylesheet.Append(fills);
// Default Border
var borders = new Borders() { Count = 2 };
borders.Append(new Border
{
LeftBorder = new LeftBorder(),
RightBorder = new RightBorder(),
TopBorder = new TopBorder(),
BottomBorder = new BottomBorder(),
DiagonalBorder = new DiagonalBorder()
});
borders.Append(new Border
{
LeftBorder = new LeftBorder() { Style = BorderStyleValues.Thin },
RightBorder = new RightBorder() { Style = BorderStyleValues.Thin },
TopBorder = new TopBorder() { Style = BorderStyleValues.Thin },
BottomBorder = new BottomBorder() { Style = BorderStyleValues.Thin }
});
workbookStylesPart.Stylesheet.Append(borders);
// Default cell format and a date cell format
var cellFormats = new CellFormats() { Count = 4 };
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 0,
BorderId = 0,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 0,
BorderId = 1,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 1,
BorderId = 0,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Center,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 1,
BorderId = 1,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Center,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
workbookStylesPart.Stylesheet.Append(cellFormats);
}
private enum StyleIndex
{
SimpleTextWithoutBorder = 0,
SimpleTextWithBorder = 1,
BoldTextWithoutBorder = 2,
BoldTextWithBorder = 3
}
private void CreateCell(int columnIndex, uint rowIndex, string text, StyleIndex styleIndex)
{
var columnName = GetExcelColumnName(columnIndex);
var cellReference = columnName + rowIndex;
var row = _sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex! == rowIndex);
if (row == null)
{
row = new Row() { RowIndex = rowIndex };
_sheetData.Append(row);
}
var newCell = row.Elements<Cell>()
.FirstOrDefault(c => c.CellReference != null && c.CellReference.Value == columnName + rowIndex);
if (newCell == null)
{
Cell? refCell = null;
foreach (Cell cell in row.Elements<Cell>())
{
if (cell.CellReference?.Value != null && cell.CellReference.Value.Length == cellReference.Length)
{
if (string.Compare(cell.CellReference.Value, cellReference, true) > 0)
{
refCell = cell;
break;
}
}
}
newCell = new Cell() { CellReference = cellReference };
row.InsertBefore(newCell, refCell);
}
newCell.CellValue = new CellValue(text);
newCell.DataType = CellValues.String;
newCell.StyleIndex = (uint)styleIndex;
}
private static string GetExcelColumnName(int columnNumber)
{
columnNumber += 1;
int dividend = columnNumber;
string columnName = string.Empty;
int modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
dividend = (dividend - modulo) / 26;
}
return columnName;
}
}

View File

@@ -1,95 +0,0 @@
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace SladkieBulkiBusinessLogic.OfficePackage;
internal class OpenXmlWordBuilder : BaseWordBuilder
{
private readonly Document _document;
private readonly Body _body;
public OpenXmlWordBuilder()
{
_document = new Document();
_body = _document.AppendChild(new Body());
}
public override BaseWordBuilder AddHeader(string header)
{
var paragraph = _body.AppendChild(new Paragraph());
var run = paragraph.AppendChild(new Run());
run.AppendChild(new RunProperties(new Bold()));
run.AppendChild(new Text(header));
return this;
}
public override BaseWordBuilder AddParagraph(string text)
{
var paragraph = _body.AppendChild(new Paragraph());
var run = paragraph.AppendChild(new Run());
run.AppendChild(new Text(text));
return this;
}
public override BaseWordBuilder AddTable(int[] widths, List<string[]> data)
{
if (widths == null || widths.Length == 0)
{
throw new ArgumentNullException(nameof(widths));
}
if (data == null || data.Count == 0)
{
throw new ArgumentNullException(nameof(data));
}
if (data.Any(x => x.Length != widths.Length))
{
throw new InvalidOperationException("widths.Length != data.Length");
}
var table = new Table();
table.AppendChild(new TableProperties(
new TableBorders(
new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 }
)
));
// Заголовок
var tr = new TableRow();
for (var j = 0; j < widths.Length; ++j)
{
tr.Append(new TableCell(
new TableCellProperties(new TableCellWidth() { Width = widths[j].ToString() }),
new Paragraph(new Run(new RunProperties(new Bold()), new Text(data.First()[j])))));
}
table.Append(tr);
// Данные
table.Append(data.Skip(1).Select(x =>
new TableRow(x.Select(y => new TableCell(new Paragraph(new Run(new Text(y))))))));
_body.Append(table);
return this;
}
public override Stream Build()
{
var stream = new MemoryStream();
using var wordDocument = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document);
var mainPart = wordDocument.AddMainDocumentPart();
mainPart.Document = _document;
return stream;
}
}

View File

@@ -13,9 +13,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="3.3.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.1" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
</ItemGroup>
<ItemGroup>

View File

@@ -1,19 +0,0 @@
using SladkieBulkiContrakts.AdapterContracts.OperationResponses;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.AdapterContracts;
public interface IReportAdapter
{
Task<ReportOperationResponse> GetProductsWithIngredientsAsync(CancellationToken ct);
Task<ReportOperationResponse> GetDataProductionsByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<ReportOperationResponse> GetDataSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<ReportOperationResponse> CreateDocumentProductsWithIngredientsAsync(CancellationToken ct);
Task<ReportOperationResponse> CreateDocumentProductionsByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<ReportOperationResponse> CreateDocumentSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
}

View File

@@ -1,22 +0,0 @@
using SladkieBulkiContrakts.Infrastructure;
using SladkieBulkiContrakts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.AdapterContracts.OperationResponses;
public class ReportOperationResponse : OperationResponse
{
public static ReportOperationResponse OK(Stream data, string fileName) => OK<ReportOperationResponse, Stream>(data, fileName);
public static ReportOperationResponse OK(List<ProductionViewModel> data) => OK<ReportOperationResponse, List<ProductionViewModel>>(data);
public static ReportOperationResponse OK(List<WorkerSalaryByPeriodViewModel> data) => OK<ReportOperationResponse, List<WorkerSalaryByPeriodViewModel>>(data);
public static ReportOperationResponse OK(List<ProductWithIngredientsViewModel> data) => OK<ReportOperationResponse, List<ProductWithIngredientsViewModel>>(data);
public static ReportOperationResponse BadRequest(string message) => BadRequest<ReportOperationResponse>(message);
public static ReportOperationResponse InternalServerError(string message) => InternalServerError<ReportOperationResponse>(message);
}

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace SladkieBulkiContrakts.BusinessLogicsContracts;
internal interface IIngredientBusinessLogicContract
public interface IIngredientBusinessLogicContract
{
List<IngredientDataModel> GetAllIngredients();

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace SladkieBulkiContrakts.BusinessLogicsContracts;
internal interface IPostBusinessLogicContract
public interface IPostBusinessLogicContract
{
List<PostDataModel> GetAllPosts();
List<PostDataModel> GetAllDataOfPost(string postId);

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace SladkieBulkiContrakts.BusinessLogicsContracts;
internal interface IProductBusinessLogicContract
public interface IProductBusinessLogicContract
{
List<ProductDataModel> GetAllProducts(bool onlyActive = true);
List<ProductHistoryDataModel> GetProductHistoryByProduct(string productId);

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace SladkieBulkiContrakts.BusinessLogicsContracts;
internal interface IProductionBusinessLogicContract
public interface IProductionBusinessLogicContract
{
List<ProductionDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate);
List<ProductionDataModel> GetAllSalesByWorkerByPeriod(string workerId, DateTime fromDate, DateTime toDate);

View File

@@ -1,19 +0,0 @@
using SladkieBulkiContrakts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.BusinessLogicsContracts;
internal interface IReportContract
{
Task<List<ProductWithIngredientsReportDataModel>> GetProductsWithIngredientsAsync(CancellationToken ct);
Task<List<ProductionDataModel>> GetDataProductionsByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<List<WorkerSalaryByPeriodDataModel>> GetDataSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<Stream> CreateDocumentProductionsByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<Stream> CreateDocumentProductsWithIngredientsAsync(CancellationToken ct);
Task<Stream> CreateDocumentSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
}

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace SladkieBulkiContrakts.BusinessLogicsContracts;
internal interface ISalaryBusinessLogicContract
public interface ISalaryBusinessLogicContract
{
List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate);
List<SalaryDataModel> GetAllSalariesByPeriodByWorker(DateTime fromDate, DateTime toDate, string workerId);

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace SladkieBulkiContrakts.BusinessLogicsContracts;
internal interface IWorkerBusinessLogicContract
public interface IWorkerBusinessLogicContract
{
List<WorkerDataModel> GetAllWorkers(bool onlyActive = true);
List<WorkerDataModel> GetAllWorkersByPost(string postId, bool onlyActive = true);

View File

@@ -1,7 +1,5 @@
using Microsoft.Extensions.Localization;
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Infrastructure;
using SladkieBulkiContrakts.Resources;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -10,24 +8,24 @@ using System.Threading.Tasks;
namespace SladkieBulkiContrakts.DataModels;
internal class IngredientDataModel(string id, string NameIngredients, string sizeInit, double initPrice) : IValidation
public class IngredientDataModel(string id, string NameIngredients, string sizeInit, double initPrice) : IValidation
{
public string Id { get; private set; } = id;
public string NameIngredients { get; private set; } = NameIngredients;
public string SizeInit { get; private set; } = sizeInit;
public double InitPrice { get; private set; } = initPrice;
public void Validate(IStringLocalizer<Messages> localizer)
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField*"], "Id"));
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
throw new ValidationException("The value in the field Id is not a unique identifier");
if (NameIngredients.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField*"], "NameIngredients"));
throw new ValidationException("Field NameIngredients is empty");
if (SizeInit.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField*"], "SizeInit"));
throw new ValidationException("Field SizeInit is empty");
if (InitPrice <= 0)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "InitPrice"));
throw new ValidationException("Field InitPrice must be greater than zero");
}
}

View File

@@ -1,7 +1,5 @@
using Microsoft.Extensions.Localization;
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Infrastructure;
using SladkieBulkiContrakts.Resources;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -10,18 +8,18 @@ using System.Threading.Tasks;
namespace SladkieBulkiContrakts.DataModels;
internal class IngredientHistoryDataModel(string productId, double oldPrice) : IValidation
public class IngredientHistoryDataModel(string productId, double oldPrice) : IValidation
{
public string IngredienId { get; private set; } = productId;
public double OldPrice { get; private set; } = oldPrice;
public DateTime ChangeDate { get; private set; } = DateTime.UtcNow;
public void Validate(IStringLocalizer<Messages> localizer)
public void Validate()
{
if (IngredienId.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField*"], "IngredienId"));
throw new ValidationException("Field IngredienId is empty");
if (!IngredienId.IsGuid())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "IngredienId"));
throw new ValidationException("The value in the field IngredienId is not a unique identifier");
if (OldPrice <= 0)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "OldPrice"));
throw new ValidationException("Field OldPrice is less than or equal to 0");
}
}

View File

@@ -10,12 +10,10 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.Extensions.Localization;
using SladkieBulkiContrakts.Resources;
namespace SladkieBulkiContrakts.DataModels;
internal class PostDataModel(string postId, string postName, PostType postType, PostConfiguration configuration) : IValidation
public class PostDataModel(string postId, string postName, PostType postType, PostConfiguration configuration) : IValidation
{
public string Id { get; private set; } = postId;
@@ -39,24 +37,24 @@ internal class PostDataModel(string postId, string postName, PostType postType,
}
}
public void Validate(IStringLocalizer<Messages> localizer)
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
throw new ValidationException("The value in the field Id is not a unique identifier");
if (PostName.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "PostName"));
throw new ValidationException("Field PostName is empty");
if (PostType == PostType.None)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "PostType"));
throw new ValidationException("Field PostType is empty");
if (ConfigurationModel is null)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotInitialized"], "ConfigurationModel"));
throw new ValidationException("Field ConfigurationModel is not initialized");
if (ConfigurationModel!.Rate <= 0)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Rate"));
throw new ValidationException("Field Rate is less or equal zero");
}
}

View File

@@ -1,9 +1,7 @@
using Microsoft.Extensions.Localization;
using SladkieBulkiContrakts.Enums;
using SladkieBulkiContrakts.Enums;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Infrastructure;
using SladkieBulkiContrakts.Resources;
using System.Collections.Generic;
using System.Diagnostics;
@@ -11,7 +9,7 @@ namespace SladkieBulkiContrakts.DataModels;
internal class ProductDataModel : IValidation
public class ProductDataModel : IValidation
{
public string Id { get; private set; }
public string Name { get; private set; }
@@ -21,6 +19,7 @@ internal class ProductDataModel : IValidation
public double UnitPrice { get; private set; }
public bool IsDeleted { get; private set; }
// 👇 Пустой конструктор для сериализации, EF, AutoMapper
public ProductDataModel()
{
Ingredients = new List<ProductIngredientDataModel>();
@@ -47,31 +46,27 @@ internal class ProductDataModel : IValidation
// Валидация
public void Validate(IStringLocalizer<Messages> localizer)
{
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField*"], "Id"));
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
throw new ValidationException("The value in the field Id is not a unique identifier");
if (Name.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField*"], "Name"));
throw new ValidationException("Field Name is empty");
if (Description.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField*"], "Description"));
throw new ValidationException("Field Description is empty");
if (ProductType == ProductType.None)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField*"], "ProductType"));
throw new ValidationException("Field ProductType is empty");
if (UnitPrice <= 0)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "InitPrice"));
throw new ValidationException("Field UnitPrice must be greater than zero");
if (Ingredients is null)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotInitialized"], "Ingredients"));
if (Ingredients.Count == 0)
throw new ValidationException(localizer["ValidationExceptionMessageNoIngredientsInProduct"]);
}
if (Ingredients == null || Ingredients.Count == 0)
throw new ValidationException("No ingredients defined");
}
}

View File

@@ -1,7 +1,5 @@
using Microsoft.Extensions.Localization;
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Infrastructure;
using SladkieBulkiContrakts.Resources;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -10,20 +8,19 @@ using System.Threading.Tasks;
namespace SladkieBulkiContrakts.DataModels;
internal class ProductHistoryDataModel(string productId, double oldPrice): IValidation
public class ProductHistoryDataModel(string productId, double oldPrice): IValidation
{
public string ProductId { get; private set; } = productId;
public double OldPrice { get; private set; } = oldPrice;
public DateTime ChangeDate { get; private set; } = DateTime.UtcNow;
public void Validate(IStringLocalizer<Messages> localizer)
public void Validate()
{
if (ProductId.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField*"], "ProductId"));
throw new ValidationException("Field ProductId is empty");
if (!ProductId.IsGuid())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "ProductId"));
throw new ValidationException("The value in the field ProductId is not a unique identifier");
if (OldPrice <= 0)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "OldPrice"));
throw new ValidationException("Field OldPrice is less than or equal to 0");
}
}

View File

@@ -1,34 +1,29 @@
using Microsoft.Extensions.Localization;
using SladkieBulkiContrakts.Enums;
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Infrastructure;
using SladkieBulkiContrakts.Resources;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace SladkieBulkiContrakts.DataModels;
internal class ProductIngredientDataModel(string productId, string ingredientId, int count) : IValidation
public class ProductIngredientDataModel(string productId, string ingredientId, int count) : IValidation
{
public string ProductId { get; private set; } = productId;
public string IngredientId { get; private set; } = ingredientId;
public int Count { get; private set; } = count;
public void Validate(IStringLocalizer<Messages> localizer)
public void Validate()
{
if (ProductId.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField*"], "ProductId"));
throw new ValidationException("Field ProductId is empty");
if (!ProductId.IsGuid())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "ProductId"));
throw new ValidationException("The value in the field ProductId is not a unique identifier");
if (IngredientId.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField*"], "IngredientId"));
throw new ValidationException("Field IngredientId is empty");
if (!IngredientId.IsGuid())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "IngredientId"));
throw new ValidationException("The value in the field IngredientId is not a unique identifier");
if (Count <= 0)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Count"));
throw new ValidationException("Field Count is less than or equal to 0");
}
}

View File

@@ -1,26 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.DataModels;
public class ProductWithIngredientsReportDataModel
{
public string ProductId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string ProductType { get; set; }
public double UnitPrice { get; set; }
public List<IngredientInProductDto> Ingredients { get; set; } = new();
}
public class IngredientInProductDto
{
public string IngredientId { get; set; }
public string NameIngredients { get; set; }
public string SizeUnit { get; set; } // мера измерения
public double InitPrice { get; set; }
public int Count { get; set; } // количество ингредиента в продукте
}

View File

@@ -1,38 +1,34 @@
using Microsoft.Extensions.Localization;
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Infrastructure;
using SladkieBulkiContrakts.Resources;
internal class ProductionDataModel(string id, DateTime productionDate, int count, double sum, string workerId, string productId) : IValidation
public class ProductionDataModel(string id, DateTime productionDate, int count, double sum, string workerId, string productId) : IValidation
{
public string Id { get; private set; } = id;
public DateTime ProductionDate { get; private set; } = productionDate.ToUniversalTime();
public DateTime ProductionDate { get; private set; } = productionDate;
public int Count { get; private set; } = count;
public double Sum { get; private set; } = sum;
public string WorkerId { get; private set; } = workerId;
public string ProductId { get; private set; } = productId;
public void Validate(IStringLocalizer<Messages> localizer)
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField*"], "Id"));
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
throw new ValidationException("The value in the field Id is not a unique identifier");
if (ProductionDate > DateTime.Now)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageDateNotFuture"], "ProductionDate"));
throw new ValidationException("ProductionDate cannot be in the future");
if (Count <= 0)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Count"));
throw new ValidationException("Field Count must be greater than zero");
if (WorkerId.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField*"], "WorkerId"));
throw new ValidationException("Field WorkerId is empty");
if (!WorkerId.IsGuid())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "WorkerId"));
throw new ValidationException("The value in the field WorkerId is not a unique identifier");
if (ProductId.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField*"], "ProductId"));
throw new ValidationException("Field ProductId is empty");
if (!ProductId.IsGuid())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "ProductId"));
throw new ValidationException("The value in the field ProductId is not a unique identifier");
if (Sum <= 0)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Sum"));
throw new ValidationException("Field Sum is less than or equal to 0");
}
}

View File

@@ -1,7 +1,5 @@
using Microsoft.Extensions.Localization;
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Infrastructure;
using SladkieBulkiContrakts.Resources;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -10,25 +8,25 @@ using System.Threading.Tasks;
namespace SladkieBulkiContrakts.DataModels;
internal class SalaryDataModel(string workerId, DateTime salaryDate, double workerSalary) : IValidation
public class SalaryDataModel(string workerId, DateTime salaryDate, double workerSalary) : IValidation
{
private readonly WorkerDataModel? _worker;
public string WorkerId { get; private set; } = workerId;
public DateTime SalaryDate { get; private set; } = salaryDate.ToUniversalTime();
public DateTime SalaryDate { get; private set; } = salaryDate;
public double WorkerSalary { get; private set; } = workerSalary;
public string WorkerFIO => _worker?.FIO ?? string.Empty;
public SalaryDataModel(string workerId, DateTime salaryDate, double workerSalary, WorkerDataModel? worker) : this(workerId, salaryDate, workerSalary)
{
_worker = worker;
}
public void Validate(IStringLocalizer<Messages> localizer)
public void Validate()
{
if (WorkerId.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField*"], "WorkerId"));
throw new ValidationException("Field WorkerId is empty");
if (!WorkerId.IsGuid())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "WorkerId"));
throw new ValidationException("The value in the field WorkerId is not a unique identifier");
if (WorkerSalary <= 0)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "WorkerSalary"));
throw new ValidationException("Field Salary is less than or equal to 0");
}
}

View File

@@ -10,19 +10,17 @@ using System.Xml;
using System.Text.RegularExpressions;
using System.Numerics;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Localization;
using SladkieBulkiContrakts.Resources;
namespace SladkieBulkiContrakts.DataModels;
internal class WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted, string email) : IValidation
public class WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted, string email) : IValidation
{
private readonly PostDataModel? _post;
public string Id { get; private set; } = id;
public string FIO { get; private set; } = fio;
public string PostId { get; private set; } = postId;
public DateTime BirthDate { get; private set; } = birthDate.ToUniversalTime();
public DateTime EmploymentDate { get; private set; } = employmentDate.ToUniversalTime();
public DateTime BirthDate { get; private set; } = birthDate;
public DateTime EmploymentDate { get; private set; } = employmentDate;
public bool IsDeleted { get; private set; } = isDeleted;
public string Email { get; private set; } = email;
@@ -34,36 +32,26 @@ internal class WorkerDataModel(string id, string fio, string postId, DateTime bi
public WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate, string email) : this(id, fio, postId, birthDate, employmentDate, false, email) { }
public void Validate(IStringLocalizer<Messages> localizer)
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField*"], "Id"));
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
throw new ValidationException("The value in the field Id is not a unique identifier");
if (FIO.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField*"], "FIO"));
throw new ValidationException("Field FIO is empty");
if (PostId.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField*"], "PostId"));
throw new ValidationException("Field PostId is empty");
if (!PostId.IsGuid())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "PostId"));
throw new ValidationException("The value in the field PostId is not a unique identifier");
if (BirthDate.Date > DateTime.Now.AddYears(-16).Date)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageMinorsBirthDate"], BirthDate.ToShortDateString()));
throw new ValidationException($"Minors cannot be hired (BirthDate = { BirthDate.ToShortDateString() })");
if (EmploymentDate.Date < BirthDate.Date)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmploymentDateAndBirthDate"],
EmploymentDate.ToShortDateString(), BirthDate.ToShortDateString()));
throw new ValidationException("The date of employment cannot be less than the date of birth");
if ((EmploymentDate - BirthDate).TotalDays / 365 < 16) // EmploymentDate.Year - BirthDate.Year
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageMinorsEmploymentDate"],
EmploymentDate.ToShortDateString(), BirthDate.ToShortDateString()));
throw new ValidationException($"Minors cannot be hired (EmploymentDate - { EmploymentDate.ToShortDateString() }, BirthDate - { BirthDate.ToShortDateString()})");
if (!Regex.IsMatch(Email, @"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"))
throw new ValidationException((localizer["ValidationExceptionMessageIncorrectEmail"]));
throw new ValidationException("Field Email is not a email");
}
}

View File

@@ -1,18 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.DataModels;
public class WorkerSalaryByPeriodDataModel
{
public required string WorkerFIO { get; set; }
public double TotalSalary { get; set; }
public DateTime FromPeriod { get; set; }
public DateTime ToPeriod { get; set; }
}

View File

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

View File

@@ -1,6 +1,4 @@
using Microsoft.Extensions.Localization;
using SladkieBulkiContrakts.Resources;
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -8,10 +6,13 @@ using System.Threading.Tasks;
namespace SladkieBulkiContrakts.Exceptions;
internal class ElementExistsException(string paramName, string paramValue, IStringLocalizer<Messages> localizer) :
Exception(string.Format(localizer["ElementExistsExceptionMessage"], paramValue, paramName))
public class ElementExistsException : Exception
{
public string ParamName { get; private set; } = paramName;
public string ParamValue { get; private set; } = paramValue;
}
public string ParamName { get; private set; }
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;
}
}

View File

@@ -1,6 +1,4 @@
using Microsoft.Extensions.Localization;
using SladkieBulkiContrakts.Resources;
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -8,8 +6,12 @@ using System.Threading.Tasks;
namespace SladkieBulkiContrakts.Exceptions;
internal class ElementNotFoundException(string value, IStringLocalizer<Messages> localizer) :
Exception(string.Format(localizer["ElementNotFoundExceptionMessage"], value))
public class ElementNotFoundException : Exception
{
public string Value { get; private set; } = value;
public string Value { get; private set; }
public ElementNotFoundException(string value) : base($"Element not found at value = { value}")
{
Value = value;
}
}

View File

@@ -1,11 +1,10 @@
using Microsoft.Extensions.Localization;
using SladkieBulkiContrakts.Resources;
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
internal class IncorrectDatesException(DateTime start, DateTime end, IStringLocalizer<Messages> localizer) :
Exception(string.Format(localizer["IncorrectDatesExceptionMessage"], start.ToShortDateString(), end.ToShortDateString()))
{ }
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}") { }
}

View File

@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.Exceptions;
public class NullListException : Exception
{
public NullListException() : base("The returned list is null") { }
}

View File

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

View File

@@ -5,4 +5,6 @@ using System.Text;
using System.Threading.Tasks;
public class ValidationException(string message) : Exception(message)
{ }
{
}

View File

@@ -9,4 +9,5 @@ namespace SladkieBulkiContrakts.Infrastructure;
public interface IConfigurationSalary
{
double ExtraSaleSum { get; }
int MaxParallelThreads { get; }
}

View File

@@ -1,6 +1,4 @@
using Microsoft.Extensions.Localization;
using SladkieBulkiContrakts.Resources;
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -8,7 +6,8 @@ using System.Threading.Tasks;
namespace SladkieBulkiContrakts.Infrastructure;
internal interface IValidation
public interface IValidation
{
void Validate(IStringLocalizer<Messages> localizer);
}
void Validate();
}

View File

@@ -14,8 +14,6 @@ public class OperationResponse
protected HttpStatusCode StatusCode { get; set; }
protected object? Result { get; set; }
protected string? FileName { get; set; }
public IActionResult GetResponse(HttpRequest request, HttpResponse response)
{
@@ -28,21 +26,12 @@ public class OperationResponse
{
return new StatusCodeResult((int)StatusCode);
}
if (Result is Stream stream)
{
return new FileStreamResult(stream, "application/octet-stream")
{
FileDownloadName = FileName
};
}
return new ObjectResult(Result);
}
protected static TResult OK<TResult, TData>(TData data) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.OK, Result = data };
protected static TResult OK<TResult, TData>(TData data, string fileName) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.OK, Result = data, FileName = fileName };
protected static TResult NoContent<TResult>() where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.NoContent };
protected static TResult BadRequest<TResult>(string? errorMessage = null) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.BadRequest, Result = errorMessage };

View File

@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@@ -12,8 +11,5 @@ public class PostConfiguration
public virtual string Type => nameof(PostConfiguration);
public double Rate { get; set; }
public string CultureName { get; set; } = CultureInfo.CurrentCulture.Name;
}

View File

@@ -1,423 +0,0 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace SladkieBulkiContrakts.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("SladkieBulkiContrakts.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 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 DocumentDocCaptionCount {
get {
return ResourceManager.GetString("DocumentDocCaptionCount", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Описание.
/// </summary>
internal static string DocumentDocCaptionDesc {
get {
return ResourceManager.GetString("DocumentDocCaptionDesc", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Ингредиенты.
/// </summary>
internal static string DocumentDocCaptionIngred {
get {
return ResourceManager.GetString("DocumentDocCaptionIngred", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Цена.
/// </summary>
internal static string DocumentDocCaptionPrice {
get {
return ResourceManager.GetString("DocumentDocCaptionPrice", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Тип.
/// </summary>
internal static string DocumentDocCaptionProdType {
get {
return ResourceManager.GetString("DocumentDocCaptionProdType", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Продукт.
/// </summary>
internal static string DocumentDocCaptionProduct {
get {
return ResourceManager.GetString("DocumentDocCaptionProduct", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Единица измерения.
/// </summary>
internal static string DocumentDocCaptionSize {
get {
return ResourceManager.GetString("DocumentDocCaptionSize", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Цена за единицу.
/// </summary>
internal static string DocumentDocCaptionUnitPrice {
get {
return ResourceManager.GetString("DocumentDocCaptionUnitPrice", 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 DocumentExcelCaptionSum {
get {
return ResourceManager.GetString("DocumentExcelCaptionSum", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Всего.
/// </summary>
internal static string DocumentExcelCaptionTotal {
get {
return ResourceManager.GetString("DocumentExcelCaptionTotal", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Работник.
/// </summary>
internal static string DocumentExcelCaptionWorkerFIO {
get {
return ResourceManager.GetString("DocumentExcelCaptionWorkerFIO", 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 StorageExceptionMessage {
get {
return ResourceManager.GetString("StorageExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на {0} не может быть в будущем.
/// </summary>
internal static string ValidationExceptionMessageDateNotFuture {
get {
return ResourceManager.GetString("ValidationExceptionMessageDateNotFuture", 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>
/// Ищет локализованную строку, похожую на Значение в поле email не является email.
/// </summary>
internal static string ValidationExceptionMessageIncorrectEmail {
get {
return ResourceManager.GetString("ValidationExceptionMessageIncorrectEmail", 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>
/// Ищет локализованную строку, похожую на Значение в поле {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

@@ -1,240 +0,0 @@
<?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="AdapterMessageElementDeletedException" xml:space="preserve">
<value>Element nach Daten: {0} wurde gelöscht</value>
</data>
<data name="AdapterMessageElementNotFoundException" xml:space="preserve">
<value>Es wurde kein Datenelement gefunden: {0}</value>
</data>
<data name="AdapterMessageEmptyDate" xml:space="preserve">
<value>Die Daten sind leer</value>
</data>
<data name="AdapterMessageIncorrectDatesException" xml:space="preserve">
<value>Falsche Datumsangaben: {0}</value>
</data>
<data name="AdapterMessageInvalidOperationException" xml:space="preserve">
<value>Fehler bei der Datenverarbeitung: {0}</value>
</data>
<data name="AdapterMessageStorageException" xml:space="preserve">
<value>Fehler beim Arbeiten mit dem Datenspeicher: {0}</value>
</data>
<data name="AdapterMessageValidationException" xml:space="preserve">
<value>Ungültige Daten wurden übergeben: {0}</value>
</data>
<data name="DocumentDocCaptionComponent" xml:space="preserve">
<value>Komponente</value>
</data>
<data name="DocumentDocCaptionDate" xml:space="preserve">
<value>Datum</value>
</data>
<data name="DocumentDocCaptionPrice" xml:space="preserve">
<value>Preis</value>
</data>
<data name="DocumentDocHeader" xml:space="preserve">
<value>Geschichte der Komponentenpreise</value>
</data>
<data name="DocumentDocSubHeader" xml:space="preserve">
<value>Erstellt am Datum {0}</value>
</data>
<data name="DocumentExcelCaptionComponent" xml:space="preserve">
<value>Komponente</value>
</data>
<data name="DocumentExcelCaptionCount" xml:space="preserve">
<value>Anzahl</value>
</data>
<data name="DocumentExcelCaptionDate" xml:space="preserve">
<value>Datum</value>
</data>
<data name="DocumentExcelCaptionDiscount" xml:space="preserve">
<value>Preisnachlaß</value>
</data>
<data name="DocumentExcelCaptionSum" xml:space="preserve">
<value>Summe</value>
</data>
<data name="DocumentExcelCaptionTotal" xml:space="preserve">
<value>Insgesamt</value>
</data>
<data name="DocumentExcelCaptionWorker" xml:space="preserve">
<value>Verkäufer</value>
</data>
<data name="DocumentExcelHeader" xml:space="preserve">
<value>Umsatz pro Zeitraum</value>
</data>
<data name="DocumentExcelSubHeader" xml:space="preserve">
<value>von {0} bis zum{1}</value>
</data>
<data name="DocumentPdfDiagramCaption" xml:space="preserve">
<value>Anrechnungen</value>
</data>
<data name="DocumentPdfHeader" xml:space="preserve">
<value>Rabattliste</value>
</data>
<data name="DocumentPdfSubHeader" xml:space="preserve">
<value>für den Zeitraum {0} bis {1}</value>
</data>
<data name="ElementDeletedExceptionMessage" xml:space="preserve">
<value>Das gelöschte Element kann nicht geändert werden (ID: {0})</value>
</data>
<data name="ElementExistsExceptionMessage" xml:space="preserve">
<value>Es ist bereits ein Element mit dem Wert vorhanden {0} des Parameters {1} </value>
</data>
<data name="ElementNotFoundExceptionMessage" xml:space="preserve">
<value>Element wurde nicht durch Wert = {0} gefunden</value>
</data>
<data name="IncorrectDatesExceptionMessage" xml:space="preserve">
<value>Das Enddatum muss später als das Startdatum sein. Startdatum: {0}. Enddatum: {1}</value>
</data>
<data name="NotEnoughDataToProcessExceptionMessage" xml:space="preserve">
<value>Zu verarbeitende Daten sind nicht ausreichend: {0}</value>
</data>
<data name="NotFoundDataMessage" xml:space="preserve">
<value>Keine Daten gefunden</value>
</data>
<data name="StorageExceptionMessage" xml:space="preserve">
<value>Fehler beim Ausführen im Speicher: {0}</value>
</data>
<data name="ValidationExceptionMessageEmploymentDateAndBirthDate" xml:space="preserve">
<value>Das Beschäftigungsdatum darf nicht vor dem Geburtsdatum liegen ({0}, {1})</value>
</data>
<data name="ValidationExceptionMessageEmptyField" xml:space="preserve">
<value>Der Wert im Feld "{0}" ist leer</value>
</data>
<data name="ValidationExceptionMessageIncorrectPhoneNumber" xml:space="preserve">
<value>Der Wert im Feld Telefonnummer ist keine Telefonnummer</value>
</data>
<data name="ValidationExceptionMessageLessOrEqualZero" xml:space="preserve">
<value>Der Wert im Feld {0} ist kleiner oder gleich 0</value>
</data>
<data name="ValidationExceptionMessageMinorsBirthDate" xml:space="preserve">
<value>Minderjährige können nicht eingestellt werden (Geburtsdatum: {0})</value>
</data>
<data name="ValidationExceptionMessageMinorsEmploymentDate" xml:space="preserve">
<value>Minderjährige können nicht eingestellt werden (Beschäftigungsdatum {0}, Geburtsdatum: {1})</value>
</data>
<data name="ValidationExceptionMessageNoComponentsInSale" xml:space="preserve">
<value>Es muss mindestens ein Komponente zum Verkauf stehen</value>
</data>
<data name="ValidationExceptionMessageNotAId" xml:space="preserve">
<value>Der Wert im Feld "{0}" ist kein eindeutiger Bezeichnertyp</value>
</data>
<data name="ValidationExceptionMessageNotInitialized" xml:space="preserve">
<value>Der Wert im Feld "{0}" wurde nicht initialisiert</value>
</data>
</root>

View File

@@ -1,240 +0,0 @@
<?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="AdapterMessageElementDeletedException" xml:space="preserve">
<value>Element by data: {0} was deleted</value>
</data>
<data name="AdapterMessageElementNotFoundException" xml:space="preserve">
<value>Not found element by data: {0}</value>
</data>
<data name="AdapterMessageEmptyDate" xml:space="preserve">
<value>Data is empty</value>
</data>
<data name="AdapterMessageIncorrectDatesException" xml:space="preserve">
<value>Incorrect dates: {0}</value>
</data>
<data name="AdapterMessageStorageException" xml:space="preserve">
<value>Error while working with data storage: {0}</value>
</data>
<data name="AdapterMessageValidationException" xml:space="preserve">
<value>Incorrect data transmitted: {0}</value>
</data>
<data name="DocumentDocCaptionCount" xml:space="preserve">
<value>Count</value>
</data>
<data name="DocumentDocCaptionDesc" xml:space="preserve">
<value>Description</value>
</data>
<data name="DocumentDocCaptionIngred" xml:space="preserve">
<value>Ingredients</value>
</data>
<data name="DocumentDocCaptionPrice" xml:space="preserve">
<value>Price</value>
</data>
<data name="DocumentDocCaptionProdType" xml:space="preserve">
<value>ProductType</value>
</data>
<data name="DocumentDocCaptionProduct" xml:space="preserve">
<value>Product</value>
</data>
<data name="DocumentDocCaptionSize" xml:space="preserve">
<value>SizeInit</value>
</data>
<data name="DocumentDocCaptionUnitPrice" xml:space="preserve">
<value>UnitPrice</value>
</data>
<data name="DocumentDocHeader" xml:space="preserve">
<value>ProductsWithIngredients</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="DocumentExcelCaptionSum" xml:space="preserve">
<value>Sum</value>
</data>
<data name="DocumentExcelCaptionTotal" xml:space="preserve">
<value>Total</value>
</data>
<data name="DocumentExcelCaptionWorkerFIO" xml:space="preserve">
<value>Worker</value>
</data>
<data name="DocumentExcelHeader" xml:space="preserve">
<value>Productions for the period</value>
</data>
<data name="DocumentExcelSubHeader" xml:space="preserve">
<value>from {0} to {1}</value>
</data>
<data name="DocumentPdfDiagramCaption" xml:space="preserve">
<value>Accruals</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="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="StorageExceptionMessage" xml:space="preserve">
<value>Error while working in storage: {0}</value>
</data>
<data name="ValidationExceptionMessageDateNotFuture" xml:space="preserve">
<value>{0} cannot future</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="ValidationExceptionMessageEmptyField" xml:space="preserve">
<value>The value in field {0} is empty</value>
</data>
<data name="ValidationExceptionMessageIncorrectEmail" xml:space="preserve">
<value>The value in the email field is not a email</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="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="ValidationExceptionMessageNotAId" xml:space="preserve">
<value>The value in the {0} field is not a unique identifier type.</value>
</data>
<data name="ValidationExceptionMessageNotInitialized" xml:space="preserve">
<value>The value in field {0} is not initialized</value>
</data>
</root>

View File

@@ -1,240 +0,0 @@
<?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="AdapterMessageElementDeletedException" xml:space="preserve">
<value>Элемент по данным: {0} был удален</value>
</data>
<data name="AdapterMessageElementNotFoundException" xml:space="preserve">
<value>Не найден элемент по данным: {0}</value>
</data>
<data name="AdapterMessageEmptyDate" xml:space="preserve">
<value>Данные пусты</value>
</data>
<data name="AdapterMessageIncorrectDatesException" xml:space="preserve">
<value>Неправильные даты: {0}</value>
</data>
<data name="AdapterMessageStorageException" xml:space="preserve">
<value>Ошибка при работе с хранилищем данных: {0}</value>
</data>
<data name="AdapterMessageValidationException" xml:space="preserve">
<value>Переданы неверные данные: {0}</value>
</data>
<data name="DocumentDocCaptionCount" xml:space="preserve">
<value>Кол-во</value>
</data>
<data name="DocumentDocCaptionDesc" xml:space="preserve">
<value>Описание</value>
</data>
<data name="DocumentDocCaptionIngred" xml:space="preserve">
<value>Ингредиенты</value>
</data>
<data name="DocumentDocCaptionPrice" xml:space="preserve">
<value>Цена</value>
</data>
<data name="DocumentDocCaptionProdType" xml:space="preserve">
<value>Тип</value>
</data>
<data name="DocumentDocCaptionProduct" xml:space="preserve">
<value>Продукт</value>
</data>
<data name="DocumentDocCaptionSize" xml:space="preserve">
<value>Единица измерения</value>
</data>
<data name="DocumentDocCaptionUnitPrice" 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="DocumentExcelCaptionSum" xml:space="preserve">
<value>Сумма</value>
</data>
<data name="DocumentExcelCaptionTotal" xml:space="preserve">
<value>Всего</value>
</data>
<data name="DocumentExcelCaptionWorkerFIO" 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="DocumentPdfDiagramCaption" xml:space="preserve">
<value>Начисления</value>
</data>
<data name="DocumentPdfHeader" xml:space="preserve">
<value>Зарплатная ведомость</value>
</data>
<data name="DocumentPdfSubHeader" xml:space="preserve">
<value>за период с {0} по {1}</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="StorageExceptionMessage" xml:space="preserve">
<value>Ошибка при работе в хранилище: {0}</value>
</data>
<data name="ValidationExceptionMessageDateNotFuture" xml:space="preserve">
<value>{0} не может быть в будущем</value>
</data>
<data name="ValidationExceptionMessageEmploymentDateAndBirthDate" xml:space="preserve">
<value>Дата трудоустройства не может быть раньше даты рождения ({0}, {1})</value>
</data>
<data name="ValidationExceptionMessageEmptyField" xml:space="preserve">
<value>Значение в поле {0} пусто</value>
</data>
<data name="ValidationExceptionMessageIncorrectEmail" xml:space="preserve">
<value>Значение в поле email не является email</value>
</data>
<data name="ValidationExceptionMessageLessOrEqualZero" xml:space="preserve">
<value>Значение в поле {0} меньше или равно 0</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="ValidationExceptionMessageNotAId" xml:space="preserve">
<value>Значение в поле {0} не является типом уникального идентификатора</value>
</data>
<data name="ValidationExceptionMessageNotInitialized" xml:space="preserve">
<value>Значение в поле {0} не проиницализировано</value>
</data>
</root>

View File

@@ -10,31 +10,6 @@
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.3.0" />
<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.5" />
</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="SladkieBulkiBusinessLogic" />
<InternalsVisibleTo Include="SladkieBulkiDatabase" />
<InternalsVisibleTo Include="SladkieBulkiWedApi" />
<InternalsVisibleTo Include="SladkieBulkiTests" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
</Project>

View File

@@ -7,12 +7,10 @@ using System.Threading.Tasks;
namespace SladkieBulkiContrakts.StoragesContarcts;
internal interface IIngredientStorageContract
public interface IIngredientStorageContract
{
List<IngredientDataModel> GetList();
Task<List<IngredientDataModel>> GetListAsync(CancellationToken ct);
// Получить ингредиенты по единице измерения
List<IngredientDataModel>? GetElementBySizeUnit(string sizeInit);

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace SladkieBulkiContrakts.StoragesContarcts;
internal interface IPostStorageContract
public interface IPostStorageContract
{
List<PostDataModel> GetList();
List<PostDataModel> GetPostWithHistory(string postId);

View File

@@ -7,10 +7,9 @@ using System.Threading.Tasks;
namespace SladkieBulkiContrakts.StoragesContarcts;
internal interface IProductStorageContract
public interface IProductStorageContract
{
List<ProductDataModel> GetList(bool onlyActive = true);
Task<List<ProductDataModel>> GetListAsync(CancellationToken ct);
List<ProductHistoryDataModel> GetHistoryByProductId(string productId);
ProductDataModel? GetElementById(string id);
ProductDataModel? GetElementByName(string name);

View File

@@ -7,11 +7,9 @@ using System.Threading.Tasks;
namespace SladkieBulkiContrakts.StoragesContarcts;
internal interface IProductionStorageContract
public interface IProductionStorageContract
{
List<ProductionDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? workerId = null, string? productId = null);
Task<List<ProductionDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct);
ProductionDataModel? GetElementById(string id);
void AddElement(ProductionDataModel productionDataModel);
void DelElement(string id);

View File

@@ -7,10 +7,8 @@ using System.Threading.Tasks;
namespace SladkieBulkiContrakts.StoragesContarcts;
internal interface ISalaryStorageContract
public interface ISalaryStorageContract
{
List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? workerId = null);
Task<List<SalaryDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct);
void AddElement(SalaryDataModel salaryDataModel);
}

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace SladkieBulkiContrakts.StoragesContarcts;
internal interface IWorkerStorageContract
public interface IWorkerStorageContract
{
List<WorkerDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null);
WorkerDataModel? GetElementById(string id);

View File

@@ -1,24 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.ViewModels;
public class ProductWithIngredientsViewModel
{
public required string Name { get; set; }
public required string Description { get; set; }
public required string ProductType { get; set; }
public double UnitPrice { get; set; }
public required List<IngredientInProductViewModel> Ingredients { get; set; }
}
public class IngredientInProductViewModel
{
public required string NameIngredients { get; set; }
public required string SizeUnit { get; set; }
public double InitPrice { get; set; }
public int Count { get; set; }
}

View File

@@ -14,6 +14,5 @@ public class ProductionViewModel
public double Sum { get; set; }
public string WorkerId { get; set; } = default!;
public string ProductId { get; set; } = default!;
public string Name { get; set; } = default!;
}

View File

@@ -1,18 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.ViewModels;
public class WorkerSalaryByPeriodViewModel
{
public required string WorkerFIO { get; set; }
public double TotalSalary { get; set; }
public DateTime FromPeriod { get; set; }
public DateTime ToPeriod { get; set; }
}

View File

@@ -1,10 +1,8 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.Resources;
using SladkieBulkiContrakts.StoragesContarcts;
using SladkieBulkiDatabase.Models;
using System;
@@ -19,9 +17,8 @@ internal class IngredientStorageContract : IIngredientStorageContract
{
private readonly SladkieBulkiDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public IngredientStorageContract(SladkieBulkiDbContext sladkieBulkiDbContext, IStringLocalizer<Messages> localizer)
public IngredientStorageContract(SladkieBulkiDbContext sladkieBulkiDbContext)
{
_dbContext = sladkieBulkiDbContext;
var config = new MapperConfiguration(cfg =>
@@ -30,7 +27,6 @@ internal class IngredientStorageContract : IIngredientStorageContract
cfg.CreateMap<IngredientDataModel, Ingredient>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<IngredientDataModel> GetList()
@@ -42,31 +38,10 @@ internal class IngredientStorageContract : IIngredientStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
public async Task<List<IngredientDataModel>> GetListAsync(CancellationToken ct)
{
try
{
return [.. await _dbContext.Ingredients
.Select(x => _mapper.Map<IngredientDataModel>(x))
.ToListAsync(ct)];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
}
}
public IngredientDataModel? GetElementById(string id)
{
try
@@ -76,7 +51,7 @@ internal class IngredientStorageContract : IIngredientStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -89,7 +64,7 @@ internal class IngredientStorageContract : IIngredientStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -104,7 +79,7 @@ internal class IngredientStorageContract : IIngredientStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -118,17 +93,17 @@ internal class IngredientStorageContract : IIngredientStorageContract
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", ingredientDataModel.Id, _localizer);
throw new ElementExistsException("Id", ingredientDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Ingredients_NameIngridients" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("NameIngredients", ingredientDataModel.NameIngredients, _localizer);
throw new ElementExistsException("NameIngredients", ingredientDataModel.NameIngredients);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -137,7 +112,7 @@ internal class IngredientStorageContract : IIngredientStorageContract
{
try
{
var element = GetIngredientById(ingredientDataModel.Id) ?? throw new ElementNotFoundException(ingredientDataModel.Id, _localizer);
var element = GetIngredientById(ingredientDataModel.Id) ?? throw new ElementNotFoundException(ingredientDataModel.Id);
_dbContext.Ingredients.Update(_mapper.Map(ingredientDataModel, element));
_dbContext.SaveChanges();
}
@@ -149,12 +124,12 @@ internal class IngredientStorageContract : IIngredientStorageContract
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Ingredients_NameIngridients" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("NameIngredients", ingredientDataModel.NameIngredients, _localizer);
throw new ElementExistsException("NameIngredients", ingredientDataModel.NameIngredients);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}

View File

@@ -1,10 +1,8 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.Resources;
using SladkieBulkiContrakts.StoragesContarcts;
using SladkieBulkiDatabase.Models;
using System;
@@ -19,8 +17,8 @@ internal class PostStorageContract : IPostStorageContract
{
private readonly SladkieBulkiDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public PostStorageContract(SladkieBulkiDbContext dbContext, IStringLocalizer<Messages> localizer)
public PostStorageContract(SladkieBulkiDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
@@ -35,7 +33,6 @@ internal class PostStorageContract : IPostStorageContract
.ForMember(x => x.Configuration, x => x.MapFrom(src => src.ConfigurationModel));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<PostDataModel> GetList()
@@ -47,7 +44,7 @@ internal class PostStorageContract : IPostStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -60,7 +57,7 @@ internal class PostStorageContract : IPostStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -73,7 +70,7 @@ internal class PostStorageContract : IPostStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -86,7 +83,7 @@ internal class PostStorageContract : IPostStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -100,17 +97,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, _localizer);
throw new ElementExistsException("PostName", postDataModel.PostName);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostId_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostId", postDataModel.Id, _localizer);
throw new ElementExistsException("PostId", postDataModel.Id);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -121,10 +118,10 @@ internal class PostStorageContract : IPostStorageContract
var transaction = _dbContext.Database.BeginTransaction();
try
{
var element = GetPostById(postDataModel.Id) ?? throw new ElementNotFoundException(postDataModel.Id, _localizer);
var element = GetPostById(postDataModel.Id) ?? throw new ElementNotFoundException(postDataModel.Id);
if (!element.IsActual)
{
throw new ElementDeletedException(postDataModel.Id, _localizer);
throw new ElementDeletedException(postDataModel.Id);
}
element.IsActual = false;
_dbContext.SaveChanges();
@@ -142,7 +139,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, _localizer);
throw new ElementExistsException("PostName", postDataModel.PostName);
}
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
{
@@ -152,7 +149,7 @@ internal class PostStorageContract : IPostStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -160,10 +157,10 @@ internal class PostStorageContract : IPostStorageContract
{
try
{
var element = GetPostById(id) ?? throw new ElementNotFoundException(id, _localizer);
var element = GetPostById(id) ?? throw new ElementNotFoundException(id);
if (!element.IsActual)
{
throw new ElementDeletedException(id, _localizer);
throw new ElementDeletedException(id);
}
element.IsActual = false;
_dbContext.SaveChanges();
@@ -179,7 +176,7 @@ internal class PostStorageContract : IPostStorageContract
{
try
{
var element = GetPostById(id) ?? throw new ElementNotFoundException(id, _localizer);
var element = GetPostById(id) ?? throw new ElementNotFoundException(id);
element.IsActual = true;
_dbContext.SaveChanges();
}

View File

@@ -1,10 +1,8 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.Resources;
using SladkieBulkiContrakts.StoragesContarcts;
using SladkieBulkiDatabase.Models;
using System;
@@ -19,31 +17,21 @@ internal class ProductStorageContract : IProductStorageContract
{
private readonly SladkieBulkiDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public ProductStorageContract(SladkieBulkiDbContext dbContext, IStringLocalizer<Messages> localizer)
public ProductStorageContract(SladkieBulkiDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<ProductIngredient, ProductIngredientDataModel>();
cfg.CreateMap<ProductIngredientDataModel, ProductIngredient>();
cfg.CreateMap<Product, ProductDataModel>()
.ForMember(dest => dest.Ingredients,
opt => opt.MapFrom(src =>
src.ProductIngredients != null
? src.ProductIngredients.Select(pi => new ProductIngredientDataModel(
pi.ProductId,
pi.IngredientId,
pi.Count)).ToList()
: new List<ProductIngredientDataModel>()));
cfg.CreateMap<Product, ProductDataModel>();
cfg.CreateMap<ProductDataModel, Product>()
.ForMember(x => x.IsDeleted, x => x.MapFrom(src => false))
.ForMember(x => x.ProductIngredients, x => x.MapFrom(src => src.Ingredients));
cfg.CreateMap<ProductHistory, ProductHistoryDataModel>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
@@ -62,28 +50,10 @@ internal class ProductStorageContract : IProductStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
public async Task<List<ProductDataModel>> GetListAsync(CancellationToken ct)
{
try
{
return [.. await _dbContext.Products
.Include(x => x.ProductIngredients) // Загружаем связи продукт-ингредиент
.Select(x => _mapper.Map<ProductDataModel>(x))
.ToListAsync(ct)];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
}
}
public List<ProductHistoryDataModel> GetHistoryByProductId(string productId)
{
try
@@ -97,7 +67,7 @@ internal class ProductStorageContract : IProductStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -110,7 +80,7 @@ internal class ProductStorageContract : IProductStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -124,7 +94,7 @@ internal class ProductStorageContract : IProductStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -138,18 +108,18 @@ internal class ProductStorageContract : IProductStorageContract
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", productDataModel.Id, _localizer);
throw new ElementExistsException("Id", productDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException pgEx &&
pgEx.ConstraintName == "IX_Products_Name_IsDeleted")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Name", productDataModel.Name, _localizer);
throw new ElementExistsException("Name", productDataModel.Name);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -162,10 +132,10 @@ internal class ProductStorageContract : IProductStorageContract
try
{
var element = GetProductById(productDataModel.Id)
?? throw new ElementNotFoundException(productDataModel.Id, _localizer);
?? throw new ElementNotFoundException(productDataModel.Id);
if (element.IsDeleted)
throw new ElementDeletedException(productDataModel.Id, _localizer);
throw new ElementDeletedException(productDataModel.Id);
// Проверяем, если цена изменилась, то добавляем её в историю
if (element.UnitPrice != productDataModel.UnitPrice)
@@ -200,7 +170,7 @@ internal class ProductStorageContract : IProductStorageContract
{
// Обработка ошибки уникальности
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Name", productDataModel.Name, _localizer);
throw new ElementExistsException("Name", productDataModel.Name);
}
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
{
@@ -212,7 +182,7 @@ internal class ProductStorageContract : IProductStorageContract
{
// В случае других исключений — логируем ошибку
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -222,7 +192,7 @@ internal class ProductStorageContract : IProductStorageContract
{
try
{
var element = GetProductById(id) ?? throw new ElementNotFoundException(id, _localizer);
var element = GetProductById(id) ?? throw new ElementNotFoundException(id);
element.IsDeleted = true;
_dbContext.SaveChanges();
}
@@ -234,7 +204,7 @@ internal class ProductStorageContract : IProductStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}

View File

@@ -1,8 +1,5 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.Resources;
using SladkieBulkiContrakts.StoragesContarcts;
using SladkieBulkiDatabase.Models;
using System;
@@ -17,9 +14,8 @@ internal class ProductionStorageContract : IProductionStorageContract
{
private readonly SladkieBulkiDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public ProductionStorageContract(SladkieBulkiDbContext dbContext, IStringLocalizer<Messages> localizer)
public ProductionStorageContract(SladkieBulkiDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
@@ -30,7 +26,6 @@ internal class ProductionStorageContract : IProductionStorageContract
.ForMember(dest => dest.Product, opt => opt.Ignore());
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<ProductionDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? workerId = null, string? productId = null)
@@ -59,24 +54,7 @@ internal class ProductionStorageContract : IProductionStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
}
}
public async Task<List<ProductionDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct)
{
try
{
return [.. await _dbContext.Productions
.Where(p => p.ProductionDate >= startDate && p.ProductionDate <= endDate)
.Select(p => _mapper.Map<ProductionDataModel>(p))
.ToListAsync(ct)];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -89,7 +67,7 @@ internal class ProductionStorageContract : IProductionStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -103,7 +81,7 @@ internal class ProductionStorageContract : IProductionStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -112,7 +90,7 @@ internal class ProductionStorageContract : IProductionStorageContract
var element = GetProductionById(id);
if (element == null)
{
throw new ElementNotFoundException($"Element not found at value = {id}", _localizer);
throw new ElementNotFoundException($"Element not found at value = {id}");
}
_dbContext.Productions.Remove(element);

View File

@@ -5,15 +5,13 @@ using SladkieBulkiContrakts.StoragesContarcts;
using SladkieBulkiDatabase.Models;
using SladkieBulkiDatabase;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using SladkieBulkiContrakts.Resources;
internal class SalaryStorageContract : ISalaryStorageContract
{
private readonly SladkieBulkiDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public SalaryStorageContract(SladkieBulkiDbContext dbContext, IStringLocalizer<Messages> localizer)
public SalaryStorageContract(SladkieBulkiDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
@@ -24,7 +22,6 @@ internal class SalaryStorageContract : ISalaryStorageContract
.ForMember(dest => dest.WorkerSalary, opt => opt.MapFrom(src => src.WorkerSalary));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? workerId = null)
@@ -42,20 +39,7 @@ internal class SalaryStorageContract : ISalaryStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
}
}
public async Task<List<SalaryDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct)
{
try
{
return [.. await _dbContext.Salaries.Include(x => x.Worker).Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate).Select(x => _mapper.Map<SalaryDataModel>(x)).ToListAsync(ct)];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -69,7 +53,7 @@ internal class SalaryStorageContract : ISalaryStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
}

View File

@@ -1,10 +1,8 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.Resources;
using SladkieBulkiContrakts.StoragesContarcts;
using SladkieBulkiDatabase.Models;
@@ -14,9 +12,8 @@ internal class WorkerStorageContract : IWorkerStorageContract
{
private readonly SladkieBulkiDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public WorkerStorageContract(SladkieBulkiDbContext dbContext, IStringLocalizer<Messages> localizer)
public WorkerStorageContract(SladkieBulkiDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
@@ -27,7 +24,6 @@ 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)
@@ -56,7 +52,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -69,7 +65,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -82,7 +78,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -96,12 +92,12 @@ internal class WorkerStorageContract : IWorkerStorageContract
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", workerDataModel.Id, _localizer);
throw new ElementExistsException("Id", workerDataModel.Id);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -109,7 +105,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
{
try
{
var element = GetWorkerById(workerDataModel.Id) ?? throw new ElementNotFoundException(workerDataModel.Id, _localizer);
var element = GetWorkerById(workerDataModel.Id) ?? throw new ElementNotFoundException(workerDataModel.Id);
_dbContext.Workers.Update(_mapper.Map(workerDataModel, element));
_dbContext.SaveChanges();
}
@@ -121,7 +117,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -129,7 +125,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
{
try
{
var element = GetWorkerById(id) ?? throw new ElementNotFoundException(id, _localizer);
var element = GetWorkerById(id) ?? throw new ElementNotFoundException(id);
element.IsDeleted = true;
element.DateOfDelete = DateTime.UtcNow;
_dbContext.SaveChanges();
@@ -142,7 +138,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -157,7 +153,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}

View File

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

View File

@@ -4,7 +4,6 @@ using SladkieBulkiContrakts.StoragesContarcts;
using SladkieBulkiContrakts.DataModels;
using Microsoft.Extensions.Logging;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiTests.Infrastructure;
namespace SladkieBulkiTests.BusinessLogicsContractsTests;
@@ -18,7 +17,7 @@ internal class IngredientBusinessLogicContractTests
public void OneTimeSetUp()
{
_ingredientStorageContract = new Mock<IIngredientStorageContract>();
_ingredientBusinessLogicContract = new IngredientBusinessLogicContract(_ingredientStorageContract.Object, StringLocalizerMockCreator.GetObject(), new Mock<ILogger>().Object);
_ingredientBusinessLogicContract = new IngredientBusinessLogicContract(_ingredientStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
@@ -63,13 +62,19 @@ internal class IngredientBusinessLogicContractTests
_ingredientStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllBuyers_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _ingredientBusinessLogicContract.GetAllIngredients(), Throws.TypeOf<NullListException>());
_ingredientStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllIngredients_StorageThrowError_ThrowException_Test()
{
//Arrange
_ingredientStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_ingredientStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _ingredientBusinessLogicContract.GetAllIngredients(), Throws.TypeOf<StorageException>());
_ingredientStorageContract.Verify(x => x.GetList(), Times.Once);
@@ -180,9 +185,9 @@ internal class IngredientBusinessLogicContractTests
{
// Arrange
_ingredientStorageContract.Setup(x =>
x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_ingredientStorageContract.Setup(x =>
x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() =>
@@ -228,7 +233,7 @@ internal class IngredientBusinessLogicContractTests
// Arrange
_ingredientStorageContract.Setup(x =>
x.AddElement(It.IsAny<IngredientDataModel>()))
.Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
.Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() =>
@@ -267,7 +272,7 @@ internal class IngredientBusinessLogicContractTests
// Arrange
_ingredientStorageContract.Setup(x =>
x.AddElement(It.IsAny<IngredientDataModel>()))
.Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
.Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() =>
@@ -309,7 +314,7 @@ internal class IngredientBusinessLogicContractTests
// Arrange
_ingredientStorageContract.Setup(x =>
x.UpdElement(It.IsAny<IngredientDataModel>()))
.Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetObject()));
.Throws(new ElementNotFoundException(""));
// Act & Assert
Assert.That(() =>
@@ -326,7 +331,7 @@ internal class IngredientBusinessLogicContractTests
// Arrange
_ingredientStorageContract.Setup(x =>
x.UpdElement(It.IsAny<IngredientDataModel>()))
.Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
.Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() =>
@@ -364,7 +369,7 @@ internal class IngredientBusinessLogicContractTests
// Arrange
_ingredientStorageContract.Setup(x =>
x.UpdElement(It.IsAny<IngredientDataModel>()))
.Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
.Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() =>

View File

@@ -6,7 +6,6 @@ using SladkieBulkiContrakts.StoragesContarcts;
using Microsoft.Extensions.Logging;
using Moq;
using SladkieBulkiContrakts.Infrastructure.PostConfigurations;
using SladkieBulkiTests.Infrastructure;
namespace SladkieBulkiTests.BusinessLogicsContractsTests;
@@ -20,7 +19,7 @@ internal class PostBusinessLogicContractTests
public void OneTimeSetUp()
{
_postStorageContract = new Mock<IPostStorageContract>();
_postBusinessLogicContract = new PostBusinessLogicContract(_postStorageContract.Object, StringLocalizerMockCreator.GetObject(), new Mock<ILogger>().Object);
_postBusinessLogicContract = new PostBusinessLogicContract(_postStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
@@ -66,12 +65,19 @@ 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(), StringLocalizerMockCreator.GetObject()));
_postStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllPosts(), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetList(), Times.Once);
@@ -126,13 +132,19 @@ 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(), StringLocalizerMockCreator.GetObject()));
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
@@ -200,8 +212,8 @@ internal class PostBusinessLogicContractTests
public void GetPostByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_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()));
_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()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _postBusinessLogicContract.GetPostByData("name"), Throws.TypeOf<StorageException>());
@@ -231,7 +243,7 @@ internal class PostBusinessLogicContractTests
public void InsertPost_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Preform, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
@@ -257,7 +269,7 @@ internal class PostBusinessLogicContractTests
public void InsertPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Preform, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
@@ -285,7 +297,7 @@ internal class PostBusinessLogicContractTests
public void UpdatePost_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetObject()));
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Preform, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
@@ -295,7 +307,7 @@ internal class PostBusinessLogicContractTests
public void UpdatePost_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.Preform, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
@@ -321,7 +333,7 @@ internal class PostBusinessLogicContractTests
public void UpdatePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Preform, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
@@ -346,7 +358,7 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetObject()));
_postStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
@@ -373,7 +385,7 @@ internal class PostBusinessLogicContractTests
public void DeletePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_postStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
@@ -398,7 +410,7 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetObject()));
_postStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);
@@ -425,7 +437,7 @@ internal class PostBusinessLogicContractTests
public void RestorePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_postStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);

View File

@@ -5,7 +5,6 @@ using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Enums;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.StoragesContarcts;
using SladkieBulkiTests.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -24,7 +23,7 @@ internal class ProductBusinessLogicContractTests
public void OneTimeSetUp()
{
_productStorageContract = new Mock<IProductStorageContract>();
_productBusinessLogicContract = new ProductBusinessLogicContract(_productStorageContract.Object, StringLocalizerMockCreator.GetObject(), new Mock<ILogger>().Object);
_productBusinessLogicContract = new ProductBusinessLogicContract(_productStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
@@ -83,12 +82,22 @@ internal class ProductBusinessLogicContractTests
}
[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>()), Times.Once);
}
[Test]
public void GetAllProducts_StorageThrowError_ThrowException_Test()
{
// Arrange
_productStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_productStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _productBusinessLogicContract.GetAllProducts(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
@@ -150,12 +159,19 @@ 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(), StringLocalizerMockCreator.GetObject()));
_productStorageContract.Setup(x => x.GetHistoryByProductId(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Once);
@@ -230,10 +246,10 @@ internal class ProductBusinessLogicContractTests
//Arrange
_productStorageContract.Setup(x =>
x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
InvalidOperationException()));
_productStorageContract.Setup(x =>
x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
InvalidOperationException()));
//Act&Assert
Assert.That(() =>
_productBusinessLogicContract.GetProductByData(Guid.NewGuid().ToString()),
@@ -272,7 +288,7 @@ internal class ProductBusinessLogicContractTests
public void InsertProduct_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_productStorageContract.Setup(x => x.AddElement(It.IsAny<ProductDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
_productStorageContract.Setup(x => x.AddElement(It.IsAny<ProductDataModel>())).Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() => _productBusinessLogicContract.InsertProduct(new(Guid.NewGuid().ToString(), "name", Guid.NewGuid().ToString(), ProductType.Workpiece, [new ProductIngredientDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)], 10, false)),
@@ -303,7 +319,7 @@ internal class ProductBusinessLogicContractTests
{
//Arrange
_productStorageContract.Setup(x => x.AddElement(It.IsAny<ProductDataModel>())).Throws(new StorageException(new
InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.InsertProduct(new(Guid.NewGuid().ToString(), "name", Guid.NewGuid().ToString(), ProductType.Workpiece, [new ProductIngredientDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)], 10, false)), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Once);
@@ -332,7 +348,7 @@ internal class ProductBusinessLogicContractTests
{
//Arrange
_productStorageContract.Setup(x =>
x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetObject()));
x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() =>
_productBusinessLogicContract.UpdateProduct(new(Guid.NewGuid().ToString(), "name", Guid.NewGuid().ToString(), ProductType.Workpiece, [new ProductIngredientDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)], 10, false)),
@@ -347,7 +363,7 @@ internal class ProductBusinessLogicContractTests
//Arrange
_productStorageContract.Setup(x =>
x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new
ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() =>
_productBusinessLogicContract.UpdateProduct(new(Guid.NewGuid().ToString(), "anme", Guid.NewGuid().ToString(), ProductType.Workpiece, [new ProductIngredientDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)], 10, false)),
@@ -381,7 +397,7 @@ internal class ProductBusinessLogicContractTests
//Arrange
_productStorageContract.Setup(x =>
x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new StorageException(new
InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
InvalidOperationException()));
//Act&Assert
Assert.That(() =>
_productBusinessLogicContract.UpdateProduct(new(Guid.NewGuid().ToString(), "name", Guid.NewGuid().ToString(), ProductType.Workpiece, [new ProductIngredientDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)], 10, false)),
@@ -412,7 +428,7 @@ internal class ProductBusinessLogicContractTests
//Arrange
var id = Guid.NewGuid().ToString();
_productStorageContract.Setup(x =>
x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetObject()));
x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() =>
_productBusinessLogicContract.DeleteProduct(Guid.NewGuid().ToString()),
@@ -449,7 +465,7 @@ internal class ProductBusinessLogicContractTests
//Arrange
_productStorageContract.Setup(x =>
x.DelElement(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
InvalidOperationException()));
//Act&Assert
Assert.That(() =>
_productBusinessLogicContract.DeleteProduct(Guid.NewGuid().ToString()),

View File

@@ -5,7 +5,6 @@ using SladkieBulkiContrakts.BusinessLogicsContracts;
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.StoragesContarcts;
using SladkieBulkiTests.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -24,7 +23,7 @@ internal class ProductionBusinessLogicContractTests
public void OneTimeSetUp()
{
_productionStorageContract = new Mock<IProductionStorageContract>();
_productionBusinessLogicContract = new ProductionBusinessLogicContract(_productionStorageContract.Object, StringLocalizerMockCreator.GetObject(), new Mock<ILogger>().Object);
_productionBusinessLogicContract = new ProductionBusinessLogicContract(_productionStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
@@ -113,13 +112,19 @@ internal class ProductionBusinessLogicContractTests
It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productionBusinessLogicContract.GetAllSalesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_productionStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_productionStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_productionStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productionBusinessLogicContract.GetAllSalesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_productionStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
@@ -187,11 +192,19 @@ internal class ProductionBusinessLogicContractTests
_productionStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByWorkerByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productionBusinessLogicContract.GetAllSalesByWorkerByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_productionStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByWorkerByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_productionStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_productionStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productionBusinessLogicContract.GetAllSalesByWorkerByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_productionStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
@@ -259,12 +272,19 @@ internal class ProductionBusinessLogicContractTests
_productionStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByProductByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productionBusinessLogicContract.GetAllSalesByProductByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_productionStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByProductByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_productionStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_productionStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productionBusinessLogicContract.GetAllSalesByProductByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_productionStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
@@ -314,7 +334,7 @@ internal class ProductionBusinessLogicContractTests
public void GetSaleByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_productionStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_productionStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productionBusinessLogicContract.GetProductionByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_productionStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
@@ -360,7 +380,7 @@ internal class ProductionBusinessLogicContractTests
// Arrange
_productionStorageContract
.Setup(x => x.AddElement(It.IsAny<ProductionDataModel>()))
.Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
.Throws(new ElementExistsException("Data", "Data"));
var record = new ProductionDataModel(
Guid.NewGuid().ToString(),
@@ -408,7 +428,7 @@ internal class ProductionBusinessLogicContractTests
// Arrange
_productionStorageContract
.Setup(x => x.AddElement(It.IsAny<ProductionDataModel>()))
.Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
.Throws(new StorageException(new InvalidOperationException()));
var record = new ProductionDataModel(
Guid.NewGuid().ToString(),
@@ -443,7 +463,7 @@ internal class ProductionBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
_productionStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetObject()));
_productionStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _productionBusinessLogicContract.CancelProduction(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_productionStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
@@ -470,7 +490,7 @@ internal class ProductionBusinessLogicContractTests
public void CancelSale_StorageThrowError_ThrowException_Test()
{
//Arrange
_productionStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_productionStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productionBusinessLogicContract.CancelProduction(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_productionStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);

View File

@@ -1,469 +0,0 @@
using Microsoft.Extensions.Logging;
using Moq;
using SladkieBulkiBusinessLogic.Implementations;
using SladkieBulkiBusinessLogic.OfficePackage;
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Enums;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.StoragesContarcts;
using SladkieBulkiDatabase.Implementations;
using SladkieBulkiDatabase.Models;
using SladkieBulkiTests.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiTests.BusinessLogicsContractsTests;
[TestFixture]
internal class ReportContractTests
{
private ReportContract _reportContract;
private Mock<IProductStorageContract> _productStorageContract;
private Mock<IIngredientStorageContract> _ingredientStorageContract;
private Mock<IProductionStorageContract> _productionStorageContract;
private Mock<ISalaryStorageContract> _salaryStorageContract;
private Mock<IPostStorageContract> _postStorageContract;
private Mock<IWorkerStorageContract> _workerStorageContract;
private Mock<BaseWordBuilder> _baseWordBuilder;
private Mock<BaseExcelBuilder> _baseExcelBuilder;
private Mock<BasePdfBuilder> _basePdfBuilder;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_productStorageContract = new Mock<IProductStorageContract>();
_ingredientStorageContract = new Mock<IIngredientStorageContract>();
_productionStorageContract = new Mock<IProductionStorageContract>();
_salaryStorageContract = new Mock<ISalaryStorageContract>();
_postStorageContract = new Mock<IPostStorageContract>();
_workerStorageContract = new Mock<IWorkerStorageContract>();
_baseWordBuilder = new Mock<BaseWordBuilder>();
_baseExcelBuilder = new Mock<BaseExcelBuilder>();
_basePdfBuilder = new Mock<BasePdfBuilder>();
_reportContract = new ReportContract(_productStorageContract.Object, StringLocalizerMockCreator.GetObject(), _ingredientStorageContract.Object, _productionStorageContract.Object, _salaryStorageContract.Object, _workerStorageContract.Object, _baseWordBuilder.Object, _baseExcelBuilder.Object, _basePdfBuilder.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_productStorageContract.Reset();
_ingredientStorageContract.Reset();
_productionStorageContract.Reset();
_salaryStorageContract.Reset();
_postStorageContract.Reset();
}
[Test]
public async Task CreateDocumentSalaryByPeriod_ShouldSuccess_Test()
{
//Arrange
var startDate = DateTime.UtcNow.AddDays(-20);
var endDate = DateTime.UtcNow.AddDays(5);
var worker1 = new WorkerDataModel(Guid.NewGuid().ToString(), "fio 1", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-20), DateTime.UtcNow.AddDays(-3), "test@mail.ru");
var worker2 = new WorkerDataModel(Guid.NewGuid().ToString(), "fio 2", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-20), DateTime.UtcNow.AddDays(-3), "testpv@mail.ru");
var salaries = new List<SalaryDataModel>()
{
new(worker1.Id, DateTime.UtcNow.AddDays(-10), 100, worker1),
new(worker1.Id, endDate, 1000, worker1),
new(worker1.Id, startDate, 1000, worker1),
new(worker2.Id, DateTime.UtcNow.AddDays(-10), 100, worker2),
new(worker2.Id, DateTime.UtcNow.AddDays(-5), 200, worker2)
};
_salaryStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(salaries);
_basePdfBuilder.Setup(x => x.AddHeader(It.IsAny<string>())).Returns(_basePdfBuilder.Object);
_basePdfBuilder.Setup(x => x.AddParagraph(It.IsAny<string>())).Returns(_basePdfBuilder.Object);
var chartData = new List<(string, double)>();
_basePdfBuilder.Setup(x => x.AddPieChart(It.IsAny<string>(), It.IsAny<List<(string, double)>>()))
.Callback<string, List<(string, double)>>((_, data) => chartData = data)
.Returns(_basePdfBuilder.Object);
//Act
var data = await _reportContract.CreateDocumentSalaryByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None);
//Assert
Assert.Multiple(() =>
{
Assert.That(chartData, Has.Count.EqualTo(2));
Assert.That(chartData.Any(x => x.Item1 == worker1.FIO && x.Item2 == 2100), Is.True);
Assert.That(chartData.Any(x => x.Item1 == worker2.FIO && x.Item2 == 300), Is.True);
});
_salaryStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
_basePdfBuilder.Verify(x => x.AddHeader(It.IsAny<string>()), Times.Once);
_basePdfBuilder.Verify(x => x.AddParagraph(It.IsAny<string>()), Times.Once);
_basePdfBuilder.Verify(x => x.AddPieChart(It.IsAny<string>(), It.IsAny<List<(string, double)>>()), Times.Once);
_basePdfBuilder.Verify(x => x.Build(), Times.Once);
}
[Test]
public async Task GetDataSalaryByPeriod_ShouldSuccess_Test()
{
//Arrange
var startDate = DateTime.UtcNow.AddDays(-20);
var endDate = DateTime.UtcNow.AddDays(5);
var worker1 = new WorkerDataModel(Guid.NewGuid().ToString(), "fio 1", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-20), DateTime.UtcNow.AddDays(-3), "test@mail.ru");
var worker2 = new WorkerDataModel(Guid.NewGuid().ToString(), "fio 2", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-20), DateTime.UtcNow.AddDays(-3), "testov@mail.ru");
var salaries = new List<SalaryDataModel>()
{
new(worker1.Id, DateTime.UtcNow.AddDays(-10), 100, worker1),
new(worker1.Id, endDate, 1000, worker1),
new(worker1.Id, startDate, 1000, worker1),
new(worker2.Id, DateTime.UtcNow.AddDays(-10), 100, worker2),
new(worker2.Id, DateTime.UtcNow.AddDays(-5), 200, worker2)
};
_salaryStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(salaries);
//Act
var data = await _reportContract.GetDataSalaryByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None);
//Assert
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(2));
var worker1Salary = data.First(x => x.WorkerFIO == worker1.FIO);
Assert.That(worker1Salary, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(worker1Salary.TotalSalary, Is.EqualTo(2100));
Assert.That(worker1Salary.FromPeriod, Is.EqualTo(startDate));
Assert.That(worker1Salary.ToPeriod, Is.EqualTo(endDate));
});
var worker2Salary = data.First(x => x.WorkerFIO == worker2.FIO);
Assert.That(worker2Salary, Is.Not.Null);
Assert.That(worker2Salary.TotalSalary, Is.EqualTo(300));
_salaryStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public async Task GetDataSalaryByPeriod_WhenNoRecords_ShouldSuccess_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(new List<SalaryDataModel>()));
//Act
var data = await _reportContract.GetDataSalaryByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None);
//Assert
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(0));
_salaryStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public void GetDataSalaryByPeriod_WhenIncorrectDates_ShouldFail_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(async () => await _reportContract.GetDataSalaryByPeriodAsync(date, date, CancellationToken.None), Throws.TypeOf<IncorrectDatesException>());
Assert.That(async () => await _reportContract.GetDataSalaryByPeriodAsync(date, DateTime.UtcNow.AddDays(-1), CancellationToken.None), Throws.TypeOf<IncorrectDatesException>());
}
[Test]
public void GetDataBySalaryByPeriod_WhenStorageThrowError_ShouldFail_Test()
{
//Arrange
_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);
}
[Test]
public async Task GetDataByProductionsByPeriod_ShouldSuccess_Test()
{
// Arrange
_productionStorageContract.Setup(x => x.GetListAsync(
It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<ProductionDataModel>
{
new(Guid.NewGuid().ToString(), DateTime.UtcNow, 5, 1000, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()),
new(Guid.NewGuid().ToString(), DateTime.UtcNow, 10, 2000, Guid.NewGuid().ToString(), Guid.NewGuid().ToString())
});
// Act
var data = await _reportContract.GetDataProductionsByPeriodAsync(
DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None);
// Assert
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(2));
_productionStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public async Task GetDataByProductionsByPeriod_WhenNoRecords_ShouldSuccess_Test()
{
// Arrange
_productionStorageContract.Setup(x => x.GetListAsync(
It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<ProductionDataModel>());
// Act
var data = await _reportContract.GetDataProductionsByPeriodAsync(
DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None);
// Assert
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(0));
_productionStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public void GetDataByProductionsByPeriod_WhenIncorrectDates_ShouldFail_Test()
{
// Arrange
var date = DateTime.UtcNow;
// Act & Assert
Assert.That(async () => await _reportContract.GetDataProductionsByPeriodAsync(date, date, CancellationToken.None),
Throws.TypeOf<IncorrectDatesException>());
Assert.That(async () => await _reportContract.GetDataProductionsByPeriodAsync(date, date.AddDays(-1), CancellationToken.None),
Throws.TypeOf<IncorrectDatesException>());
}
[Test]
public void GetDataByProductionsByPeriod_WhenStorageThrowError_ShouldFail_Test()
{
// Arrange
_productionStorageContract.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.GetDataProductionsByPeriodAsync(
DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None),
Throws.TypeOf<StorageException>());
_productionStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public async Task GetProductsWithIngredients_ShouldReturnAllProducts_Test()
{
// Arrange
_productStorageContract.Setup(x => x.GetListAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult(new List<ProductDataModel>
{
new(
Guid.NewGuid().ToString(),
"Product 1",
"desc 1",
ProductType.Workpiece,
[
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 3)
],
100
),
new(
Guid.NewGuid().ToString(),
"Product 2",
"desc 2",
ProductType.Packaging,
[
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 2),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)
],
200
)
}));
_ingredientStorageContract.Setup(x => x.GetListAsync(It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<IngredientDataModel>());
// Act
var data = await _reportContract.GetProductsWithIngredientsAsync(CancellationToken.None);
// Assert
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(2));
Assert.Multiple(() =>
{
Assert.That(data[0].Name, Is.EqualTo("Product 1"));
Assert.That(data[0].Ingredients, Has.Count.EqualTo(0)); // пока что ингредиенты не подтягиваются (заглушка)
Assert.That(data[1].Name, Is.EqualTo("Product 2"));
Assert.That(data[1].Ingredients, Has.Count.EqualTo(0)); // пока что ингредиенты не подтягиваются (заглушка)
});
_productStorageContract.Verify(x => x.GetListAsync(It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public async Task GetProductsWithIngredients_WhenNoRecords_ShouldReturnEmptyList_Test()
{
// Arrange
_productStorageContract.Setup(x => x.GetListAsync(It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(new List<ProductDataModel>()));
// Act
var data = await _reportContract.GetProductsWithIngredientsAsync(CancellationToken.None);
// Assert
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(0));
_productStorageContract.Verify(x => x.GetListAsync(It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public void GetProductsWithIngredients_WhenStorageThrowsException_ShouldPropagate_Test()
{
// Arrange
_productStorageContract.Setup(x => x.GetListAsync(It.IsAny<CancellationToken>()))
.Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
// Act & Assert
Assert.That(async () => await _reportContract.GetProductsWithIngredientsAsync(CancellationToken.None),
Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.GetListAsync(It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public async Task CreateDocumentProductsWithIngredients_ShouldSuccess_Test()
{
// Arrange — продукт 1 с 1 ингредиентом, продукт 2 с двумя ингредиентами
var product1Id = Guid.NewGuid().ToString();
var product2Id = Guid.NewGuid().ToString();
var ingredient1 = new IngredientDataModel(Guid.NewGuid().ToString(), "Мука", "кг", 50);
var ingredient2 = new IngredientDataModel(Guid.NewGuid().ToString(), "Вода", "л", 5);
_productStorageContract.Setup(x => x.GetListAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult(new List<ProductDataModel>
{
new(
product1Id, "Булка", "Пшеничная", ProductType.Production,
new List<ProductIngredientDataModel> { new(product1Id, ingredient1.Id, 2) },
100
),
new(
product2Id, "Кекс", "С добавлением воды", ProductType.Production,
new List<ProductIngredientDataModel>
{
new(product2Id, ingredient1.Id, 1),
new(product2Id, ingredient2.Id, 1)
},
120
)
}));
_ingredientStorageContract.Setup(x => x.GetListAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult(new List<IngredientDataModel>
{
ingredient1,
ingredient2
}));
_baseWordBuilder.Setup(x => x.AddHeader(It.IsAny<string>())).Returns(_baseWordBuilder.Object);
_baseWordBuilder.Setup(x => x.AddParagraph(It.IsAny<string>())).Returns(_baseWordBuilder.Object);
var countRows = 0;
string[] firstRow = [];
string[] secondRow = [];
string[] thirdRow = [];
_baseWordBuilder.Setup(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>()))
.Callback((int[] widths, List<string[]> data) =>
{
countRows = data.Count;
firstRow = data[0]; // Заголовок
secondRow = data[1]; // Первая строка (Булка)
thirdRow = data[2]; // Первый ингредиент Булки
})
.Returns(_baseWordBuilder.Object);
// Act
var data = await _reportContract.CreateDocumentProductsWithIngredientsAsync(CancellationToken.None);
// Assert
_productStorageContract.Verify(x => x.GetListAsync(It.IsAny<CancellationToken>()), Times.Once);
_baseWordBuilder.Verify(x => x.AddHeader(It.IsAny<string>()), Times.Once);
_baseWordBuilder.Verify(x => x.AddParagraph(It.IsAny<string>()), Times.Once);
_baseWordBuilder.Verify(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>()), Times.Once);
_baseWordBuilder.Verify(x => x.Build(), Times.Once);
Assert.Multiple(() =>
{
// 1 строка заголовка + 1 строка (Булка) + 2 строки (Кекс + 2 ингредиента) = 4
Assert.That(countRows, Is.EqualTo(4), "Ожидается 4 строки в итоговой таблице");
Assert.That(firstRow.Length, Is.EqualTo(8), "В каждой строке должно быть 8 столбцов");
Assert.That(secondRow.Length, Is.EqualTo(8));
Assert.That(thirdRow.Length, Is.EqualTo(8));
// Проверяем, что названия продуктов и ингредиентов реально попали в нужные строки (чтобы не было полного рассинхрона)
Assert.That(secondRow.Any(x => x.Contains("Булка")), "В строке должно быть название первого продукта");
Assert.That(secondRow.Any(x => x.Contains("Мука")), "В строке должен быть первый ингредиент");
Assert.That(thirdRow.Any(x => x.Contains("Кекс")), "В строке должно быть название второго продукта");
Assert.That(thirdRow.Any(x => x.Contains("Мука")) || thirdRow.Any(x => x.Contains("Вода")), "В строке должны быть ингредиенты второго продукта");
});
}
[Test]
public async Task CreateDocumentProductionsByPeriod_ShouldeSuccess_Test()
{
var product1Id = Guid.NewGuid().ToString();
var product2Id = Guid.NewGuid().ToString();
var ingredient1 = new IngredientDataModel(Guid.NewGuid().ToString(), "Мука", "кг", 50);
var ingredient2 = new IngredientDataModel(Guid.NewGuid().ToString(), "Вода", "л", 5);
// Arrange
var product1 = new ProductDataModel(Guid.NewGuid().ToString(), "Булка", "desk1", ProductType.Production, new List<ProductIngredientDataModel> { new(product1Id, ingredient1.Id, 2) }, 10);
var product2 = new ProductDataModel(Guid.NewGuid().ToString(), "Кекс", "desk2", ProductType.Production, new List<ProductIngredientDataModel> { new(product2Id, ingredient2.Id, 2) }, 20);
var date1 = DateTime.UtcNow.AddDays(-1).Date;
var date2 = DateTime.UtcNow.Date;
_productionStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(new List<ProductionDataModel>
{
new(Guid.NewGuid().ToString(), date1, 3, 30, Guid.NewGuid().ToString(), product1.Id),
new(Guid.NewGuid().ToString(), date2, 5, 100, Guid.NewGuid().ToString(), product2.Id)
}));
_productStorageContract.Setup(x => x.GetElementById(product1.Id)).Returns(product1);
_productStorageContract.Setup(x => x.GetElementById(product2.Id)).Returns(product2);
_baseExcelBuilder.Setup(x => x.AddHeader(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>())).Returns(_baseExcelBuilder.Object);
_baseExcelBuilder.Setup(x => x.AddParagraph(It.IsAny<string>(), It.IsAny<int>())).Returns(_baseExcelBuilder.Object);
var countRows = 0;
string[] firstRow = [];
string[] secondRow = [];
_baseExcelBuilder.Setup(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>()))
.Callback((int[] widths, List<string[]> data) =>
{
countRows = data.Count;
firstRow = data[0]; // заголовок
secondRow = data[1]; // первая запись
})
.Returns(_baseExcelBuilder.Object);
// Act
var data = await _reportContract.CreateDocumentProductionsByPeriodAsync(DateTime.UtcNow.AddDays(-2), DateTime.UtcNow, CancellationToken.None);
// Assert
Assert.Multiple(() =>
{
// 1 строка заголовка + 2 строки данных + итого = 4
Assert.That(countRows, Is.EqualTo(4));
Assert.That(firstRow, Has.Length.EqualTo(5)); // ["Дата", "Продукт", "Количество", "Сумма", "Работник"]
Assert.That(secondRow, Has.Length.EqualTo(5)); // Данные о первой записи
});
Assert.Multiple(() =>
{
Assert.That(countRows, Is.GreaterThanOrEqualTo(3), "Ожидалось хотя бы 3 строки (заголовок + 2 строки данных)");
Assert.That(firstRow.Length, Is.EqualTo(5), "Ожидалось 5 столбцов в заголовке");
Assert.That(secondRow.Length, Is.EqualTo(5), "Ожидалось 5 столбцов в первой строке данных");
});
_productionStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
_baseExcelBuilder.Verify(x => x.AddHeader(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()), Times.Once);
_baseExcelBuilder.Verify(x => x.AddParagraph(It.IsAny<string>(), It.IsAny<int>()), Times.Once);
_baseExcelBuilder.Verify(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>()), Times.Once);
_baseExcelBuilder.Verify(x => x.Build(), Times.Once);
}
}

View File

@@ -4,6 +4,7 @@ using SladkieBulkiBusinessLogic.Implementations;
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Enums;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.Infrastructure.PostConfigurations;
using SladkieBulkiContrakts.StoragesContarcts;
using SladkieBulkiTests.Infrastructure;
using System;
@@ -30,7 +31,7 @@ internal class SalaryBusinessLogicContractTests
_productionStorageContract = new Mock<IProductionStorageContract>();
_postStorageContract = new Mock<IPostStorageContract>();
_workerStorageContract = new Mock<IWorkerStorageContract>();
_salaryBusinessLogicContract = new SalaryBusinessLogicContract(_salaryStorageContract.Object, StringLocalizerMockCreator.GetObject(),
_salaryBusinessLogicContract = new SalaryBusinessLogicContract(_salaryStorageContract.Object,
_productionStorageContract.Object, _postStorageContract.Object, _workerStorageContract.Object, new Mock<ILogger>().Object, _salaryConfigurationTest);
}
@@ -89,12 +90,19 @@ 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(), StringLocalizerMockCreator.GetObject()));
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//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);
@@ -163,176 +171,184 @@ 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(), StringLocalizerMockCreator.GetObject()));
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//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);
}
//[Test]
//public void CalculateSalaryByMounth_CalculateSalary_Test()
//{
// //Arrange
// var workerId = Guid.NewGuid().ToString();
// var saleSum = 200.0;
// var postSalary = 2000.0;
// _productionStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
// .Returns([new ProductionDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0, saleSum, workerId, null)]);
// _postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
// .Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manufacturer, postSalary));
// _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, "1@mail.ru"),]);
// var sum = 0.0;
// var expectedSum = postSalary + saleSum * 0.1;
// _salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
// .Callback((SalaryDataModel x) =>
// {
// sum = x.WorkerSalary;
// });
// //Act
// _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
// //Assert
// Assert.That(sum, Is.EqualTo(expectedSum));
//}
[Test]
public void CalculateSalaryByMounth_CalculateSalary_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
var saleSum = 200.0;
var postSalary = 2000.0;
_productionStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new ProductionDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0, saleSum, workerId, null)]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manufacturer, new ManufacturerPostConfiguration { Rate = postSalary, SalePercent = 0.1 }));
_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, "1@mail.ru"),]);
var sum = 0.0;
var expectedSum = postSalary + saleSum * 0.1;
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
.Callback((SalaryDataModel x) =>
{
sum = x.WorkerSalary;
});
//Act
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
//Assert
Assert.That(sum, Is.EqualTo(expectedSum));
}
//[Test]
//public void CalculateSalaryByMounth_WithSeveralWorkers_Test()
//{
// //Arrange
// var worker1Id = Guid.NewGuid().ToString();
// var worker2Id = Guid.NewGuid().ToString();
// var worker3Id = Guid.NewGuid().ToString();
// var list = new List<WorkerDataModel>() {
// new(worker1Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false, "1@mail.ru"),
// new(worker2Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false, "1@mail.ru"),
// new(worker3Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false, "1@mail.ru")
// };
// _productionStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
// .Returns([new ProductionDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0, 0.0, worker1Id, null),
// new ProductionDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0, 0.0, worker1Id, null),
// new ProductionDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0, 0.0, worker2Id, null),
// new ProductionDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0, 0.0, worker3Id, null),
// new ProductionDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0, 0.0, worker3Id, null)]);
// _postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
// .Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manufacturer, 2000));
// _workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
// .Returns(list);
// //Act
// _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
// //Assert
// _salaryStorageContract.Verify(x => x.AddElement(It.IsAny<SalaryDataModel>()), Times.Exactly(list.Count));
//}
[Test]
public void CalculateSalaryByMounth_WithSeveralWorkers_Test()
{
//Arrange
var worker1Id = Guid.NewGuid().ToString();
var worker2Id = Guid.NewGuid().ToString();
var worker3Id = Guid.NewGuid().ToString();
var list = new List<WorkerDataModel>() {
new(worker1Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false, "1@mail.ru"),
new(worker2Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false, "1@mail.ru"),
new(worker3Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false, "1@mail.ru")
};
_productionStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new ProductionDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0, 0.0, worker1Id, null),
new ProductionDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0, 0.0, worker1Id, null),
new ProductionDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0, 0.0, worker2Id, null),
new ProductionDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0, 0.0, worker3Id, null),
new ProductionDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0, 0.0, worker3Id, null)]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manufacturer, new PostConfiguration() { Rate = 2000 }));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns(list);
//Act
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
//Assert
_salaryStorageContract.Verify(x => x.AddElement(It.IsAny<SalaryDataModel>()), Times.Exactly(list.Count));
}
//[Test]
//public void CalculateSalaryByMounth_WithoitSalesByWorker_Test()
//{
// //Arrange
// var postSalary = 2000.0;
// var workerId = Guid.NewGuid().ToString();
// _productionStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
// .Returns([]);
// _postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
// .Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manufacturer, postSalary));
// _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, "1@mail.ru")]);
// var sum = 0.0;
// var expectedSum = postSalary;
// _salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
// .Callback((SalaryDataModel x) =>
// {
// sum = x.WorkerSalary;
// });
// //Act
// _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
// //Assert
// Assert.That(sum, Is.EqualTo(expectedSum));
//}
[Test]
public void CalculateSalaryByMounth_WithoitSalesByWorker_Test()
{
//Arrange
var postSalary = 2000.0;
var workerId = Guid.NewGuid().ToString();
_productionStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manufacturer, new PostConfiguration() { Rate = postSalary }));
_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, "1@mail.ru")]);
var sum = 0.0;
var expectedSum = postSalary;
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
.Callback((SalaryDataModel x) =>
{
sum = x.WorkerSalary;
});
//Act
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
//Assert
Assert.That(sum, Is.EqualTo(expectedSum));
}
//[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.Manufacturer, 2000));
// _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, "1@mail.ru")]);
// //Act&Assert
// Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
//}
[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.Manufacturer, new PostConfiguration() { Rate = 2000 }));
_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, "1@mail.ru")]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
//[Test]
//public void CalculateSalaryByMounth_PostStorageReturnNull_ThrowException_Test()
//{
// //Arrange
// var workerId = Guid.NewGuid().ToString();
// _productionStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
// .Returns([new ProductionDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0, 200.0, workerId, null)]);
// _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, "1@mail.ru")]);
// //Act&Assert
// Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
//}
[Test]
public void CalculateSalaryByMounth_PostStorageReturnNull_ThrowException_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
_productionStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new ProductionDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0, 200.0, workerId, null)]);
_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, "1@mail.ru")]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
//[Test]
//public void CalculateSalaryByMounth_WorkerStorageReturnNull_ThrowException_Test()
//{
// //Arrange
// var workerId = Guid.NewGuid().ToString();
// _productionStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
// .Returns([new ProductionDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0, 200.0, workerId, null)]);
// _postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
// .Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manufacturer, 2000));
// //Act&Assert
// Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
//}
[Test]
public void CalculateSalaryByMounth_WorkerStorageReturnNull_ThrowException_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
_productionStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new ProductionDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0, 200.0, workerId, null)]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manufacturer, new PostConfiguration() { Rate = 2000 }));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
//[Test]
//public void CalculateSalaryByMounth_SaleStorageThrowException_ThrowException_Test()
//{
// //Arrange
// var workerId = Guid.NewGuid().ToString();
// _productionStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
// .Throws(new StorageException(new InvalidOperationException()));
// _postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
// .Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manufacturer, 2000));
// _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, "1@mail.ru")]);
// //Act&Assert
// Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
//}
[Test]
public void CalculateSalaryByMounth_SaleStorageThrowException_ThrowException_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
_productionStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manufacturer, new PostConfiguration() { Rate = 2000 }));
_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, "1@mail.ru")]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
}
//[Test]
//public void CalculateSalaryByMounth_PostStorageThrowException_ThrowException_Test()
//{
// //Arrange
// var workerId = Guid.NewGuid().ToString();
// _productionStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
// .Returns([new ProductionDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0, 200.0, workerId, null)]);
// _postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
// .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?>()))
// .Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false, "1@mail.ru")]);
// //Act&Assert
// Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
//}
[Test]
public void CalculateSalaryByMounth_PostStorageThrowException_ThrowException_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
_productionStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new ProductionDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0, 200.0, workerId, null)]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.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?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false, "1@mail.ru")]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
}
//[Test]
//public void CalculateSalaryByMounth_WorkerStorageThrowException_ThrowException_Test()
//{
// //Arrange
// var workerId = Guid.NewGuid().ToString();
// _productionStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
// .Returns([new ProductionDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0, 200.0, workerId, null)]);
// _postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
// .Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manufacturer, 2000));
// _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()));
// //Act&Assert
// Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
//}
[Test]
public void CalculateSalaryByMounth_WorkerStorageThrowException_ThrowException_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
_productionStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new ProductionDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0, 200.0, workerId, null)]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manufacturer, new PostConfiguration() { Rate = 200 }));
_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()));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
}
}

View File

@@ -4,7 +4,6 @@ using SladkieBulkiBusinessLogic.Implementations;
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.StoragesContarcts;
using SladkieBulkiTests.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -22,7 +21,7 @@ internal class WorkerBusinessLogicContractTests
public void OneTimeSetUp()
{
_workerStorageContract = new Mock<IWorkerStorageContract>();
_workerBusinessLogicContract = new WorkerBusinessLogicContract(_workerStorageContract.Object, StringLocalizerMockCreator.GetObject(), new Mock<ILogger>().Object);
_workerBusinessLogicContract = new WorkerBusinessLogicContract(_workerStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
@@ -76,12 +75,19 @@ 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(), 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?>())).Throws(new StorageException(new InvalidOperationException()));
//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);
@@ -150,11 +156,19 @@ 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(), 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?>())).Throws(new StorageException(new InvalidOperationException()));
//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);
@@ -218,12 +232,19 @@ 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(), 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?>())).Throws(new StorageException(new InvalidOperationException()));
//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);
@@ -287,13 +308,19 @@ 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(), 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?>())).Throws(new StorageException(new InvalidOperationException()));
//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);
@@ -361,8 +388,8 @@ internal class WorkerBusinessLogicContractTests
public void GetWorkerByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_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()));
_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()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData("fio"), Throws.TypeOf<StorageException>());
@@ -393,7 +420,7 @@ internal class WorkerBusinessLogicContractTests
public void InsertWorker_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, "1@mail.ru")), Throws.TypeOf<ElementExistsException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Once);
@@ -419,7 +446,7 @@ internal class WorkerBusinessLogicContractTests
public void InsertWorker_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, "1@mail.ru")), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Once);
@@ -448,7 +475,7 @@ internal class WorkerBusinessLogicContractTests
public void UpdateWorker_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetObject()));
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, "1@mail.ru")), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Once);
@@ -474,7 +501,7 @@ internal class WorkerBusinessLogicContractTests
public void UpdateWorker_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, "1@mail.ru")), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Once);
@@ -499,7 +526,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, StringLocalizerMockCreator.GetObject()));
_workerStorageContract.Setup(x => x.DelElement(It.Is((string x) => x != id))).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.DeleteWorker(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
@@ -526,7 +553,7 @@ internal class WorkerBusinessLogicContractTests
public void DeleteWorker_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_workerStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//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,4 @@
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiTests.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -15,47 +14,47 @@ internal class IngredientDataModelTests
public void IdIsNullEmptyTest()
{
var ingredient = CreateDataModel(null, "ingredientName", "g", 10);
Assert.That(() => ingredient.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => ingredient.Validate(), Throws.TypeOf<ValidationException>());
ingredient = CreateDataModel(string.Empty, "ingredientName", "g", 10);
Assert.That(() => ingredient.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => ingredient.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var ingredient = CreateDataModel("id", "ingredientName", "g", 10);
Assert.That(() => ingredient.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => ingredient.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IngredientNameIsNullOrEmptyTest()
{
var ingredient = CreateDataModel(Guid.NewGuid().ToString(), null, "g", 10);
Assert.That(() => ingredient.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => ingredient.Validate(), Throws.TypeOf<ValidationException>());
ingredient = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, "g", 10);
Assert.That(() => ingredient.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => ingredient.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void SizeInitIsNullOrEmptyTest()
{
var ingredient = CreateDataModel(Guid.NewGuid().ToString(), "ingredientName", null, 10);
Assert.That(() => ingredient.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => ingredient.Validate(), Throws.TypeOf<ValidationException>());
ingredient = CreateDataModel(Guid.NewGuid().ToString(), "ingredientName", string.Empty, 10);
Assert.That(() => ingredient.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => ingredient.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void InitPriceIsZeroOrNegativeTest()
{
var ingredient = CreateDataModel(Guid.NewGuid().ToString(), "ingredientName", "g", 0);
Assert.That(() => ingredient.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => ingredient.Validate(), Throws.TypeOf<ValidationException>());
ingredient = CreateDataModel(Guid.NewGuid().ToString(), "ingredientName", "g", -10);
Assert.That(() => ingredient.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => ingredient.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -67,7 +66,7 @@ internal class IngredientDataModelTests
var initPrice = 20.5;
var ingredient = CreateDataModel(ingredientId, ingredientName, sizeInit, initPrice);
Assert.That(() => ingredient.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.That(() => ingredient.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{

View File

@@ -1,5 +1,4 @@
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiTests.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -15,27 +14,27 @@ internal class IngredientHistoryDataModelTests
public void IngredienIdIsNullEmptyTest()
{
var ingredientHistory = CreateDataModel(null, 10);
Assert.That(() => ingredientHistory.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => ingredientHistory.Validate(), Throws.TypeOf<ValidationException>());
ingredientHistory = CreateDataModel(string.Empty, 10);
Assert.That(() => ingredientHistory.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => ingredientHistory.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IngredienIdIsNotGuidTest()
{
var ingredientHistory = CreateDataModel("id", 10);
Assert.That(() => ingredientHistory.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => ingredientHistory.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void OldPriceIsZeroOrNegativeTest()
{
var ingredientHistory = CreateDataModel(Guid.NewGuid().ToString(), 0);
Assert.That(() => ingredientHistory.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => ingredientHistory.Validate(), Throws.TypeOf<ValidationException>());
ingredientHistory = CreateDataModel(Guid.NewGuid().ToString(), -10);
Assert.That(() => ingredientHistory.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => ingredientHistory.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -45,7 +44,7 @@ internal class IngredientHistoryDataModelTests
var oldPrice = 15.5;
var ingredientHistory = CreateDataModel(ingredientId, oldPrice);
Assert.That(() => ingredientHistory.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.That(() => ingredientHistory.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{

View File

@@ -1,7 +1,6 @@
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Enums;
using SladkieBulkiContrakts.Infrastructure.PostConfigurations;
using SladkieBulkiTests.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -17,39 +16,39 @@ internal class PostDataModelTests
public void IdIsNullOrEmptyTest()
{
var post = CreateDataModel(null, "name", PostType.Manufacturer, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(string.Empty, "name", PostType.Manufacturer, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var post = CreateDataModel("id", "name", PostType.Manufacturer, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostNameIsEmptyTest()
{
var manufacturer = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Manufacturer, new PostConfiguration() { Rate = 10 });
Assert.That(() => manufacturer.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
manufacturer = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Manufacturer, new PostConfiguration() { Rate = 10 });
Assert.That(() => manufacturer.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostTypeIsNoneTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.None, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ConfigurationModelIsNullTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Manufacturer, null);
Assert.That(() => post.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
@@ -57,9 +56,9 @@ internal class PostDataModelTests
public void RateIsLessOrZeroTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Manufacturer, new PostConfiguration() { Rate = 0 });
Assert.That(() => post.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Manufacturer, new PostConfiguration() { Rate = -10 });
Assert.That(() => post.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -70,7 +69,7 @@ internal class PostDataModelTests
var postType = PostType.Manufacturer;
var configuration = new PostConfiguration() { Rate = 10 };
var post = CreateDataModel(postId, postName, postType, configuration);
Assert.That(() => post.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.That(() => post.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(post.Id, Is.EqualTo(postId));
@@ -78,7 +77,6 @@ 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,5 @@
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Enums;
using SladkieBulkiTests.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -16,54 +15,54 @@ internal class ProductDataModelTests
public void IdIsNullEmptyTest()
{
var product = CreateDataModel(null, "Product1", "Description", ProductType.Production, CreateSubDataModel(), 100, false);
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
product = CreateDataModel(string.Empty, "Product1", "Description", ProductType.Production, CreateSubDataModel(), 100, false);
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var product = CreateDataModel("id", "Product1", "Description", ProductType.Production, CreateSubDataModel(), 100, false);
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void NameIsNullOrEmptyTest()
{
var product = CreateDataModel(Guid.NewGuid().ToString(), null, "Description", ProductType.Production, CreateSubDataModel(), 100, false);
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
product = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, "Description", ProductType.Production, CreateSubDataModel(), 100, false);
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void DescriptionIsNullOrEmptyTest()
{
var product = CreateDataModel(Guid.NewGuid().ToString(), "Product1", null, ProductType.Production, CreateSubDataModel(), 100, false);
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
product = CreateDataModel(Guid.NewGuid().ToString(), "Product1", string.Empty, ProductType.Production, CreateSubDataModel(), 100, false);
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductTypeIsNoneTest()
{
var product = CreateDataModel(Guid.NewGuid().ToString(), "Product1", "Description", ProductType.None, CreateSubDataModel(), 100, false);
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void UnitPriceIsZeroOrNegativeTest()
{
var product = CreateDataModel(Guid.NewGuid().ToString(), "Product1", "Description", ProductType.Production, CreateSubDataModel(), 0, false);
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
product = CreateDataModel(Guid.NewGuid().ToString(), "Product1", "Description", ProductType.Production, CreateSubDataModel(), -100, false);
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -82,7 +81,7 @@ internal class ProductDataModelTests
var product = CreateDataModel(productId, productName, productDescription, productType, ingredients, unitPrice, false);
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.That(() => product.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{

View File

@@ -1,5 +1,4 @@
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiTests.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -15,27 +14,27 @@ internal class ProductHistoryDataModelTests
public void ProductIdIsNullEmptyTest()
{
var productHistory = CreateDataModel(null, 100);
Assert.That(() => productHistory.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => productHistory.Validate(), Throws.TypeOf<ValidationException>());
productHistory = CreateDataModel(string.Empty, 100);
Assert.That(() => productHistory.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => productHistory.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductIdIsNotGuidTest()
{
var productHistory = CreateDataModel("id", 100);
Assert.That(() => productHistory.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => productHistory.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void OldPriceIsZeroOrNegativeTest()
{
var productHistory = CreateDataModel(Guid.NewGuid().ToString(), 0);
Assert.That(() => productHistory.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => productHistory.Validate(), Throws.TypeOf<ValidationException>());
productHistory = CreateDataModel(Guid.NewGuid().ToString(), -100);
Assert.That(() => productHistory.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => productHistory.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -45,7 +44,7 @@ internal class ProductHistoryDataModelTests
var oldPrice = 100.0;
var productHistory = CreateDataModel(productId, oldPrice);
Assert.That(() => productHistory.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.That(() => productHistory.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{

View File

@@ -1,5 +1,4 @@
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiTests.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -15,44 +14,44 @@ internal class ProductIngredientDataModelTests
public void ProductIdIsNullEmptyTest()
{
var productIngredient = CreateDataModel(null, Guid.NewGuid().ToString(), 5);
Assert.That(() => productIngredient.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => productIngredient.Validate(), Throws.TypeOf<ValidationException>());
productIngredient = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 5);
Assert.That(() => productIngredient.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => productIngredient.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductIdIsNotGuidTest()
{
var productIngredient = CreateDataModel("id", Guid.NewGuid().ToString(), 5);
Assert.That(() => productIngredient.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => productIngredient.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IngredientIdIsNullEmptyTest()
{
var productIngredient = CreateDataModel(Guid.NewGuid().ToString(), null, 5);
Assert.That(() => productIngredient.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => productIngredient.Validate(), Throws.TypeOf<ValidationException>());
productIngredient = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, 5);
Assert.That(() => productIngredient.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => productIngredient.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IngredientIdIsNotGuidTest()
{
var productIngredient = CreateDataModel(Guid.NewGuid().ToString(), "id", 5);
Assert.That(() => productIngredient.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => productIngredient.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CountIsZeroOrNegativeTest()
{
var productIngredient = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0);
Assert.That(() => productIngredient.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => productIngredient.Validate(), Throws.TypeOf<ValidationException>());
productIngredient = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -5);
Assert.That(() => productIngredient.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => productIngredient.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -63,7 +62,7 @@ internal class ProductIngredientDataModelTests
var count = 5;
var productIngredient = CreateDataModel(productId, ingredientId, count);
Assert.That(() => productIngredient.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.That(() => productIngredient.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{

View File

@@ -1,5 +1,4 @@
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiTests.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -15,89 +14,89 @@ internal class ProductionDataModelTests
public void IdIsNullOrEmptyTest()
{
var production = CreateDataModel(null, DateTime.Now, 5, 100, Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
Assert.That(() => production.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => production.Validate(), Throws.TypeOf<ValidationException>());
production = CreateDataModel(string.Empty, DateTime.Now, 5, 100, Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
Assert.That(() => production.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => production.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var production = CreateDataModel("id", DateTime.Now, 5, 100, Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
Assert.That(() => production.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => production.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductionDateIsInTheFutureTest()
{
var production = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now.AddDays(1), 5, 100, Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
Assert.That(() => production.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => production.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CountIsLessThanOrEqualToZeroTest()
{
var production = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0, 100, Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
Assert.That(() => production.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => production.Validate(), Throws.TypeOf<ValidationException>());
production = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now, -1, 100, Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
Assert.That(() => production.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => production.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void WorkerIdIsNullOrEmptyTest()
{
var production = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now, 5, 100, null, Guid.NewGuid().ToString());
Assert.That(() => production.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => production.Validate(), Throws.TypeOf<ValidationException>());
production = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now, 5, 100, string.Empty, Guid.NewGuid().ToString());
Assert.That(() => production.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => production.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void WorkerIdIsNotGuidTest()
{
var production = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now, 5, 100, "workerId", Guid.NewGuid().ToString());
Assert.That(() => production.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => production.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductIdIsNullOrEmptyTest()
{
var production = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now, 5, 100, Guid.NewGuid().ToString(), null);
Assert.That(() => production.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => production.Validate(), Throws.TypeOf<ValidationException>());
production = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now, 5, 100, Guid.NewGuid().ToString(), string.Empty);
Assert.That(() => production.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => production.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductIdIsNotGuidTest()
{
var production = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now, 5, 100, Guid.NewGuid().ToString(), "productId");
Assert.That(() => production.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => production.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void SumIsLessThanOrEqualToZeroTest()
{
var production = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now, 5, -100, Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
Assert.That(() => production.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => production.Validate(), Throws.TypeOf<ValidationException>());
production = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now, 5, 0, Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
Assert.That(() => production.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => production.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsAreCorrectTest()
{
var production = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now, 5, 100, Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
Assert.That(() => production.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.That(() => production.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(production.Id, Is.Not.Null.Or.Empty);
Assert.That(production.ProductionDate, Is.EqualTo(DateTime.Now.ToUniversalTime()).Within(TimeSpan.FromSeconds(1)));
Assert.That(production.ProductionDate, Is.EqualTo(DateTime.Now).Within(TimeSpan.FromSeconds(1)));
Assert.That(production.Count, Is.GreaterThan(0));
Assert.That(production.Sum, Is.GreaterThan(0));
Assert.That(production.WorkerId, Is.Not.Null.Or.Empty);

View File

@@ -1,5 +1,4 @@
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiTests.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -15,27 +14,27 @@ internal class SalaryDataModelTests
public void WorkerIdIsNullEmptyTest()
{
var salary = CreateDataModel(null, DateTime.Now, 1000.0);
Assert.That(() => salary.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
salary = CreateDataModel(string.Empty, DateTime.Now, 1000.0);
Assert.That(() => salary.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void WorkerIdIsNotGuidTest()
{
var salary = CreateDataModel("workerId", DateTime.Now, 1000.0);
Assert.That(() => salary.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void SalaryIsZeroOrNegativeTest()
{
var salary = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0.0);
Assert.That(() => salary.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
salary = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now, -500.0);
Assert.That(() => salary.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -46,12 +45,12 @@ internal class SalaryDataModelTests
var workerSalary = 1000.0;
var salary = CreateDataModel(workerId, salaryDate, workerSalary);
Assert.That(() => salary.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.That(() => salary.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(salary.WorkerId, Is.EqualTo(workerId));
Assert.That(salary.SalaryDate, Is.EqualTo(salaryDate.ToUniversalTime()));
Assert.That(salary.SalaryDate, Is.EqualTo(salaryDate));
Assert.That(salary.WorkerSalary, Is.EqualTo(workerSalary));
});
}

View File

@@ -1,5 +1,4 @@
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiTests.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -15,58 +14,58 @@ namespace SladkieBulkiTests.DataModelsTests;
public void WorkerIdIsNullEmptyTest()
{
var worker = CreateDataModel(null, "John Doe", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-30), DateTime.Now, false, "test@example.com");
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
worker = CreateDataModel(string.Empty, "John Doe", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-30), DateTime.Now, false, "test@example.com");
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void WorkerIdIsNotGuidTest()
{
var worker = CreateDataModel("workerId", "John Doe", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-30), DateTime.Now, false, "test@example.com");
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void FioIsNullEmptyTest()
{
var worker = CreateDataModel(Guid.NewGuid().ToString(), null, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-30), DateTime.Now, false, "test@example.com");
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
worker = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-30), DateTime.Now, false, "test@example.com");
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostIdIsNullEmptyTest()
{
var worker = CreateDataModel(Guid.NewGuid().ToString(), "John Doe", null, DateTime.Now.AddYears(-30), DateTime.Now, false, "test@example.com");
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
worker = CreateDataModel(Guid.NewGuid().ToString(), "John Doe", string.Empty, DateTime.Now.AddYears(-30), DateTime.Now, false, "test@example.com");
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void BirthDateTooYoungTest()
{
var worker = CreateDataModel(Guid.NewGuid().ToString(), "John Doe", Guid.NewGuid().ToString(), DateTime.Now, DateTime.Now, false, "test@example.com");
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void EmploymentDateBeforeBirthDateTest()
{
var worker = CreateDataModel(Guid.NewGuid().ToString(), "John Doe", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-30), DateTime.Now.AddYears(-31), false, "test@example.com");
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void EmailInvalidTest()
{
var worker = CreateDataModel(Guid.NewGuid().ToString(), "John Doe", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-30), DateTime.Now, false, "invalid-email");
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -79,15 +78,15 @@ namespace SladkieBulkiTests.DataModelsTests;
var email = "test@example.com";
var worker = CreateDataModel(workerId, "John Doe", postId, birthDate, employmentDate, false, email);
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.That(() => worker.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(worker.Id, Is.EqualTo(workerId));
Assert.That(worker.FIO, Is.EqualTo("John Doe"));
Assert.That(worker.PostId, Is.EqualTo(postId));
Assert.That(worker.BirthDate, Is.EqualTo(birthDate.ToUniversalTime()));
Assert.That(worker.EmploymentDate, Is.EqualTo(employmentDate.ToUniversalTime()));
Assert.That(worker.BirthDate, Is.EqualTo(birthDate));
Assert.That(worker.EmploymentDate, Is.EqualTo(employmentDate));
Assert.That(worker.Email, Is.EqualTo(email));
});
}

View File

@@ -10,4 +10,5 @@ namespace SladkieBulkiTests.Infrastructure;
class ConfigurationSalaryTest : IConfigurationSalary
{
public double ExtraSaleSum => 10;
public int MaxParallelThreads { get; set; } = 4;
}

View File

@@ -1,25 +0,0 @@
using Microsoft.Extensions.Localization;
using Moq;
using SladkieBulkiContrakts.Resources;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiTests.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

@@ -1,248 +0,0 @@
using Microsoft.AspNetCore.Mvc.Testing;
using Newtonsoft.Json.Linq;
using SladkieBulkiContrakts.BindingModels;
using SladkieBulkiDatabase.Models;
using SladkieBulkiDatabase;
using SladkieBulkiTests.Infrastructure;
using System.Net;
using System.Text.Json;
using System.Text;
using Microsoft.AspNetCore.TestHost;
using SladkieBulkiContrakts.Enums;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Serilog;
using Microsoft.Extensions.Logging;
internal abstract class BaseLocalizationControllerTest
{
protected abstract string GetLocale();
private WebApplicationFactory<Program> _webApplication;
protected HttpClient HttpClient { get; private set; }
protected static SladkieBulkiDbContext SladkieBulkiDbContext { get; private set; }
protected static readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNameCaseInsensitive = true };
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());
SladkieBulkiDbContext = _webApplication.Services.GetRequiredService<SladkieBulkiDbContext>();
SladkieBulkiDbContext.Database.EnsureDeleted();
SladkieBulkiDbContext.Database.EnsureCreated();
}
[SetUp]
public void SetUp()
{
_workerId = SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "Работник Иванов").Id;
_productId = SladkieBulkiDbContext.InsertProductWithIngredientsToDatabaseAndReturn(
new List<Ingredient>(), name: улка_" + Guid.NewGuid().ToString("N").Substring(0, 8), description: "Свежая булка", productType: ProductType.Production, unitPrice: 100
).Id;
_postId = SladkieBulkiDbContext.InsertPostToDatabaseAndReturn(postName: "Пекарь").PostId;
}
[TearDown]
public void TearDown()
{
SladkieBulkiDbContext.RemoveSalariesFromDatabase();
SladkieBulkiDbContext.RemoveProductionsFromDatabase();
SladkieBulkiDbContext.RemoveWorkersFromDatabase();
SladkieBulkiDbContext.RemovePostsFromDatabase();
SladkieBulkiDbContext.RemoveProductsFromDatabase();
SladkieBulkiDbContext.RemoveIngredientsFromDatabase();
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
SladkieBulkiDbContext?.Database.EnsureDeleted();
SladkieBulkiDbContext?.Dispose();
HttpClient?.Dispose();
_webApplication?.Dispose();
}
[Test]
public async Task LoadProducts_WhenHaveRecords_ShouldSuccess_Test()
{
var product1 = SladkieBulkiDbContext.InsertProductWithIngredientsToDatabaseAndReturn(
new List<Ingredient>(), name: улка_" + Guid.NewGuid().ToString("N").Substring(0, 8)
);
var product2 = SladkieBulkiDbContext.InsertProductWithIngredientsToDatabaseAndReturn(
new List<Ingredient>(), name: "Кекс_" + Guid.NewGuid().ToString("N").Substring(0, 8)
);
var response = await HttpClient.GetAsync("/api/report/LoadProducts");
await AssertStreamAsync(response, $"file-{GetLocale()}.docx");
}
[Test]
public async Task LoadProductions_WhenHaveRecords_ShouldSuccess_Test()
{
var worker = SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "Петр Пекарь");
var product1 = SladkieBulkiDbContext.InsertProductWithIngredientsToDatabaseAndReturn(
new List<Ingredient>(), name: улка_" + Guid.NewGuid().ToString("N").Substring(0, 8)
);
var product2 = SladkieBulkiDbContext.InsertProductWithIngredientsToDatabaseAndReturn(
new List<Ingredient>(), name: "Кекс_" + Guid.NewGuid().ToString("N").Substring(0, 8)
);
SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(workerId: worker.Id, productId: product1.Id, productionDate: DateTime.UtcNow.AddHours(-3), count: 3, sum: 100);
SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(workerId: worker.Id, productId: product2.Id, productionDate: DateTime.UtcNow.AddHours(-2), count: 2, sum: 120);
var response = await HttpClient.GetAsync($"/api/report/loadproductions?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
await AssertStreamAsync(response, $"file-{GetLocale()}.xlsx");
}
[Test]
public async Task LoadSalary_WhenHaveRecords_ShouldSuccess_Test()
{
var post = SladkieBulkiDbContext.InsertPostToDatabaseAndReturn();
var worker1 = SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "Иван_" + Guid.NewGuid().ToString("N").Substring(0, 8), postId: post.PostId).AddPost(post);
var worker2 = SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: етр_" + Guid.NewGuid().ToString("N").Substring(0, 8), postId: post.PostId).AddPost(post);
SladkieBulkiDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, workerSalary: 100, salaryDate: DateTime.UtcNow.AddDays(-10));
SladkieBulkiDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, workerSalary: 1000, salaryDate: DateTime.UtcNow.AddDays(-5));
SladkieBulkiDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, workerSalary: 200, salaryDate: DateTime.UtcNow.AddDays(5));
SladkieBulkiDbContext.InsertSalaryToDatabaseAndReturn(worker2.Id, workerSalary: 500, salaryDate: DateTime.UtcNow.AddDays(-5));
SladkieBulkiDbContext.InsertSalaryToDatabaseAndReturn(worker2.Id, workerSalary: 300, salaryDate: DateTime.UtcNow.AddDays(-3));
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}");
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("workers/getrecord")]
[TestCase("products/getrecord")]
[TestCase("posts")]
public async Task Api_GetElement_NotFound_Test(string path)
{
var response = await HttpClient.GetAsync($"/api/{path}/{Guid.NewGuid()}");
// Принимаем и NotFound, и BadRequest (для универсальности)
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound).Or.EqualTo(HttpStatusCode.BadRequest));
var content = await response.Content.ReadAsStringAsync();
// Проверка на не-пустой контент и json тип
if (!string.IsNullOrWhiteSpace(content)
&& response.Content.Headers.ContentType?.MediaType.Contains("json", StringComparison.OrdinalIgnoreCase) == true)
{
// Парсим только если json, иначе не проверяем
Assert.That(JToken.Parse(content).ToString(), Does.StartWith(MessageElementNotFound()));
}
else
{
// Пустое тело или текст — не валим тест, но можно проверить, что оно вообще есть
Assert.That(string.IsNullOrWhiteSpace(content) || content.StartsWith(MessageElementNotFound()), "Пустой или ожидаемый ответ");
}
}
// Проверка что не даёт добавить дубль по Id
private static IEnumerable<TestCaseData> TestDataElementExists()
{
yield return new TestCaseData(() => {
var worker = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "Тестовый работник", PostId = _postId, BirthDate = DateTime.UtcNow.AddYears(-30), EmploymentDate = DateTime.UtcNow.AddDays(-1) };
SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(worker.Id, worker.FIO, worker.PostId);
return worker;
}, "workers/register");
yield return new TestCaseData(() => {
var product = new ProductBindingModel { Id = Guid.NewGuid().ToString(), Name = улка_" + Guid.NewGuid().ToString("N").Substring(0, 8), ProductType = ProductType.Production.ToString(), UnitPrice = 100 };
SladkieBulkiDbContext.InsertProductWithIngredientsToDatabaseAndReturn(new List<Ingredient>(), product.Id, product.Name);
return product;
}, "products/register");
}
protected abstract string MessageElementExists();
protected abstract string MessageValidationException();
[TestCaseSource(nameof(TestDataElementExists))]
public async Task Api_Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test(Func<object> createModel, string path)
{
var model = createModel();
var response = await HttpClient.PostAsync($"/api/{path}", MakeContent(model));
var content = await response.Content.ReadAsStringAsync();
var expectedMessages = new[]
{
MessageElementExists(),
"Data is empty",
"Данные пусты",
"Die Daten sind leer"
};
// JSON-объект
if (!string.IsNullOrWhiteSpace(content) && content.TrimStart().StartsWith("{"))
{
var json = JObject.Parse(content);
Assert.That(expectedMessages.Any(em => (json["message"]?.ToString() ?? "").StartsWith(em)),
$"Json message mismatch\nExpected: One of [{string.Join(", ", expectedMessages)}]\nBut was: {json["message"]}");
}
// JSON-строка
else if (!string.IsNullOrWhiteSpace(content) && content.TrimStart().StartsWith("\""))
{
var plainMessage = content.Trim().Trim('"');
Assert.That(expectedMessages.Any(em => plainMessage.StartsWith(em)),
$"Raw response mismatch\nExpected: One of [{string.Join(", ", expectedMessages)}]\nBut was: {plainMessage}");
}
else
{
Assert.That(string.IsNullOrWhiteSpace(content) || expectedMessages.Any(em => content.StartsWith(em)),
$"Ответ должен быть пустым или содержать сообщение об ошибке, но было: {content}");
}
}
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");
}

View File

@@ -1,19 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiTests.LocalizationTests;
[TestFixture]
internal class DeDETests : BaseLocalizationControllerTest
{
protected override string GetLocale() => "de-DE";
protected override string MessageElementExists() => "Es ist bereits ein Element mit dem Wert vorhanden";
protected override string MessageElementNotFound() => "Es wurde kein Datenelement gefunden";
protected override string MessageValidationException() => "Ungültige Daten wurden übergeben";
}

View File

@@ -1,18 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiTests.LocalizationTests;
[TestFixture]
internal class DefaultTests : BaseLocalizationControllerTest
{
protected override string GetLocale() => "bla-BLA";
protected override string MessageElementExists() => "Уже существует элемент со значением";
protected override string MessageElementNotFound() => "Не найден элемент по данным";
protected override string MessageValidationException() => "Переданы неверные данные";
}

View File

@@ -1,18 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiTests.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";
protected override string MessageValidationException() => "Incorrect data transmitted";
}

View File

@@ -1,18 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiTests.LocalizationTests;
[TestFixture]
internal class RuRUTests : BaseLocalizationControllerTest
{
protected override string GetLocale() => "ru-RU";
protected override string MessageElementExists() => "Уже существует элемент со значением";
protected override string MessageElementNotFound() => "Не найден элемент по данным";
protected override string MessageValidationException() => "Переданы неверные данные";
}

View File

@@ -3,7 +3,6 @@ using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiDatabase.Implementations;
using SladkieBulkiDatabase.Models;
using SladkieBulkiTests.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -20,7 +19,7 @@ internal class IngredientStorageContractTests : BaseStorageContractTest
[SetUp]
public void SetUp()
{
_ingredientStorageContract = new IngredientStorageContract(SladkieBulkiDbContext, StringLocalizerMockCreator.GetObject());
_ingredientStorageContract = new IngredientStorageContract(SladkieBulkiDbContext);
}
[TearDown]

View File

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

View File

@@ -4,7 +4,6 @@ using SladkieBulkiContrakts.Enums;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiDatabase.Implementations;
using SladkieBulkiDatabase.Models;
using SladkieBulkiTests.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -23,7 +22,7 @@ internal class ProductStorageContractTests : BaseStorageContractTest
[SetUp]
public void SetUp()
{
_productStorageContract = new ProductStorageContract(SladkieBulkiDbContext, StringLocalizerMockCreator.GetObject());
_productStorageContract = new ProductStorageContract(SladkieBulkiDbContext);
_ingredient = InsertIngredientToDatabaseAndReturn();
}
@@ -35,52 +34,6 @@ internal class ProductStorageContractTests : BaseStorageContractTest
SladkieBulkiDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Ingredients\" CASCADE;");
}
[Test]
public async Task Try_GetListAsync_WhenHaveRecords_Test()
{
// Arrange: создаём ингредиенты
var ingredient1 = SladkieBulkiDbContext.InsertIngredientToDatabaseAndReturn(nameIngredients: "Мука");
var ingredient2 = SladkieBulkiDbContext.InsertIngredientToDatabaseAndReturn(nameIngredients: "Вода");
// Arrange: создаём продукты с ингредиентами
var product1 = SladkieBulkiDbContext.InsertProductWithIngredientsToDatabaseAndReturn(
new List<Ingredient> { ingredient1 }, name: "Булка");
var product2 = SladkieBulkiDbContext.InsertProductWithIngredientsToDatabaseAndReturn(
new List<Ingredient> { ingredient2 }, name: "Кекс");
var product3 = SladkieBulkiDbContext.InsertProductWithIngredientsToDatabaseAndReturn(
new List<Ingredient> { ingredient1, ingredient2 }, name: "Пирог");
// Act: получаем список продуктов
var list = await _productStorageContract.GetListAsync(CancellationToken.None);
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
Assert.That(list.Any(x => x.Name == "Булка"), Is.True);
Assert.That(list.Any(x => x.Name == "Кекс"), Is.True);
Assert.That(list.Any(x => x.Name == "Пирог"), Is.True);
// Можно дополнительно проверить наличие ингредиентов у конкретного продукта:
var cake = list.First(x => x.Name == "Пирог");
Assert.That(cake.Ingredients.Count, Is.EqualTo(2));
}
[Test]
public async Task Try_GetListAsync_WhenNoRecords_Test()
{
// Act
var list = await _productStorageContract.GetListAsync(CancellationToken.None);
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{

View File

@@ -5,7 +5,6 @@ using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.StoragesContarcts;
using SladkieBulkiDatabase.Implementations;
using SladkieBulkiDatabase.Models;
using SladkieBulkiTests.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -24,11 +23,9 @@ internal class ProductionStorageContractTests : BaseStorageContractTest
[SetUp]
public void SetUp()
{
_productionStorageContract = new ProductionStorageContract(SladkieBulkiDbContext, StringLocalizerMockCreator.GetObject());
_productionStorageContract = new ProductionStorageContract(SladkieBulkiDbContext);
_worker = InsertWorkerToDatabaseAndReturn();
_product = InsertProductToDatabaseAndReturn();
}
[TearDown]
@@ -41,69 +38,6 @@ internal class ProductionStorageContractTests : BaseStorageContractTest
SladkieBulkiDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Ingredients\" CASCADE;");
}
[Test]
public async Task Try_GetListAsync_ByPeriod_Test()
{
// Уникальные имена!
var worker = SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "Работник " );
var product = SladkieBulkiDbContext.InsertProductWithIngredientsToDatabaseAndReturn(new List<Ingredient>(), name: "Продукт " );
// Входит в период
var prod1 = SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(
workerId: worker.Id,
productId: product.Id,
productionDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3),
count: 5,
sum: 100);
var prod2 = SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(
workerId: worker.Id,
productId: product.Id,
productionDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3),
count: 3,
sum: 60);
// Не входит в период
SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(
workerId: worker.Id,
productId: product.Id,
productionDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3),
count: 1,
sum: 10);
SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(
workerId: worker.Id,
productId: product.Id,
productionDate: DateTime.UtcNow.AddDays(1).AddMinutes(3),
count: 2,
sum: 20);
// Act
var list = await _productionStorageContract.GetListAsync(
startDate: DateTime.UtcNow.AddDays(-1),
endDate: DateTime.UtcNow.AddDays(1),
CancellationToken.None);
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
}
[Test]
public async Task Try_GetListAsync_WhenNoRecords_Test()
{
// Act
var list = await _productionStorageContract.GetListAsync(
startDate: DateTime.UtcNow.AddDays(-1),
endDate: DateTime.UtcNow.AddDays(1),
CancellationToken.None);
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{

View File

@@ -2,7 +2,6 @@
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiDatabase.Implementations;
using SladkieBulkiDatabase.Models;
using SladkieBulkiTests.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -21,7 +20,7 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
[SetUp]
public void SetUp()
{
_salaryStorageContract = new SalaryStorageContract(SladkieBulkiDbContext, StringLocalizerMockCreator.GetObject());
_salaryStorageContract = new SalaryStorageContract(SladkieBulkiDbContext);
_worker = InsertWorkerToDatabaseAndReturn();
}
@@ -32,31 +31,6 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
SladkieBulkiDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Workers\" CASCADE;");
}
[Test]
public async Task Try_GetListAsync_ByPeriod_Test()
{
SladkieBulkiDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
SladkieBulkiDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-5));
SladkieBulkiDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
SladkieBulkiDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
SladkieBulkiDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(5));
SladkieBulkiDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
var list = await _salaryStorageContract.GetListAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1), CancellationToken.None);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(2));
});
}
[Test]
public async Task Try_GetListAsync_WhenNoRecords_Test()
{
var list = await _salaryStorageContract.GetListAsync(DateTime.UtcNow.AddDays(-10), DateTime.UtcNow.AddDays(10), CancellationToken.None);
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{

View File

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

View File

@@ -1,266 +0,0 @@
using DocumentFormat.OpenXml.Wordprocessing;
using SladkieBulkiContrakts.ViewModels;
using SladkieBulkiDatabase.Models;
using SladkieBulkiTests.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiTests.WebApiControllersTests;
[TestFixture]
internal class ReportControllerTests : BaseWebApiControllerTest
{
[TearDown]
public void TearDown()
{
SladkieBulkiDbContext.RemoveProductsFromDatabase();
SladkieBulkiDbContext.RemoveIngredientsFromDatabase();
SladkieBulkiDbContext.RemoveSalariesFromDatabase();
SladkieBulkiDbContext.RemoveProductionsFromDatabase();
SladkieBulkiDbContext.RemoveWorkersFromDatabase();
SladkieBulkiDbContext.RemovePostsFromDatabase();
}
[Test]
public async Task GetSalary_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var post = SladkieBulkiDbContext.InsertPostToDatabaseAndReturn();
var worker1 = SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: post.PostId).AddPost(post);
var worker2 = SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: post.PostId).AddPost(post);
SladkieBulkiDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, workerSalary: 100, salaryDate: DateTime.UtcNow.AddDays(-10));
SladkieBulkiDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, workerSalary: 1000, salaryDate: DateTime.UtcNow.AddDays(-5));
SladkieBulkiDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, workerSalary: 200, salaryDate: DateTime.UtcNow.AddDays(5));
SladkieBulkiDbContext.InsertSalaryToDatabaseAndReturn(worker2.Id, workerSalary: 500, salaryDate: DateTime.UtcNow.AddDays(-5));
SladkieBulkiDbContext.InsertSalaryToDatabaseAndReturn(worker2.Id, workerSalary: 300, salaryDate: DateTime.UtcNow.AddDays(-3));
//Act
var response = await HttpClient.GetAsync($"/api/report/getsalary?fromDate={DateTime.Now.AddDays(-7):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<WorkerSalaryByPeriodViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(2));
Assert.Multiple(() =>
{
Assert.That(data.First(x => x.WorkerFIO == worker1.FIO).TotalSalary, Is.EqualTo(1000));
Assert.That(data.First(x => x.WorkerFIO == worker2.FIO).TotalSalary, Is.EqualTo(800));
});
}
[Test]
public async Task GetSalary_WhenDateIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/report/getsalary?fromDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task GetProductions_WhenHaveRecords_ShouldSuccess_Test()
{
// Arrange
var worker = SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "Петров Петр");
var product1 = SladkieBulkiDbContext.InsertProductWithIngredientsToDatabaseAndReturn(new List<Ingredient>(), name: "Булка");
var product2 = SladkieBulkiDbContext.InsertProductWithIngredientsToDatabaseAndReturn(new List<Ingredient>(), name: "Кекс");
SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(
workerId: worker.Id,
productId: product1.Id,
productionDate: DateTime.UtcNow.AddDays(-0.5),
count: 10,
sum: 1000);
SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(
workerId: worker.Id,
productId: product2.Id,
productionDate: DateTime.UtcNow.AddDays(-0.4),
count: 5,
sum: 600);
// Act
var response = await HttpClient.GetAsync($"/api/report/getproductions?fromDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
// Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<ProductionViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(data, Has.Count.EqualTo(2));
Assert.That(data.Any(x => x.ProductId == product1.Id), Is.True);
Assert.That(data.Any(x => x.ProductId == product2.Id), Is.True);
});
}
[Test]
public async Task GetProductions_WhenDateIsIncorrect_ShouldBadRequest_Test()
{
// Act
var response = await HttpClient.GetAsync($"/api/report/getproductions?fromDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
// Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task GetProductsWithIngredients_WhenHaveRecords_ShouldSuccess_Test()
{
// Arrange: создаём ингредиенты
var flour = SladkieBulkiDbContext.InsertIngredientToDatabaseAndReturn(nameIngredients: "Мука", sizeInit: "кг", initPrice: 50);
var water = SladkieBulkiDbContext.InsertIngredientToDatabaseAndReturn(nameIngredients: "Вода", sizeInit: "л", initPrice: 5);
// Arrange: создаём продукты с ингредиентами
var bun = SladkieBulkiDbContext.InsertProductWithIngredientsToDatabaseAndReturn(
new List<Ingredient> { flour }, name: "Булка", description: "Пшеничная", unitPrice: 100);
var cake = SladkieBulkiDbContext.InsertProductWithIngredientsToDatabaseAndReturn(
new List<Ingredient> { flour, water }, name: "Кекс", description: "С добавлением воды", unitPrice: 120);
var response = await HttpClient.GetAsync("/api/report/getproducts");
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<ProductWithIngredientsViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(2));
Assert.That(data.Any(x => x.Name == "Булка"), Is.True);
Assert.That(data.Any(x => x.Name == "Кекс"), Is.True);
var bunVm = data.First(x => x.Name == "Булка");
Assert.That(bunVm.Ingredients.Count, Is.EqualTo(1));
Assert.That(bunVm.Ingredients[0].NameIngredients, Is.EqualTo("Мука"));
Assert.That(bunVm.Ingredients[0].SizeUnit, Is.EqualTo("кг"));
Assert.That(bunVm.Ingredients[0].InitPrice, Is.EqualTo(50));
var cakeVm = data.First(x => x.Name == "Кекс");
Assert.That(cakeVm.Ingredients.Count, Is.EqualTo(2));
Assert.That(cakeVm.Ingredients.Any(i => i.NameIngredients == "Мука"), Is.True);
Assert.That(cakeVm.Ingredients.Any(i => i.NameIngredients == "Вода"), Is.True);
}
[Test]
public async Task LoadSalary_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var post = SladkieBulkiDbContext.InsertPostToDatabaseAndReturn();
var worker1 = SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "Karabas Barabas", postId: post.PostId).AddPost(post);
var worker2 = SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "Roy Mystang", postId: post.PostId).AddPost(post);
SladkieBulkiDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, workerSalary: 100, salaryDate: DateTime.UtcNow.AddDays(-10));
SladkieBulkiDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, workerSalary: 1000, salaryDate: DateTime.UtcNow.AddDays(-5));
SladkieBulkiDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, workerSalary: 200, salaryDate: DateTime.UtcNow.AddDays(5));
SladkieBulkiDbContext.InsertSalaryToDatabaseAndReturn(worker2.Id, workerSalary: 500, salaryDate: DateTime.UtcNow.AddDays(-5));
SladkieBulkiDbContext.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}");
//Assert
await AssertStreamAsync(response, "file.pdf");
}
[Test]
public async Task LoadSalary_WhenDateIsIncorrect_ShouldBadRequest_Test()
{
//Act
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));
}
[Test]
public async Task LoadProductsWithIngredients_WhenHaveRecords_ShouldSuccess_Test()
{
// Arrange: создаём ингредиенты
var flour = SladkieBulkiDbContext.InsertIngredientToDatabaseAndReturn(nameIngredients: "Мука", sizeInit: "кг", initPrice: 50);
var water = SladkieBulkiDbContext.InsertIngredientToDatabaseAndReturn(nameIngredients: "Вода", sizeInit: "л", initPrice: 5);
// Arrange: создаём продукты с ингредиентами
SladkieBulkiDbContext.InsertProductWithIngredientsToDatabaseAndReturn(
new List<Ingredient> { flour }, name: "Булка", description: "Пшеничная", unitPrice: 100);
SladkieBulkiDbContext.InsertProductWithIngredientsToDatabaseAndReturn(
new List<Ingredient> { flour, water }, name: "Кекс", description: "С добавлением воды", unitPrice: 120);
// Act
var response = await HttpClient.GetAsync("/api/report/LoadProducts"); // <-- Подгони под свой Route/Action
// Assert
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 AssertStreamAsync(response, "file.docx");
}
[Test]
public async Task LoadProductions_WhenHaveRecords_ShouldSuccess_Test()
{
// Arrange
var worker = SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "Pupkin Vasya");
var product1 = SladkieBulkiDbContext.InsertProductWithIngredientsToDatabaseAndReturn(
new List<Ingredient>(), // ингредиенты
name: "Булка"
);
var product2 = SladkieBulkiDbContext.InsertProductWithIngredientsToDatabaseAndReturn(
new List<Ingredient>(), // ингредиенты
name: "Кекс"
);
// Создаём производства для двух продуктов
SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(
productionDate: DateTime.UtcNow.AddHours(-3),
count: 3,
sum: 100,
workerId: worker.Id,
productId: product1.Id
);
SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(
productionDate: DateTime.UtcNow.AddHours(-2),
count: 2,
sum: 120,
workerId: worker.Id,
productId: product2.Id
);
// Act
var response = await HttpClient.GetAsync($"/api/report/loadproductions?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");
}
[Test]
public async Task LoadProductions_WhenDateIsIncorrect_ShouldBadRequest_Test()
{
// Act
var response = await HttpClient.GetAsync($"/api/report/loadproductions?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));
}
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);
}
}

View File

@@ -132,7 +132,7 @@ internal class SalaryControllerTests : BaseWebApiControllerTest
SladkieBulkiDbContext.InsertSalaryToDatabaseAndReturn(worker2.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
SladkieBulkiDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
//Act
var response = await HttpClient.GetAsync($"/api/salaries/getworkerrecords?fromDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}&id={worker1.Id}");
var response = await HttpClient.GetAsync($"/api/salaries/getworkerrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&id={worker1.Id}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<SalaryViewModel>>(response);
@@ -164,163 +164,163 @@ internal class SalaryControllerTests : BaseWebApiControllerTest
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
//[Test]
//public async Task Calculate_ShouldSuccess_Test()
//{
// // Arrange
// var ingredient = SladkieBulkiDbContext.InsertIngredientToDatabaseAndReturn(
// nameIngredients: "Сахар",
// sizeInit: "кг",
// initPrice: 100
// );
[Test]
public async Task Calculate_ShouldSuccess_Test()
{
// Arrange
var ingredient = SladkieBulkiDbContext.InsertIngredientToDatabaseAndReturn(
nameIngredients: "Сахар",
sizeInit: "кг",
initPrice: 100
);
// var post = SladkieBulkiDbContext.InsertPostToDatabaseAndReturn(
// config: new ManufacturerPostConfiguration()
// {
// Rate = 1000,
// SalePercent = 0.1, // 10% от среднего за день
// BonusForExtraSales = 0 // по умолчанию
// }
// );
// var worker = SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "name", postId: post.PostId);
var post = SladkieBulkiDbContext.InsertPostToDatabaseAndReturn(
config: new ManufacturerPostConfiguration()
{
Rate = 1000,
SalePercent = 0.1, // 10% от среднего за день
BonusForExtraSales = 0 // по умолчанию
}
);
var worker = SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "name", postId: post.PostId);
// var product = SladkieBulkiDbContext.InsertProductWithIngredientsToDatabaseAndReturn(
// new List<Ingredient> { ingredient },
// name: "Булка",
// description: "Вкусная булка",
// productType: ProductType.Packaging,
// unitPrice: 100
// );
var product = SladkieBulkiDbContext.InsertProductWithIngredientsToDatabaseAndReturn(
new List<Ingredient> { ingredient },
name: "Булка",
description: "Вкусная булка",
productType: ProductType.Packaging,
unitPrice: 100
);
// var production = SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(
// productId: product.Id,
// workerId: worker.Id,
// productionDate: DateTime.UtcNow.Date, // Сегодня
// sum: 2000
// );
var production = SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(
productId: product.Id,
workerId: worker.Id,
productionDate: DateTime.UtcNow.Date, // Сегодня
sum: 2000
);
// // Act
// var response = await HttpClient.PostAsync($"/api/salaries/calculate?date={DateTime.UtcNow:O}", MakeContent(new { }));
// Act
var response = await HttpClient.PostAsync($"/api/salaries/calculate?date={DateTime.UtcNow:O}", MakeContent(new { }));
// // Assert
// Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent).Or.EqualTo(HttpStatusCode.OK));
// Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent).Or.EqualTo(HttpStatusCode.OK));
// var salaries = SladkieBulkiDbContext.GetSalariesFromDatabaseByWorkerId(worker.Id);
// Assert.Multiple(() =>
// {
// Assert.That(salaries, Is.Not.Null);
// Assert.That(salaries.Length, Is.EqualTo(1));
// Assert.That(salaries.First().WorkerSalary, Is.EqualTo(1000 + 2000 * 0.1).Within(0.01));
// Assert.That(salaries.First().SalaryDate.Month, Is.EqualTo(DateTime.UtcNow.Month));
// });
//}
var salaries = SladkieBulkiDbContext.GetSalariesFromDatabaseByWorkerId(worker.Id);
Assert.Multiple(() =>
{
Assert.That(salaries, Is.Not.Null);
Assert.That(salaries.Length, Is.EqualTo(1));
Assert.That(salaries.First().WorkerSalary, Is.EqualTo(1000 + 2000 * 0.1).Within(0.01));
Assert.That(salaries.First().SalaryDate.Month, Is.EqualTo(DateTime.UtcNow.Month));
});
}
//[Test]
//public async Task Calculate_WithSeveralWorkers_ShouldSuccess_Test()
//{
// // Arrange
// var post = SladkieBulkiDbContext.InsertPostToDatabaseAndReturn(
// config: new ManufacturerPostConfiguration() { Rate = 1000, SalePercent = 0.1 }); // 10%
// var worker1 = SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "name 1", postId: post.PostId);
// var worker2 = SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "name 2", postId: post.PostId);
// var worker3 = SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "name 3", postId: post.PostId);
[Test]
public async Task Calculate_WithSeveralWorkers_ShouldSuccess_Test()
{
// Arrange
var post = SladkieBulkiDbContext.InsertPostToDatabaseAndReturn(
config: new ManufacturerPostConfiguration() { Rate = 1000, SalePercent = 0.1 }); // 10%
var worker1 = SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "name 1", postId: post.PostId);
var worker2 = SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "name 2", postId: post.PostId);
var worker3 = SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "name 3", postId: post.PostId);
// var ingredient = SladkieBulkiDbContext.InsertIngredientToDatabaseAndReturn();
// var product = SladkieBulkiDbContext.InsertProductWithIngredientsToDatabaseAndReturn(
// new List<Ingredient> { ingredient }, name: "Product", unitPrice: 100);
var ingredient = SladkieBulkiDbContext.InsertIngredientToDatabaseAndReturn();
var product = SladkieBulkiDbContext.InsertProductWithIngredientsToDatabaseAndReturn(
new List<Ingredient> { ingredient }, name: "Product", unitPrice: 100);
// // ВАЖНО! Разные дни для worker1, чтобы процент считался дважды
// SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(
// workerId: worker1.Id, productId: product.Id, sum: 2000, productionDate: DateTime.UtcNow.Date);
// SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(
// workerId: worker1.Id, productId: product.Id, sum: 2000, productionDate: DateTime.UtcNow.Date.AddDays(-1));
// SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(
// workerId: worker2.Id, productId: product.Id, sum: 2000, productionDate: DateTime.UtcNow.Date);
// SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(
// workerId: worker3.Id, productId: product.Id, sum: 2000, productionDate: DateTime.UtcNow.Date);
// ВАЖНО! Разные дни для worker1, чтобы процент считался дважды
SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(
workerId: worker1.Id, productId: product.Id, sum: 2000, productionDate: DateTime.UtcNow.Date);
SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(
workerId: worker1.Id, productId: product.Id, sum: 2000, productionDate: DateTime.UtcNow.Date.AddDays(-1));
SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(
workerId: worker2.Id, productId: product.Id, sum: 2000, productionDate: DateTime.UtcNow.Date);
SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(
workerId: worker3.Id, productId: product.Id, sum: 2000, productionDate: DateTime.UtcNow.Date);
// // Act
// var response = await HttpClient.PostAsync($"/api/salaries/calculate?date={DateTime.UtcNow:O}", null);
// Act
var response = await HttpClient.PostAsync($"/api/salaries/calculate?date={DateTime.UtcNow:O}", null);
// // Assert
// Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
// var salaries = SladkieBulkiDbContext.Salaries.ToArray();
// Assert.That(salaries, Has.Length.EqualTo(3), "Суммарно должно быть по зарплате на каждого работника");
// Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
var salaries = SladkieBulkiDbContext.Salaries.ToArray();
Assert.That(salaries, Has.Length.EqualTo(3), "Суммарно должно быть по зарплате на каждого работника");
// var s1 = salaries.FirstOrDefault(x => x.WorkerId == worker1.Id);
// var s2 = salaries.FirstOrDefault(x => x.WorkerId == worker2.Id);
// var s3 = salaries.FirstOrDefault(x => x.WorkerId == worker3.Id);
var s1 = salaries.FirstOrDefault(x => x.WorkerId == worker1.Id);
var s2 = salaries.FirstOrDefault(x => x.WorkerId == worker2.Id);
var s3 = salaries.FirstOrDefault(x => x.WorkerId == worker3.Id);
// Assert.Multiple(() =>
// {
// Assert.That(s1, Is.Not.Null);
// Assert.That(s2, Is.Not.Null);
// Assert.That(s3, Is.Not.Null);
// Assert.That(s1.WorkerSalary, Is.EqualTo(1000 + 0.1 * 2000 + 0.1 * 2000).Within(0.01)); // 1400
// Assert.That(s2.WorkerSalary, Is.EqualTo(1000 + 0.1 * 2000).Within(0.01)); // 1200
// Assert.That(s3.WorkerSalary, Is.EqualTo(1000 + 0.1 * 2000).Within(0.01)); // 1200
// });
//}
Assert.Multiple(() =>
{
Assert.That(s1, Is.Not.Null);
Assert.That(s2, Is.Not.Null);
Assert.That(s3, Is.Not.Null);
Assert.That(s1.WorkerSalary, Is.EqualTo(1000 + 0.1 * 2000 + 0.1 * 2000).Within(0.01)); // 1400
Assert.That(s2.WorkerSalary, Is.EqualTo(1000 + 0.1 * 2000).Within(0.01)); // 1200
Assert.That(s3.WorkerSalary, Is.EqualTo(1000 + 0.1 * 2000).Within(0.01)); // 1200
});
}
//[Test]
//public async Task Calculate_WithoutSalesByWorker_ShouldSuccess_Test()
//{
// // Arrange:
// var post = SladkieBulkiDbContext.InsertPostToDatabaseAndReturn(config: new ManufacturerPostConfiguration() { Rate = 1000, SalePercent = 0.1 });
// var worker1 = SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "name 1", postId: post.PostId);
// var worker2 = SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "name 2", postId: post.PostId);
[Test]
public async Task Calculate_WithoutSalesByWorker_ShouldSuccess_Test()
{
// Arrange:
var post = SladkieBulkiDbContext.InsertPostToDatabaseAndReturn(config: new ManufacturerPostConfiguration() { Rate = 1000, SalePercent = 0.1 });
var worker1 = SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "name 1", postId: post.PostId);
var worker2 = SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "name 2", postId: post.PostId);
// var ingredient = SladkieBulkiDbContext.InsertIngredientToDatabaseAndReturn();
// var product = SladkieBulkiDbContext.InsertProductWithIngredientsToDatabaseAndReturn(
// new List<Ingredient> { ingredient }, name: "Test Product", unitPrice: 100);
var ingredient = SladkieBulkiDbContext.InsertIngredientToDatabaseAndReturn();
var product = SladkieBulkiDbContext.InsertProductWithIngredientsToDatabaseAndReturn(
new List<Ingredient> { ingredient }, name: "Test Product", unitPrice: 100);
// SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(
// workerId: worker1.Id, productId: product.Id, sum: 2000, productionDate: DateTime.UtcNow.AddMonths(-1));
// SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(
// workerId: worker2.Id, productId: product.Id, sum: 2000, productionDate: DateTime.UtcNow);
SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(
workerId: worker1.Id, productId: product.Id, sum: 2000, productionDate: DateTime.UtcNow.AddMonths(-1));
SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(
workerId: worker2.Id, productId: product.Id, sum: 2000, productionDate: DateTime.UtcNow);
// // Act: рассчитываем зарплаты за текущий месяц
// var response = await HttpClient.PostAsync($"/api/salaries/calculate?date={DateTime.UtcNow:O}", null);
// Act: рассчитываем зарплаты за текущий месяц
var response = await HttpClient.PostAsync($"/api/salaries/calculate?date={DateTime.UtcNow:O}", null);
// // Assert:
// Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
// var salary1 = SladkieBulkiDbContext.GetSalariesFromDatabaseByWorkerId(worker1.Id).FirstOrDefault();
// var salary2 = SladkieBulkiDbContext.GetSalariesFromDatabaseByWorkerId(worker2.Id).FirstOrDefault();
// Assert:
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
var salary1 = SladkieBulkiDbContext.GetSalariesFromDatabaseByWorkerId(worker1.Id).FirstOrDefault();
var salary2 = SladkieBulkiDbContext.GetSalariesFromDatabaseByWorkerId(worker2.Id).FirstOrDefault();
// Assert.That(salary1, Is.Not.Null);
// Assert.That(salary2, Is.Not.Null);
// Assert.Multiple(() =>
// {
// Assert.That(salary1.WorkerSalary, Is.EqualTo(1000).Within(0.01), "worker1 зарплата только оклад");
// Assert.That(salary2.WorkerSalary, Is.EqualTo(1000 + 0.1 * 2000).Within(0.01), "worker2 зарплата оклад + бонус за продажу");
// });
//}
Assert.That(salary1, Is.Not.Null);
Assert.That(salary2, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(salary1.WorkerSalary, Is.EqualTo(1000).Within(0.01), "worker1 зарплата только оклад");
Assert.That(salary2.WorkerSalary, Is.EqualTo(1000 + 0.1 * 2000).Within(0.01), "worker2 зарплата оклад + бонус за продажу");
});
}
//[Test]
//public async Task Calculate_PostNotFound_ShouldNotFound_Test()
//{
// // Arrange
// SladkieBulkiDbContext.InsertPostToDatabaseAndReturn();
// var worker = SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "name", postId: Guid.NewGuid().ToString());
[Test]
public async Task Calculate_PostNotFound_ShouldNotFound_Test()
{
// Arrange: создаём одну валидную должность, но работнику задаём другой случайный postId
SladkieBulkiDbContext.InsertPostToDatabaseAndReturn(); // есть пост в БД, но не тот, который у работника
var worker = SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "name", postId: Guid.NewGuid().ToString());
// var ingredient = SladkieBulkiDbContext.InsertIngredientToDatabaseAndReturn();
// var product = SladkieBulkiDbContext.InsertProductWithIngredientsToDatabaseAndReturn(
// new List<Ingredient> { ingredient }, name: "Product 1", unitPrice: 100);
var ingredient = SladkieBulkiDbContext.InsertIngredientToDatabaseAndReturn();
var product = SladkieBulkiDbContext.InsertProductWithIngredientsToDatabaseAndReturn(
new List<Ingredient> { ingredient }, name: "Product 1", unitPrice: 100);
// SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(workerId: worker.Id, productId: product.Id, sum: 2000);
// SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(workerId: worker.Id, productId: product.Id, sum: 2000);
SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(workerId: worker.Id, productId: product.Id, sum: 2000);
SladkieBulkiDbContext.InsertProductionToDatabaseAndReturn(workerId: worker.Id, productId: product.Id, sum: 2000);
// // Act
// var response = await HttpClient.PostAsync($"/api/salaries/calculate?date={DateTime.UtcNow:O}", null);
// Act
var response = await HttpClient.PostAsync($"/api/salaries/calculate?date={DateTime.UtcNow:O}", null);
// // Assert: ожидаем NotFound (так как должность не найдена)
// Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
//}
// Assert: ожидаем NotFound (так как должность не найдена)
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
}
private static void AssertElement(SalaryViewModel? actual, Salary expected)

View File

@@ -146,60 +146,60 @@ internal class WorkerControllerTests : BaseWebApiControllerTest
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task GetList_ByBirthDate_ShouldSuccess_Test()
{
//Arrange
SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", birthDate: DateTime.UtcNow.AddYears(-25));
SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", birthDate: DateTime.UtcNow.AddYears(-21));
SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", birthDate: DateTime.UtcNow.AddYears(-20), isDeleted: true);
SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", birthDate: DateTime.UtcNow.AddYears(-19));
[Test]
public async Task GetList_ByBirthDate_ShouldSuccess_Test()
{
//Arrange
SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", birthDate: DateTime.UtcNow.AddYears(-25));
SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", birthDate: DateTime.UtcNow.AddYears(-21));
SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", birthDate: DateTime.UtcNow.AddYears(-20), isDeleted: true);
SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", birthDate: DateTime.UtcNow.AddYears(-19));
//Act
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");
var response = await HttpClient.GetAsync($"/api/workers/getbirthdaterecords?fromDate={DateTime.UtcNow.AddYears(-21).AddMinutes(-1):O}&toDate={DateTime.UtcNow.AddYears(-20).AddMinutes(1):O}&includeDeleted=true");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(data, Has.Count.EqualTo(2));
});
}
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(data, Has.Count.EqualTo(2));
});
}
[Test]
[Test]
public async Task GetList_ByBirthDate_WhenDateIsIncorrect_ShouldBadRequest_Test()
{
//Act
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");
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");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task GetList_ByEmploymentDate_ShouldSuccess_Test()
{
//Arrange
SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", employmentDate: DateTime.UtcNow.AddDays(-2));
SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", employmentDate: DateTime.UtcNow.AddDays(-1));
SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", employmentDate: DateTime.UtcNow.AddDays(1), isDeleted: true);
SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", employmentDate: DateTime.UtcNow.AddDays(2));
[Test]
public async Task GetList_ByEmploymentDate_ShouldSuccess_Test()
{
//Arrange
SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", employmentDate: DateTime.UtcNow.AddDays(-2));
SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", employmentDate: DateTime.UtcNow.AddDays(-1));
SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", employmentDate: DateTime.UtcNow.AddDays(1), isDeleted: true);
SladkieBulkiDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", employmentDate: DateTime.UtcNow.AddDays(2));
//Act
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");
var response = await HttpClient.GetAsync($"/api/workers/getemploymentrecords?fromDate={DateTime.UtcNow.AddDays(-1).AddMinutes(-1):O}&toDate={DateTime.UtcNow.AddDays(1).AddMinutes(1):O}&includeDeleted=true");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(data, Has.Count.EqualTo(2));
});
}
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(data, Has.Count.EqualTo(2));
});
}
[Test]
[Test]
public async Task GetList_ByEmploymentDate_WhenDateIsIncorrect_ShouldBadRequest_Test()
{
//Act
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");
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");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}

View File

@@ -6,19 +6,16 @@ using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.ViewModels;
using SladkieBulkiContrakts.AdapterContracts;
using Microsoft.Extensions.Localization;
using SladkieBulkiContrakts.Resources;
namespace SladkieBulkiWedApi.Adapters;
internal class IngredientAdapter : IIngredientAdapter
public class IngredientAdapter : IIngredientAdapter
{
private readonly IIngredientBusinessLogicContract _ingredientBusinessLogicContract;
private readonly ILogger _logger;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public IngredientAdapter(IIngredientBusinessLogicContract ingredientBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<IngredientAdapter> logger)
public IngredientAdapter(IIngredientBusinessLogicContract ingredientBusinessLogicContract, ILogger<IngredientAdapter> logger)
{
_ingredientBusinessLogicContract = ingredientBusinessLogicContract;
_logger = logger;
@@ -28,7 +25,6 @@ internal class IngredientAdapter : IIngredientAdapter
cfg.CreateMap<IngredientDataModel, IngredientViewModel>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public IngredientOperationResponse GetList()
@@ -41,10 +37,15 @@ internal class IngredientAdapter : IIngredientAdapter
.ToList()
);
}
catch (NullListException)
{
_logger.LogError("NullListException");
return IngredientOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return IngredientOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
return IngredientOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
@@ -71,22 +72,22 @@ internal class IngredientAdapter : IIngredientAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return IngredientOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
return IngredientOperationResponse.BadRequest("Data is empty");
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return IngredientOperationResponse.NotFound(string.Format(_localizer["AdapterMessageElementNotFoundException"], data));
return IngredientOperationResponse.NotFound($"Not found element by data {data}");
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return IngredientOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], data));
return IngredientOperationResponse.BadRequest($"Element by data: {data} was deleted");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return IngredientOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
return IngredientOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
@@ -105,12 +106,12 @@ internal class IngredientAdapter : IIngredientAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return IngredientOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
return IngredientOperationResponse.BadRequest("Data is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return IngredientOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
return IngredientOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (ElementExistsException ex)
{
@@ -120,7 +121,7 @@ internal class IngredientAdapter : IIngredientAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return IngredientOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
return IngredientOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
@@ -139,17 +140,17 @@ internal class IngredientAdapter : IIngredientAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return IngredientOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
return IngredientOperationResponse.BadRequest("Data is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return IngredientOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
return IngredientOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return IngredientOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], ingredientModel.Id));
return IngredientOperationResponse.BadRequest($"Not found element by Id {ingredientModel.Id}");
}
catch (ElementExistsException ex)
{
@@ -159,12 +160,12 @@ internal class IngredientAdapter : IIngredientAdapter
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return IngredientOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], ingredientModel.Id));
return IngredientOperationResponse.BadRequest($"Element by id: {ingredientModel.Id} was deleted");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return IngredientOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
return IngredientOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{

View File

@@ -7,23 +7,20 @@ using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.ViewModels;
using SladkieBulkiContrakts.AdapterContracts;
using System.Text.Json;
using Microsoft.Extensions.Localization;
using SladkieBulkiContrakts.Resources;
namespace SladkieBulkiWedApi.Adapters;
internal class PostAdapter : IPostAdapter
public class PostAdapter : IPostAdapter
{
private readonly IPostBusinessLogicContract _postBusinessLogicContract;
private readonly ILogger _logger;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
private readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNameCaseInsensitive = true };
public PostAdapter(IPostBusinessLogicContract postBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<PostAdapter> logger)
public PostAdapter(IPostBusinessLogicContract postBusinessLogicContract, ILogger<PostAdapter> logger)
{
_postBusinessLogicContract = postBusinessLogicContract;
_logger = logger;
@@ -34,7 +31,6 @@ internal class PostAdapter : IPostAdapter
.ForMember(x => x.Configuration, x => x.MapFrom(src => JsonSerializer.Serialize(src.ConfigurationModel, JsonSerializerOptions)));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public PostOperationResponse GetList()
@@ -43,10 +39,15 @@ internal class PostAdapter : IPostAdapter
{
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllPosts().Select(x => _mapper.Map<PostViewModel>(x))]);
}
catch (NullListException)
{
_logger.LogError("NullListException");
return PostOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
return PostOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
@@ -64,17 +65,17 @@ internal class PostAdapter : IPostAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
return PostOperationResponse.BadRequest("Data is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
return PostOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
@@ -92,22 +93,22 @@ internal class PostAdapter : IPostAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
return PostOperationResponse.BadRequest("Data is empty");
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return PostOperationResponse.NotFound(string.Format(_localizer["AdapterMessageElementNotFoundException"], data));
return PostOperationResponse.NotFound($"Not found element by data {data}");
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], data));
}
return PostOperationResponse.BadRequest($"Element by data: {data} was deleted");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
return PostOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
@@ -126,12 +127,12 @@ internal class PostAdapter : IPostAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
return PostOperationResponse.BadRequest("Data is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (ElementExistsException ex)
{
@@ -141,7 +142,7 @@ internal class PostAdapter : IPostAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
@@ -160,17 +161,17 @@ internal class PostAdapter : IPostAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
return PostOperationResponse.BadRequest("Data is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], postModel.Id));
return PostOperationResponse.BadRequest($"Not found element by Id {postModel.Id}");
}
catch (ElementExistsException ex)
{
@@ -180,12 +181,12 @@ internal class PostAdapter : IPostAdapter
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], postModel.Id));
return PostOperationResponse.BadRequest($"Element by id: {postModel.Id} was deleted");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
@@ -204,27 +205,27 @@ internal class PostAdapter : IPostAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
return PostOperationResponse.BadRequest("Id is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], id));
return PostOperationResponse.BadRequest($"Not found element by id: {id}");
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], id));
return PostOperationResponse.BadRequest($"Element by id: {id} was deleted");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
@@ -243,22 +244,22 @@ internal class PostAdapter : IPostAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
return PostOperationResponse.BadRequest("Id is empty");
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], id));
}
return PostOperationResponse.BadRequest($"Not found element by id: {id}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{

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