63 Commits

Author SHA1 Message Date
50a0807cdf семафор 2025-05-21 12:43:59 +04:00
4abc5ebcfb забыл тесты раскомитить 2025-05-21 12:26:01 +04:00
681ae1d484 финальная миграция 2025-05-21 02:29:39 +04:00
1b9cbc274d правки в зп
даты.... и <= <
2025-05-21 02:28:26 +04:00
55c269a934 2 миграция 2025-05-21 00:39:54 +04:00
7e8e7a5ee8 правка моделей и тестов 2025-05-21 00:13:39 +04:00
b4c6d0110a миграция 2025-05-20 19:56:48 +04:00
f9cfe3dc00 Лаба готова к сдаче 2025-05-20 19:05:02 +04:00
5c1b458ffd почти все 2025-05-20 18:24:23 +04:00
2b92a2b9bd продкт 2025-05-19 23:18:00 +04:00
c960ed7320 + 2025-05-19 20:56:33 +04:00
4393d5097e часть производства 2025-05-19 20:48:39 +04:00
f1c2d1d3d8 ингредиент 2025-05-19 19:52:10 +04:00
cea9386132 Работник 2025-05-19 01:38:28 +04:00
620832b1a8 Изменения в должности в соответствии с примером. Зеленая зона соответственно 2025-05-19 00:35:03 +04:00
f886b16532 подготовка к добавлению контроллеров, адатеров и тестов 2025-05-18 21:22:47 +04:00
db9da65e76 небольшое начало 2025-05-18 18:41:36 +04:00
629e20e498 начало. Добавлен проект 2025-05-14 16:53:32 +04:00
f89577598a . 2025-05-07 12:31:02 +04:00
99fa16d354 Revert "готово"
This reverts commit 0706b6e6e5.
2025-05-07 11:49:33 +04:00
0706b6e6e5 готово 2025-05-07 11:39:53 +04:00
472ad965a8 Все зеленое, счастья полные 2025-05-06 22:44:51 +04:00
75d8b547cb Пофиксил тесты по продукту 2025-05-06 21:56:20 +04:00
c0f3362f42 Доделать 2025-04-23 14:52:09 +04:00
d92732140c промежуток 2025-04-23 13:28:01 +04:00
5924d86f90 1 2025-04-23 11:32:05 +04:00
03d8022433 ЗП тесты 2025-04-23 03:27:03 +04:00
c1a09db223 3 теста осталось 2025-04-23 03:23:39 +04:00
e64854e1f9 подготовка к тестам 2025-04-23 00:35:11 +04:00
70b42a97f4 Implementations 2025-04-22 23:56:59 +04:00
bb93edd951 dbcontext 2025-04-22 21:21:41 +04:00
d28bb63707 Модели со связями 2025-04-22 20:36:56 +04:00
f54c8ecd02 Start 2025-04-22 01:28:54 +04:00
ca8e1737d0 Зеленая зона по Работнику 2025-04-21 20:58:18 +04:00
aeffe2f451 Зеленая зона З\п 2025-04-21 20:49:20 +04:00
ab3a3f6819 Производство зеленая зона 2025-04-21 20:30:06 +04:00
6f2d341f01 Соответсвующий фикс для Продукта 2025-04-21 19:08:39 +04:00
148b67f195 Исключение 2025-04-21 18:44:30 +04:00
dbf2331511 Макрофикс по списку ингердиентов 2025-04-21 18:44:20 +04:00
4b72fdbe96 Зеленая зона продукта 2025-04-21 17:36:06 +04:00
f5a54bab32 Красная зона Продукта 2025-04-21 17:25:41 +04:00
0d4a275328 Зеленые тесты по должности(реализация) 2025-04-09 13:29:24 +04:00
684073e3be Фикс должности, тк там удаление и нужно было где то помечать удален или нет 2025-04-09 13:29:00 +04:00
5cc67e747e Красная зона для Должности 2025-04-09 12:40:50 +04:00
56a54e19aa Зеленая зона для Ингредиента (реализация) 2025-04-09 12:11:20 +04:00
2e976740af Красная зона для ингредиентов доделана. Добавлено исключение 2025-04-09 11:53:18 +04:00
1d72951b99 Красная зона по ингредиентам + несколько исключений. У меня отвалился лмс и файлик тоже... 2025-04-09 00:23:09 +04:00
595041c319 интерфейсы 2025-04-08 22:39:54 +04:00
71b48ba503 Фикс маленькой буквы в перечислении. Добавление заглушенной реализации интерфейсов 2025-04-08 01:35:03 +04:00
1d8c331535 Бизнес логика готова 2025-04-07 23:04:41 +04:00
362f1e73de Хранилище контрактов добавил 2025-04-06 22:51:53 +04:00
7867d47b02 готова к сдаче 2025-03-12 01:15:53 +04:00
b2a5990b1d регулярка 2025-03-12 00:28:44 +04:00
f6efd7985b 1 2025-03-12 00:18:44 +04:00
491737dd81 ну вроде модели все 2025-03-12 00:10:20 +04:00
52b202c58b осталось многи ко многим 2025-03-11 23:30:23 +04:00
f08b234e68 работник 2025-03-11 22:35:26 +04:00
274f2bb92e история продукта 2025-03-11 22:28:55 +04:00
49fc3892b8 поправил 2025-03-11 22:16:27 +04:00
9cc71e7b11 модель должности 2025-03-11 21:59:22 +04:00
48e0bf26df продукт 2025-03-11 21:27:07 +04:00
50881dbf02 1 2025-03-11 21:11:46 +04:00
54e37c4150 начало положено.... 2025-03-11 20:45:26 +04:00
158 changed files with 14327 additions and 1 deletions

View File

@@ -3,7 +3,15 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.9.34728.123
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SladkieBulkiContrakts", "SladkieBulkiContrakts\SladkieBulkiContrakts.csproj", "{04F3CF43-43CA-4EF0-B5BB-913425A85E29}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SladkieBulkiContrakts", "SladkieBulkiContrakts\SladkieBulkiContrakts.csproj", "{04F3CF43-43CA-4EF0-B5BB-913425A85E29}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SladkieBulkiTests", "SladkieBulkiTests\SladkieBulkiTests.csproj", "{12312C3E-A15B-4563-BD04-BB814149B2F6}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SladkieBulkiBusinessLogic", "SladkieBulkiBusinessLogic\SladkieBulkiBusinessLogic.csproj", "{004CA71C-5308-44C7-82DA-4098BA6F5F1C}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SladkieBulkiDatabase", "SladkieBulkiDatabase\SladkieBulkiDatabase.csproj", "{A39687D5-A64A-4EF1-B988-BD58CFCACDDE}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SladkieBulkiWedApi", "SladkieBulkiWedApi\SladkieBulkiWedApi.csproj", "{8623B6C7-0506-4C36-A337-CA363B92FFA2}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -15,6 +23,22 @@ Global
{04F3CF43-43CA-4EF0-B5BB-913425A85E29}.Debug|Any CPU.Build.0 = Debug|Any CPU
{04F3CF43-43CA-4EF0-B5BB-913425A85E29}.Release|Any CPU.ActiveCfg = Release|Any CPU
{04F3CF43-43CA-4EF0-B5BB-913425A85E29}.Release|Any CPU.Build.0 = Release|Any CPU
{12312C3E-A15B-4563-BD04-BB814149B2F6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{12312C3E-A15B-4563-BD04-BB814149B2F6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{12312C3E-A15B-4563-BD04-BB814149B2F6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{12312C3E-A15B-4563-BD04-BB814149B2F6}.Release|Any CPU.Build.0 = Release|Any CPU
{004CA71C-5308-44C7-82DA-4098BA6F5F1C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{004CA71C-5308-44C7-82DA-4098BA6F5F1C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{004CA71C-5308-44C7-82DA-4098BA6F5F1C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{004CA71C-5308-44C7-82DA-4098BA6F5F1C}.Release|Any CPU.Build.0 = Release|Any CPU
{A39687D5-A64A-4EF1-B988-BD58CFCACDDE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A39687D5-A64A-4EF1-B988-BD58CFCACDDE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A39687D5-A64A-4EF1-B988-BD58CFCACDDE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A39687D5-A64A-4EF1-B988-BD58CFCACDDE}.Release|Any CPU.Build.0 = Release|Any CPU
{8623B6C7-0506-4C36-A337-CA363B92FFA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8623B6C7-0506-4C36-A337-CA363B92FFA2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8623B6C7-0506-4C36-A337-CA363B92FFA2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8623B6C7-0506-4C36-A337-CA363B92FFA2}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@@ -0,0 +1,92 @@
using Microsoft.Extensions.Logging;
using SladkieBulkiContrakts.BusinessLogicsContracts;
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.StoragesContarcts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace SladkieBulkiBusinessLogic.Implementations;
internal class IngredientBusinessLogicContract (IIngredientStorageContract ingredientStorageContract, ILogger logger) : IIngredientBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IIngredientStorageContract _ingredientStorageContract = ingredientStorageContract;
public List<IngredientDataModel> GetAllIngredients()
{
_logger.LogInformation("GetAllBuyers");
return _ingredientStorageContract.GetList() ?? throw new NullListException();
}
public List<IngredientDataModel> GetIngredientsBySizeUnit(string sizeUnit)
{
_logger.LogInformation("GetIngredientsBySizeUnit: {sizeUnit}", sizeUnit);
if (string.IsNullOrWhiteSpace(sizeUnit))
{
throw new ArgumentNullException(nameof(sizeUnit));
}
var list = _ingredientStorageContract.GetElementBySizeUnit(sizeUnit);
if (list == null)
{
throw new NullListException();
}
return list.Where(x => x.SizeInit == sizeUnit).ToList();
}
public IngredientDataModel? GetIngredientById(string id)
{
_logger.LogInformation("GetIngredientById: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
return _ingredientStorageContract.GetElementById(id) ?? throw new ElementNotFoundException(id);
}
public IngredientDataModel? GetIngredientByName(string name)
{
_logger.LogInformation("GetIngredientByName: {name}", name);
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentNullException(nameof(name));
}
return _ingredientStorageContract.GetElementByName(name) ?? throw new ElementNotFoundException(name);
}
public void InsertIngredient(IngredientDataModel ingredientDataModel)
{
_logger.LogInformation("New ingredient: {json}", JsonSerializer.Serialize(ingredientDataModel));
ArgumentNullException.ThrowIfNull(ingredientDataModel);
ingredientDataModel.Validate();
_ingredientStorageContract.AddElement(ingredientDataModel);
}
public void UpdateIngredient(IngredientDataModel ingredientDataModel)
{
_logger.LogInformation("Update ingredient: {json}", JsonSerializer.Serialize(ingredientDataModel));
ArgumentNullException.ThrowIfNull(ingredientDataModel);
ingredientDataModel.Validate();
_ingredientStorageContract.UpdElement(ingredientDataModel);
}
}

View File

@@ -0,0 +1,93 @@
using Microsoft.Extensions.Logging;
using SladkieBulkiContrakts.BusinessLogicsContracts;
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.StoragesContarcts;
using System.Text.Json;
namespace SladkieBulkiBusinessLogic.Implementations;
internal class PostBusinessLogicContract(IPostStorageContract postStorageContract, ILogger logger) : IPostBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IPostStorageContract _postStorageContract = postStorageContract;
public List<PostDataModel> GetAllPosts()
{
_logger.LogInformation("GetAllPosts");
return _postStorageContract.GetList() ?? throw new NullListException();
}
public List<PostDataModel> GetAllDataOfPost(string postId)
{
_logger.LogInformation("GetAllDataOfPost for {postId}", postId);
if (postId.IsEmpty())
{
throw new ArgumentNullException(nameof(postId));
}
if (!postId.IsGuid())
{
throw new ValidationException("The value in the field postId is not a unique identifier.");
}
return _postStorageContract.GetPostWithHistory(postId) ?? throw new NullListException();
}
public PostDataModel GetPostByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _postStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
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();
_postStorageContract.AddElement(postDataModel);
}
public void UpdatePost(PostDataModel postDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(postDataModel));
ArgumentNullException.ThrowIfNull(postDataModel);
postDataModel.Validate();
_postStorageContract.UpdElement(postDataModel);
}
public void DeletePost(string id)
{
_logger.LogInformation("Delete by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_postStorageContract.DelElement(id);
}
public void RestorePost(string id)
{
_logger.LogInformation("Restore by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_postStorageContract.ResElement(id);
}
}

View File

@@ -0,0 +1,87 @@
using Microsoft.Extensions.Logging;
using SladkieBulkiContrakts.BusinessLogicsContracts;
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.StoragesContarcts;
using System.Text.Json;
namespace SladkieBulkiBusinessLogic.Implementations;
internal class ProductBusinessLogicContract(IProductStorageContract productStorageContract, ILogger logger) : IProductBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IProductStorageContract _productStorageContract = productStorageContract;
public List<ProductDataModel> GetAllProducts(bool onlyActive)
{
_logger.LogInformation("GetAllProducts params: {onlyActive}", onlyActive);
return _productStorageContract.GetList(onlyActive) ?? throw new NullListException();
//return [];
}
public List<ProductHistoryDataModel> GetProductHistoryByProduct(string productId)
{
_logger.LogInformation("GetProductHistoryByProduct for {productId}", productId);
if (productId.IsEmpty())
{
throw new ArgumentNullException(nameof(productId));
}
if (!productId.IsGuid())
{
throw new ValidationException("The value in the field productId is not a unique identifier.");
}
return _productStorageContract.GetHistoryByProductId(productId) ?? throw new NullListException();
//return [];
}
public ProductDataModel GetProductByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _productStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
return _productStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data);
//return new("", "", "", 0, [], 0, false);
}
public void InsertProduct(ProductDataModel productDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(productDataModel));
ArgumentNullException.ThrowIfNull(productDataModel);
productDataModel.Validate();
_productStorageContract.AddElement(productDataModel);
}
public void UpdateProduct(ProductDataModel productDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(productDataModel));
ArgumentNullException.ThrowIfNull(productDataModel);
productDataModel.Validate();
_productStorageContract.UpdElement(productDataModel);
}
public void DeleteProduct(string id)
{
_logger.LogInformation("Delete by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_productStorageContract.DelElement(id);
}
}

View File

@@ -0,0 +1,98 @@
using Microsoft.Extensions.Logging;
using SladkieBulkiContrakts.BusinessLogicsContracts;
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.StoragesContarcts;
using System.Text.Json;
namespace SladkieBulkiBusinessLogic.Implementations;
internal class ProductionBusinessLogicContract(IProductionStorageContract productionStorageContract,ILogger logger) : IProductionBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IProductionStorageContract _productionStorageContract = productionStorageContract;
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);
}
return _productionStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
}
public List<ProductionDataModel> GetAllSalesByProductByPeriod(string productId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllProductionsByProduct params: {productId}, {fromDate}, {toDate}", productId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (productId.IsEmpty())
{
throw new ArgumentNullException(nameof(productId));
}
if (!productId.IsGuid())
{
throw new ValidationException("The value in the field productId is not a unique identifier.");
}
return _productionStorageContract.GetList(fromDate, toDate, productId: productId) ?? throw new NullListException();
}
public List<ProductionDataModel> GetAllSalesByWorkerByPeriod(string workerId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllProductionsByWorker params: {workerId}, {fromDate}, {toDate}", workerId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (workerId.IsEmpty())
{
throw new ArgumentNullException(nameof(workerId));
}
if (!workerId.IsGuid())
{
throw new ValidationException("The value in the field workerId is not a unique identifier.");
}
return _productionStorageContract.GetList(fromDate, toDate, workerId: workerId) ?? throw new NullListException();
}
public ProductionDataModel GetProductionByData(string data)
{
_logger.LogInformation("GetProductionByData: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (!data.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
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();
_productionStorageContract.AddElement(productionDataModel);
}
public void CancelProduction(string id)
{
_logger.LogInformation("CancelProduction by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_productionStorageContract.DelElement(id);
}
}

View File

@@ -0,0 +1,147 @@
using Microsoft.Extensions.Configuration;
using SladkieBulkiContrakts.BusinessLogicsContracts;
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Infrastructure;
using SladkieBulkiContrakts.Infrastructure.PostConfigurations;
using SladkieBulkiContrakts.StoragesContarcts;
using Microsoft.Extensions.Logging;
namespace SladkieBulkiBusinessLogic.Implementations;
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 =
salaryStorageContract;
private readonly IProductionStorageContract _productionStorageContract = productionStorageContract;
private readonly IPostStorageContract _postStorageContract =
postStorageContract;
private readonly IWorkerStorageContract _workerStorageContract =
workerStorageContract;
private readonly IConfigurationSalary _salaryConfiguration = сonfiguration;
private readonly object _lockObject = new();
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);
}
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);
}
if (workerId.IsEmpty())
{
throw new ArgumentNullException(nameof(workerId));
}
if (!workerId.IsGuid())
{
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) ?? throw new NullListException();
}
public void CalculateSalaryByMounth(DateTime date)
{
_logger.LogInformation("CalculateSalaryByMounth: {date}", date);
var startDate = new DateTime(date.Year, date.Month, 1);
var finishDate = new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month));
var workers = _workerStorageContract.GetList() ?? throw new NullListException();
foreach (var worker in workers)
{
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,
ManufacturerPostConfiguration cpc => CalculateSalaryForCashier(sales, startDate, finishDate, cpc),
PackerPostConfiguration spc => CalculateSalaryForSupervisor(startDate, finishDate, spc),
PostConfiguration pc => pc.Rate,
};
_logger.LogDebug("The employee {workerId} was paid a salary of {salary}", worker.Id, salary);
_salaryStorageContract.AddElement(new SalaryDataModel(worker.Id, finishDate, salary));
}
}
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))
{
var dateCopy = date; // Нужно, чтобы замыкание захватило корректную дату
tasks.Add(Task.Run(async () =>
{
await semaphore.WaitAsync();
try
{
var salesInDay = sales
.Where(x => x.ProductionDate >= dateCopy && x.ProductionDate < dateCopy.AddDays(1))
.ToArray();
if (salesInDay.Length > 0)
{
lock (_lockObject)
{
calcPercent += (salesInDay.Sum(x => x.Sum) / salesInDay.Length) * config.SalePercent;
}
}
}
finally
{
semaphore.Release();
}
}));
}
var calcBonusTask = Task.Run(() =>
{
return sales.Where(x => x.Sum > _salaryConfiguration.ExtraSaleSum).Sum(x => x.Sum) * config.BonusForExtraSales;
});
try
{
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
{
return config.Rate + config.PersonalCountPack * _workerStorageContract.GetWorkerTrend(startDate, finishDate);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error in the supervisor payroll process");
return 0;
}
}
}

View File

@@ -0,0 +1,99 @@
using Microsoft.Extensions.Logging;
using SladkieBulkiContrakts.BusinessLogicsContracts;
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.StoragesContarcts;
using System.Text.Json;
namespace SladkieBulkiBusinessLogic.Implementations;
internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageContract, ILogger logger) : IWorkerBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IWorkerStorageContract _workerStorageContract = workerStorageContract;
public List<WorkerDataModel> GetAllWorkers(bool onlyActive = true)
{
_logger.LogInformation("GetAllWorkers params: {onlyActive}", onlyActive);
return _workerStorageContract.GetList(onlyActive) ?? throw new NullListException();
}
public List<WorkerDataModel> GetAllWorkersByPost(string postId, bool onlyActive = true)
{
_logger.LogInformation("GetAllWorkers params: {postId}, {onlyActive},", postId, onlyActive);
if (postId.IsEmpty())
{
throw new ArgumentNullException(nameof(postId));
}
if (!postId.IsGuid())
{
throw new ValidationException("The value in the field postId is not a unique identifier.");
}
return _workerStorageContract.GetList(onlyActive, postId) ?? throw new NullListException();
}
public List<WorkerDataModel> GetAllWorkersByBirthDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
{
_logger.LogInformation("GetAllWorkers params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _workerStorageContract.GetList(onlyActive, fromBirthDate: fromDate, toBirthDate: toDate) ?? throw new NullListException();
}
public List<WorkerDataModel> GetAllWorkersByEmploymentDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
{
_logger.LogInformation("GetAllWorkers params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _workerStorageContract.GetList(onlyActive, fromEmploymentDate: fromDate, toEmploymentDate: toDate) ?? throw new NullListException();
}
public WorkerDataModel GetWorkerByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _workerStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
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();
_workerStorageContract.AddElement(workerDataModel);
}
public void UpdateWorker(WorkerDataModel workerDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(workerDataModel));
ArgumentNullException.ThrowIfNull(workerDataModel);
workerDataModel.Validate();
_workerStorageContract.UpdElement(workerDataModel);
}
public void DeleteWorker(string id)
{
_logger.LogInformation("Delete by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_workerStorageContract.DelElement(id);
}
}

View File

@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="SladkieBulkiWedApi" />
<InternalsVisibleTo Include="SladkieBulkiTests" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SladkieBulkiContrakts\SladkieBulkiContrakts.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,21 @@
using SladkieBulkiContrakts.AdapterContracts.OperationResponses;
using SladkieBulkiContrakts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.AdapterContracts;
public interface IIngredientAdapter
{
IngredientOperationResponse GetList();
IngredientOperationResponse GetElement(string data);
IngredientOperationResponse RegisterIngredient(IngredientBindingModel ingredientModel);
IngredientOperationResponse ChangeIngredientInfo(IngredientBindingModel ingredientModel);
}

View File

@@ -0,0 +1,21 @@
using SladkieBulkiContrakts.AdapterContracts.OperationResponses;
using SladkieBulkiContrakts.BindingModels;
namespace SladkieBulkiContrakts.AdapterContracts;
public interface IPostAdapter
{
PostOperationResponse GetList();
PostOperationResponse GetHistory(string id);
PostOperationResponse GetElement(string data);
PostOperationResponse RegisterPost(PostBindingModel postModel);
PostOperationResponse ChangePostInfo(PostBindingModel postModel);
PostOperationResponse RemovePost(string id);
PostOperationResponse RestorePost(string id);
}

View File

@@ -0,0 +1,18 @@
using SladkieBulkiContrakts.AdapterContracts.OperationResponses;
using SladkieBulkiContrakts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.AdapterContracts;
public interface IProductAdapter
{
ProductOperationResponse GetList();
ProductOperationResponse GetElement(string data);
ProductOperationResponse RegisterProduct(ProductBindingModel model);
ProductOperationResponse ChangeProductInfo(ProductBindingModel model);
ProductOperationResponse DeleteProduct(string id);
}

View File

@@ -0,0 +1,17 @@
using SladkieBulkiContrakts.AdapterContracts.OperationResponses;
using SladkieBulkiContrakts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.AdapterContracts;
public interface IProductionAdapter
{
ProductionOperationResponse GetList(DateTime? from = null, DateTime? to = null, string? workerId = null, string? productId = null);
ProductionOperationResponse GetElement(string id);
ProductionOperationResponse RegisterProduction(ProductionBindingModel model);
ProductionOperationResponse CancelProduction(string id);
}

View File

@@ -0,0 +1,12 @@
using SladkieBulkiContrakts.AdapterContracts.OperationResponses;
namespace SladkieBulkiContrakts.AdapterContracts;
public interface ISalaryAdapter
{
SalaryOperationResponse GetListByPeriod(DateTime fromDate, DateTime toDate);
SalaryOperationResponse GetListByPeriodByWorker(DateTime fromDate, DateTime toDate, string workerId);
SalaryOperationResponse CalculateSalary(DateTime date);
}

View File

@@ -0,0 +1,23 @@
using SladkieBulkiContrakts.AdapterContracts.OperationResponses;
using SladkieBulkiContrakts.BindingModels;
namespace SladkieBulkiContrakts.AdapterContracts;
public interface IWorkerAdapter
{
WorkerOperationResponse GetList(bool includeDeleted);
WorkerOperationResponse GetPostList(string id, bool includeDeleted);
WorkerOperationResponse GetListByBirthDate(DateTime fromDate, DateTime toDate, bool includeDeleted);
WorkerOperationResponse GetListByEmploymentDate(DateTime fromDate, DateTime toDate, bool includeDeleted);
WorkerOperationResponse GetElement(string data);
WorkerOperationResponse RegisterWorker(WorkerBindingModel workerModel);
WorkerOperationResponse ChangeWorkerInfo(WorkerBindingModel workerModel);
WorkerOperationResponse RemoveWorker(string id);
}

View File

@@ -0,0 +1,25 @@
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 IngredientOperationResponse : OperationResponse
{
public static IngredientOperationResponse OK(List<IngredientViewModel> data) => OK<IngredientOperationResponse, List<IngredientViewModel>>(data);
public static IngredientOperationResponse OK(IngredientViewModel data) => OK<IngredientOperationResponse, IngredientViewModel>(data);
public static IngredientOperationResponse NoContent() => NoContent<IngredientOperationResponse>();
public static IngredientOperationResponse NotFound(string message) => NotFound<IngredientOperationResponse>(message);
public static IngredientOperationResponse BadRequest(string message) => BadRequest<IngredientOperationResponse>(message);
public static IngredientOperationResponse InternalServerError(string message) => InternalServerError<IngredientOperationResponse>(message);
}

View File

@@ -0,0 +1,19 @@
using SladkieBulkiContrakts.Infrastructure;
using SladkieBulkiContrakts.ViewModels;
namespace SladkieBulkiContrakts.AdapterContracts.OperationResponses;
public class PostOperationResponse : OperationResponse
{
public static PostOperationResponse OK(List<PostViewModel> data) => OK<PostOperationResponse, List<PostViewModel>>(data);
public static PostOperationResponse OK(PostViewModel data) => OK<PostOperationResponse, PostViewModel>(data);
public static PostOperationResponse NoContent() => NoContent<PostOperationResponse>();
public static PostOperationResponse NotFound(string message) => NotFound<PostOperationResponse>(message);
public static PostOperationResponse BadRequest(string message) => BadRequest<PostOperationResponse>(message);
public static PostOperationResponse InternalServerError(string message) => InternalServerError<PostOperationResponse>(message);
}

View File

@@ -0,0 +1,30 @@
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 ProductOperationResponse : OperationResponse
{
public static ProductOperationResponse OK(List<ProductViewModel> data) =>
OK<ProductOperationResponse, List<ProductViewModel>>(data);
public static ProductOperationResponse OK(ProductViewModel data) =>
OK<ProductOperationResponse, ProductViewModel>(data);
public static ProductOperationResponse NoContent() =>
NoContent<ProductOperationResponse>();
public static ProductOperationResponse NotFound(string message) =>
NotFound<ProductOperationResponse>(message);
public static ProductOperationResponse BadRequest(string message) =>
BadRequest<ProductOperationResponse>(message);
public static ProductOperationResponse InternalServerError(string message) =>
InternalServerError<ProductOperationResponse>(message);
}

View File

@@ -0,0 +1,31 @@
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 ProductionOperationResponse : OperationResponse
{
public static ProductionOperationResponse OK(List<ProductionViewModel> data) =>
OK<ProductionOperationResponse, List<ProductionViewModel>>(data);
public static ProductionOperationResponse OK(ProductionViewModel data) =>
OK<ProductionOperationResponse, ProductionViewModel>(data);
public static ProductionOperationResponse NoContent() =>
NoContent<ProductionOperationResponse>();
public static ProductionOperationResponse NotFound(string message) =>
NotFound<ProductionOperationResponse>(message);
public static ProductionOperationResponse BadRequest(string message) =>
BadRequest<ProductionOperationResponse>(message);
public static ProductionOperationResponse InternalServerError(string message) =>
InternalServerError<ProductionOperationResponse>(message);
}

View File

@@ -0,0 +1,17 @@

using SladkieBulkiContrakts.Infrastructure;
using SladkieBulkiContrakts.ViewModels;
namespace SladkieBulkiContrakts.AdapterContracts.OperationResponses;
public class SalaryOperationResponse : OperationResponse
{
public static SalaryOperationResponse OK(List<SalaryViewModel> data) => OK<SalaryOperationResponse, List<SalaryViewModel>>(data);
public static SalaryOperationResponse NoContent() => NoContent<SalaryOperationResponse>();
public static SalaryOperationResponse NotFound(string message) => NotFound<SalaryOperationResponse>(message);
public static SalaryOperationResponse BadRequest(string message) => BadRequest<SalaryOperationResponse>(message);
public static SalaryOperationResponse InternalServerError(string message) => InternalServerError<SalaryOperationResponse>(message);
}

View File

@@ -0,0 +1,19 @@
using SladkieBulkiContrakts.Infrastructure;
using SladkieBulkiContrakts.ViewModels;
namespace SladkieBulkiContrakts.AdapterContracts.OperationResponses;
public class WorkerOperationResponse : OperationResponse
{
public static WorkerOperationResponse OK(List<WorkerViewModel> data) => OK<WorkerOperationResponse, List<WorkerViewModel>>(data);
public static WorkerOperationResponse OK(WorkerViewModel data) => OK<WorkerOperationResponse, WorkerViewModel>(data);
public static WorkerOperationResponse NoContent() => NoContent<WorkerOperationResponse>();
public static WorkerOperationResponse NotFound(string message) => NotFound<WorkerOperationResponse>(message);
public static WorkerOperationResponse BadRequest(string message) => BadRequest<WorkerOperationResponse>(message);
public static WorkerOperationResponse InternalServerError(string message) => InternalServerError<WorkerOperationResponse>(message);
}

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.BindingModels;
public class IngredientBindingModel
{
public string? Id { get; set; }
public string? NameIngredients { get; set; }
public string? SizeInit { get; set; }
public double InitPrice { get; set; }
}

View File

@@ -0,0 +1,14 @@
namespace SladkieBulkiContrakts.BindingModels;
public class PostBindingModel
{
public string? Id { get; set; }
public string? PostId => Id;
public string? PostName { get; set; }
public string? PostType { get; set; }
public string? ConfigurationJson { get; set; }
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.BindingModels;
public class ProductBindingModel
{
public string? Id { get; set; }
public string? Name { get; set; }
public string? Description { get; set; }
public double UnitPrice { get; set; }
public string? ProductType { get; set; }
public List<IngredientBindingModel> Ingredients { get; set; } = new();
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.BindingModels;
public class ProductionBindingModel
{
public string? Id { get; set; }
public DateTime ProductionDate { get; set; }
public int Count { get; set; }
public double Sum { get; set; }
public string WorkerId { get; set; } = default!;
public string ProductId { get; set; } = default!;
}

View File

@@ -0,0 +1,11 @@
namespace SladkieBulkiContrakts.BindingModels;
public class WorkerBindingModel
{
public string? Id { get; set; }
public string? FIO { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
public string? PostId { get; set; }
public string? Email { get; set; }
}

View File

@@ -0,0 +1,23 @@
using SladkieBulkiContrakts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.BusinessLogicsContracts;
public interface IIngredientBusinessLogicContract
{
List<IngredientDataModel> GetAllIngredients();
List<IngredientDataModel> GetIngredientsBySizeUnit(string sizeUnit);
IngredientDataModel? GetIngredientByName(string name);
IngredientDataModel? GetIngredientById(string id);
void InsertIngredient(IngredientDataModel ingredientDataModel);
void UpdateIngredient(IngredientDataModel ingredientDataModel);
}

View File

@@ -0,0 +1,20 @@
using SladkieBulkiContrakts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.BusinessLogicsContracts;
public interface IPostBusinessLogicContract
{
List<PostDataModel> GetAllPosts();
List<PostDataModel> GetAllDataOfPost(string postId);
PostDataModel GetPostByData(string data);
void InsertPost(PostDataModel postDataModel);
void UpdatePost(PostDataModel postDataModel);
void DeletePost(string id);
void RestorePost(string id);
}

View File

@@ -0,0 +1,19 @@
using SladkieBulkiContrakts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.BusinessLogicsContracts;
public interface IProductBusinessLogicContract
{
List<ProductDataModel> GetAllProducts(bool onlyActive = true);
List<ProductHistoryDataModel> GetProductHistoryByProduct(string productId);
ProductDataModel GetProductByData(string data);
void InsertProduct(ProductDataModel productDataModel);
void UpdateProduct(ProductDataModel productDataModel);
void DeleteProduct(string id);
}

View File

@@ -0,0 +1,18 @@
using SladkieBulkiContrakts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.BusinessLogicsContracts;
public interface IProductionBusinessLogicContract
{
List<ProductionDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate);
List<ProductionDataModel> GetAllSalesByWorkerByPeriod(string workerId, DateTime fromDate, DateTime toDate);
List<ProductionDataModel> GetAllSalesByProductByPeriod(string productId, DateTime fromDate, DateTime toDate);
ProductionDataModel GetProductionByData(string data);
void InsertProduction(ProductionDataModel productionDataModel);
void CancelProduction(string id);
}

View File

@@ -0,0 +1,15 @@
using SladkieBulkiContrakts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.BusinessLogicsContracts;
public interface ISalaryBusinessLogicContract
{
List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate);
List<SalaryDataModel> GetAllSalariesByPeriodByWorker(DateTime fromDate, DateTime toDate, string workerId);
void CalculateSalaryByMounth(DateTime date);
}

View File

@@ -0,0 +1,20 @@
using SladkieBulkiContrakts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.BusinessLogicsContracts;
public interface IWorkerBusinessLogicContract
{
List<WorkerDataModel> GetAllWorkers(bool onlyActive = true);
List<WorkerDataModel> GetAllWorkersByPost(string postId, bool onlyActive = true);
List<WorkerDataModel> GetAllWorkersByBirthDate(DateTime fromDate, DateTime toDate, bool onlyActive = true);
List<WorkerDataModel> GetAllWorkersByEmploymentDate(DateTime fromDate, DateTime toDate, bool onlyActive = true);
WorkerDataModel GetWorkerByData(string data);
void InsertWorker(WorkerDataModel workerDataModel);
void UpdateWorker(WorkerDataModel workerDataModel);
void DeleteWorker(string id);
}

View File

@@ -0,0 +1,31 @@
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.DataModels;
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()
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
if (NameIngredients.IsEmpty())
throw new ValidationException("Field NameIngredients is empty");
if (SizeInit.IsEmpty())
throw new ValidationException("Field SizeInit is empty");
if (InitPrice <= 0)
throw new ValidationException("Field InitPrice must be greater than zero");
}
}

View File

@@ -0,0 +1,25 @@
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.DataModels;
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()
{
if (IngredienId.IsEmpty())
throw new ValidationException("Field IngredienId is empty");
if (!IngredienId.IsGuid())
throw new ValidationException("The value in the field IngredienId is not a unique identifier");
if (OldPrice <= 0)
throw new ValidationException("Field OldPrice is less than or equal to 0");
}
}

View File

@@ -0,0 +1,60 @@
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using SladkieBulkiContrakts.Enums;
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Infrastructure;
using SladkieBulkiContrakts.Infrastructure.PostConfigurations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace SladkieBulkiContrakts.DataModels;
public class PostDataModel(string postId, string postName, PostType postType, PostConfiguration configuration) : IValidation
{
public string Id { get; private set; } = postId;
public string PostName { get; private set; } = postName;
public PostType PostType { get; private set; } = postType;
public PostConfiguration ConfigurationModel { get; private set; } = configuration;
public PostDataModel(string postId, string postName, PostType postType, string configurationJson) : this(postId, postName, postType, (PostConfiguration)null)
{
var obj = JToken.Parse(configurationJson);
if (obj is not null)
{
ConfigurationModel = obj.Value<string>("Type") switch
{
nameof(ManufacturerPostConfiguration) => JsonConvert.DeserializeObject<ManufacturerPostConfiguration>(configurationJson)!,
nameof(PackerPostConfiguration) => JsonConvert.DeserializeObject<PackerPostConfiguration>(configurationJson)!,
_ => JsonConvert.DeserializeObject<PostConfiguration>(configurationJson)!,
};
}
}
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
if (PostName.IsEmpty())
throw new ValidationException("Field PostName is empty");
if (PostType == PostType.None)
throw new ValidationException("Field PostType is empty");
if (ConfigurationModel is null)
throw new ValidationException("Field ConfigurationModel is not initialized");
if (ConfigurationModel!.Rate <= 0)
throw new ValidationException("Field Rate is less or equal zero");
}
}

View File

@@ -0,0 +1,72 @@
using SladkieBulkiContrakts.Enums;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Infrastructure;
using System.Collections.Generic;
using System.Diagnostics;
namespace SladkieBulkiContrakts.DataModels;
public class ProductDataModel : IValidation
{
public string Id { get; private set; }
public string Name { get; private set; }
public string Description { get; private set; }
public ProductType ProductType { get; private set; }
public List<ProductIngredientDataModel> Ingredients { get; private set; }
public double UnitPrice { get; private set; }
public bool IsDeleted { get; private set; }
// 👇 Пустой конструктор для сериализации, EF, AutoMapper
public ProductDataModel()
{
Ingredients = new List<ProductIngredientDataModel>();
}
public ProductDataModel(string id, string name, string description, ProductType productType, List<ProductIngredientDataModel> ingredients, double unitPrice, bool isDeleted)
{
Id = id;
Name = name;
Description = description;
ProductType = productType;
Ingredients = ingredients ?? new List<ProductIngredientDataModel>();
UnitPrice = unitPrice;
IsDeleted = isDeleted;
}
public ProductDataModel(
string id,
string name,
string description,
ProductType productType,
List<ProductIngredientDataModel> ingredients,
double unitPrice)
: this(id, name, description, productType, ingredients, unitPrice, false) { }
// Валидация
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
if (Name.IsEmpty())
throw new ValidationException("Field Name is empty");
if (Description.IsEmpty())
throw new ValidationException("Field Description is empty");
if (ProductType == ProductType.None)
throw new ValidationException("Field ProductType is empty");
if (UnitPrice <= 0)
throw new ValidationException("Field UnitPrice must be greater than zero");
if (Ingredients == null || Ingredients.Count == 0)
throw new ValidationException("No ingredients defined");
}
}

View File

@@ -0,0 +1,26 @@
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.DataModels;
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()
{
if (ProductId.IsEmpty())
throw new ValidationException("Field ProductId is empty");
if (!ProductId.IsGuid())
throw new ValidationException("The value in the field ProductId is not a unique identifier");
if (OldPrice <= 0)
throw new ValidationException("Field OldPrice is less than or equal to 0");
}
}

View File

@@ -0,0 +1,29 @@
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.DataModels;
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()
{
if (ProductId.IsEmpty())
throw new ValidationException("Field ProductId is empty");
if (!ProductId.IsGuid())
throw new ValidationException("The value in the field ProductId is not a unique identifier");
if (IngredientId.IsEmpty())
throw new ValidationException("Field IngredientId is empty");
if (!IngredientId.IsGuid())
throw new ValidationException("The value in the field IngredientId is not a unique identifier");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
}
}

View File

@@ -0,0 +1,34 @@
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Infrastructure;
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;
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()
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
if (ProductionDate > DateTime.Now)
throw new ValidationException("ProductionDate cannot be in the future");
if (Count <= 0)
throw new ValidationException("Field Count must be greater than zero");
if (WorkerId.IsEmpty())
throw new ValidationException("Field WorkerId is empty");
if (!WorkerId.IsGuid())
throw new ValidationException("The value in the field WorkerId is not a unique identifier");
if (ProductId.IsEmpty())
throw new ValidationException("Field ProductId is empty");
if (!ProductId.IsGuid())
throw new ValidationException("The value in the field ProductId is not a unique identifier");
if (Sum <= 0)
throw new ValidationException("Field Sum is less than or equal to 0");
}
}

View File

@@ -0,0 +1,32 @@
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.DataModels;
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;
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()
{
if (WorkerId.IsEmpty())
throw new ValidationException("Field WorkerId is empty");
if (!WorkerId.IsGuid())
throw new ValidationException("The value in the field WorkerId is not a unique identifier");
if (WorkerSalary <= 0)
throw new ValidationException("Field Salary is less than or equal to 0");
}
}

View File

@@ -0,0 +1,57 @@
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;
using System.Xml;
using System.Text.RegularExpressions;
using System.Numerics;
using Microsoft.Extensions.Hosting;
namespace SladkieBulkiContrakts.DataModels;
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;
public DateTime EmploymentDate { get; private set; } = employmentDate;
public bool IsDeleted { get; private set; } = isDeleted;
public string Email { get; private set; } = email;
public string PostName => _post?.PostName ?? string.Empty;
public WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted, string email, PostDataModel post) : this(id, fio, postId, birthDate, employmentDate, isDeleted, email)
{
_post = post;
}
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()
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
if (FIO.IsEmpty())
throw new ValidationException("Field FIO is empty");
if (PostId.IsEmpty())
throw new ValidationException("Field PostId is empty");
if (!PostId.IsGuid())
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($"Minors cannot be hired (BirthDate = { BirthDate.ToShortDateString() })");
if (EmploymentDate.Date < BirthDate.Date)
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($"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("Field Email is not a email");
}
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.Enums;
public enum PostType
{
None = 0,
Preform = 1, // Заготовщик
Manufacturer = 2, // Изготовитель
Packer = 3 // Упаковщик
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.Enums;
public enum ProductType
{
None = 0,
Workpiece = 1, // Заготовка
Production = 2, // Производство
Packaging = 3 // Упаковка
}

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 ElementDeletedException : Exception
{
public ElementDeletedException(string id) : base($"Cannot modify a deleted item (id: {id})") { }
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.Exceptions;
public class ElementExistsException : Exception
{
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

@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.Exceptions;
public class ElementNotFoundException : Exception
{
public string Value { get; private set; }
public ElementNotFoundException(string value) : base($"Element not found at value = { value}")
{
Value = value;
}
}

View File

@@ -0,0 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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

@@ -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 StorageException : Exception
{
public StorageException(Exception ex) : base($"Error while working in storage: { ex.Message}", ex) { }
}

View File

@@ -0,0 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class ValidationException(string message) : Exception(message)
{
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.Extensions;
public static class DateTimeExtensions
{
public static bool IsDateNotOlder(this DateTime date, DateTime olderDate)
{
return date >= olderDate;
}
}

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.Extensions;
public static class StringExtensions
{
public static bool IsEmpty(this string str)
{
return string.IsNullOrWhiteSpace(str);
}
public static bool IsGuid(this string str)
{
return Guid.TryParse(str, out _);
}
}

View File

@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.Infrastructure;
public interface IConfigurationDatabase
{
string ConnectionString { get; }
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.Infrastructure;
public interface IConfigurationSalary
{
double ExtraSaleSum { get; }
int MaxParallelThreads { get; }
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.Infrastructure;
public interface IValidation
{
void Validate();
}

View File

@@ -0,0 +1,42 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.Infrastructure;
public class OperationResponse
{
protected HttpStatusCode StatusCode { get; set; }
protected object? Result { get; set; }
public IActionResult GetResponse(HttpRequest request, HttpResponse response)
{
ArgumentNullException.ThrowIfNull(request);
ArgumentNullException.ThrowIfNull(response);
response.StatusCode = (int)StatusCode;
if (Result is null)
{
return new StatusCodeResult((int)StatusCode);
}
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 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 };
protected static TResult NotFound<TResult>(string? errorMessage = null) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.NotFound, Result = errorMessage };
protected static TResult InternalServerError<TResult>(string? errorMessage = null) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.InternalServerError, Result = errorMessage };
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.Infrastructure.PostConfigurations;
public class ManufacturerPostConfiguration : PostConfiguration
{
public override string Type => nameof(ManufacturerPostConfiguration);
public double SalePercent { get; set; }
public double BonusForExtraSales { get; set; }
}

View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.Infrastructure.PostConfigurations;
public class PackerPostConfiguration : PostConfiguration
{
public override string Type => nameof(PackerPostConfiguration);
public double PersonalCountPack { get; set; }
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.Infrastructure.PostConfigurations;
public class PostConfiguration
{
public virtual string Type => nameof(PostConfiguration);
public double Rate { get; set; }
}

View File

@@ -6,4 +6,10 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<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" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,25 @@
using SladkieBulkiContrakts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.StoragesContarcts;
public interface IIngredientStorageContract
{
List<IngredientDataModel> GetList();
// Получить ингредиенты по единице измерения
List<IngredientDataModel>? GetElementBySizeUnit(string sizeInit);
IngredientDataModel? GetElementById(string id);
IngredientDataModel? GetElementByName(string name);
void AddElement(IngredientDataModel ingredientDataModel);
void UpdElement(IngredientDataModel ingredientDataModel);
}

View File

@@ -0,0 +1,21 @@
using SladkieBulkiContrakts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.StoragesContarcts;
public interface IPostStorageContract
{
List<PostDataModel> GetList();
List<PostDataModel> GetPostWithHistory(string postId);
PostDataModel? GetElementById(string id);
PostDataModel? GetElementByName(string name);
void AddElement(PostDataModel postDataModel);
void UpdElement(PostDataModel postDataModel);
void DelElement(string id);
void ResElement(string id);
}

View File

@@ -0,0 +1,21 @@
using SladkieBulkiContrakts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.StoragesContarcts;
public interface IProductStorageContract
{
List<ProductDataModel> GetList(bool onlyActive = true);
List<ProductHistoryDataModel> GetHistoryByProductId(string productId);
ProductDataModel? GetElementById(string id);
ProductDataModel? GetElementByName(string name);
void AddElement(ProductDataModel productDataModel);
void UpdElement(ProductDataModel productDataModel);
void DelElement(string id);
}

View File

@@ -0,0 +1,16 @@
using SladkieBulkiContrakts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.StoragesContarcts;
public interface IProductionStorageContract
{
List<ProductionDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? workerId = null, string? productId = null);
ProductionDataModel? GetElementById(string id);
void AddElement(ProductionDataModel productionDataModel);
void DelElement(string id);
}

View File

@@ -0,0 +1,14 @@
using SladkieBulkiContrakts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.StoragesContarcts;
public interface ISalaryStorageContract
{
List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? workerId = null);
void AddElement(SalaryDataModel salaryDataModel);
}

View File

@@ -0,0 +1,19 @@
using SladkieBulkiContrakts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.StoragesContarcts;
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);
WorkerDataModel? GetElementByFIO(string fio);
void AddElement(WorkerDataModel workerDataModel);
void UpdElement(WorkerDataModel workerDataModel);
void DelElement(string id);
int GetWorkerTrend(DateTime fromPeriod, DateTime toPeriod);
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.ViewModels;
public class IngredientViewModel
{
public string Id { get; set; } = string.Empty;
public string NameIngredients { get; set; } = string.Empty;
public string SizeInit { get; set; } = string.Empty;
public double InitPrice { get; set; }
}

View File

@@ -0,0 +1,12 @@
namespace SladkieBulkiContrakts.ViewModels;
public class PostViewModel
{
public required string Id { get; set; }
public required string PostName { get; set; }
public required string PostType { get; set; }
public required string Configuration { get; set; }
}

View File

@@ -0,0 +1,19 @@
using SladkieBulkiContrakts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.ViewModels;
public class ProductViewModel
{
public required string Id { get; set; }
public required string Name { get; set; }
public required string Description { get; set; }
public required double UnitPrice { get; set; }
public required string ProductType { get; set; }
public bool IsDeleted { get; set; }
public List<IngredientViewModel> Ingredients { get; set; } = [];
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.ViewModels;
public class ProductionViewModel
{
public string Id { get; set; } = default!;
public DateTime ProductionDate { get; set; }
public int Count { get; set; }
public double Sum { get; set; }
public string WorkerId { get; set; } = default!;
public string ProductId { get; set; } = default!;
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.ViewModels;
public class SalaryViewModel
{
public required string WorkerId { get; set; }
public required string WorkerFIO { get; set; }
public DateTime SalaryDate { get; set; }
public double WorkerSalary { get; set; }
}

View File

@@ -0,0 +1,14 @@
namespace SladkieBulkiContrakts.ViewModels;
public class WorkerViewModel
{
public required string Id { get; set; }
public required string FIO { get; set; }
public required string PostId { get; set; }
public required string PostName { get; set; }
public required string Email { get; set; }
public bool IsDeleted { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
}

View File

@@ -0,0 +1,13 @@
using SladkieBulkiContrakts.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiDatabase;
class DefaultConfigurationDatabase : IConfigurationDatabase
{
public string ConnectionString => "";
}

View File

@@ -0,0 +1,138 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.StoragesContarcts;
using SladkieBulkiDatabase.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiDatabase.Implementations;
internal class IngredientStorageContract : IIngredientStorageContract
{
private readonly SladkieBulkiDbContext _dbContext;
private readonly Mapper _mapper;
public IngredientStorageContract(SladkieBulkiDbContext sladkieBulkiDbContext)
{
_dbContext = sladkieBulkiDbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Ingredient, IngredientDataModel>();
cfg.CreateMap<IngredientDataModel, Ingredient>();
});
_mapper = new Mapper(config);
}
public List<IngredientDataModel> GetList()
{
try
{
return [.. _dbContext.Ingredients.Select(x => _mapper.Map<IngredientDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public IngredientDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<IngredientDataModel>(GetIngredientById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public IngredientDataModel? GetElementByName(string nameIngredients)
{
try
{
return _mapper.Map<IngredientDataModel>(_dbContext.Ingredients.FirstOrDefault(x => x.NameIngredients == nameIngredients));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public List<IngredientDataModel>? GetElementBySizeUnit(string sizeInit)
{
try
{
var ingredients = _dbContext.Ingredients.Where(x => x.SizeInit == sizeInit).ToList();
return _mapper.Map<List<IngredientDataModel>>(ingredients);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(IngredientDataModel ingredientDataModel)
{
try
{
_dbContext.Ingredients.Add(_mapper.Map<Ingredient>(ingredientDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
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);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(IngredientDataModel ingredientDataModel)
{
try
{
var element = GetIngredientById(ingredientDataModel.Id) ?? throw new ElementNotFoundException(ingredientDataModel.Id);
_dbContext.Ingredients.Update(_mapper.Map(ingredientDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Ingredients_NameIngridients" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("NameIngredients", ingredientDataModel.NameIngredients);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Ingredient? GetIngredientById(string id) => _dbContext.Ingredients.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,191 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.StoragesContarcts;
using SladkieBulkiDatabase.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiDatabase.Implementations;
internal class PostStorageContract : IPostStorageContract
{
private readonly SladkieBulkiDbContext _dbContext;
private readonly Mapper _mapper;
public PostStorageContract(SladkieBulkiDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Post, PostDataModel>()
.ForMember(x => x.Id, x => x.MapFrom(src => src.PostId));
cfg.CreateMap<PostDataModel, Post>()
.ForMember(x => x.Id, x => x.Ignore())
.ForMember(x => x.PostId, x => x.MapFrom(src => src.Id))
.ForMember(x => x.IsActual, x => x.MapFrom(src => true))
.ForMember(x => x.ChangeDate, x => x.MapFrom(src => DateTime.UtcNow))
.ForMember(x => x.Configuration, x => x.MapFrom(src => src.ConfigurationModel));
});
_mapper = new Mapper(config);
}
public List<PostDataModel> GetList()
{
try
{
return [.. _dbContext.Posts.Select(x => _mapper.Map<PostDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public List<PostDataModel> GetPostWithHistory(string postId)
{
try
{
return [.. _dbContext.Posts.Where(x => x.PostId == postId).Select(x => _mapper.Map<PostDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public PostDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostId == id && x.IsActual));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public PostDataModel? GetElementByName(string name)
{
try
{
return _mapper.Map<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostName == name && x.IsActual));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(PostDataModel postDataModel)
{
try
{
_dbContext.Posts.Add(_mapper.Map<Post>(postDataModel));
_dbContext.SaveChanges();
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
{
_dbContext.ChangeTracker.Clear();
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);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(PostDataModel postDataModel)
{
try
{
var transaction = _dbContext.Database.BeginTransaction();
try
{
var element = GetPostById(postDataModel.Id) ?? throw new ElementNotFoundException(postDataModel.Id);
if (!element.IsActual)
{
throw new ElementDeletedException(postDataModel.Id);
}
element.IsActual = false;
_dbContext.SaveChanges();
var newElement = _mapper.Map<Post>(postDataModel);
_dbContext.Posts.Add(newElement);
_dbContext.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostName", postDataModel.PostName);
}
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetPostById(id) ?? throw new ElementNotFoundException(id);
if (!element.IsActual)
{
throw new ElementDeletedException(id);
}
element.IsActual = false;
_dbContext.SaveChanges();
}
catch
{
_dbContext.ChangeTracker.Clear();
throw;
}
}
public void ResElement(string id)
{
try
{
var element = GetPostById(id) ?? throw new ElementNotFoundException(id);
element.IsActual = true;
_dbContext.SaveChanges();
}
catch
{
_dbContext.ChangeTracker.Clear();
throw;
}
}
private Post? GetPostById(string id) => _dbContext.Posts.Where(x => x.PostId == id).OrderByDescending(x => x.ChangeDate).FirstOrDefault();
}

View File

@@ -0,0 +1,213 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.StoragesContarcts;
using SladkieBulkiDatabase.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiDatabase.Implementations;
internal class ProductStorageContract : IProductStorageContract
{
private readonly SladkieBulkiDbContext _dbContext;
private readonly Mapper _mapper;
public ProductStorageContract(SladkieBulkiDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<ProductIngredient, ProductIngredientDataModel>();
cfg.CreateMap<ProductIngredientDataModel, ProductIngredient>();
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);
}
public List<ProductDataModel> GetList(bool onlyActive = true)
{
try
{
var query = _dbContext.Products.Include(x => x.ProductIngredients).AsQueryable();
if (onlyActive)
{
query = query.Where(x => !x.IsDeleted);
}
return [.. query.Select(x => _mapper.Map<ProductDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public List<ProductHistoryDataModel> GetHistoryByProductId(string productId)
{
try
{
return _dbContext.ProductHistories
.Where(x => x.ProductId == productId)
.OrderByDescending(x => x.ChangeDate)
.Select(x => _mapper.Map<ProductHistoryDataModel>(x)).ToList();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ProductDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<ProductDataModel>(GetProductById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ProductDataModel? GetElementByName(string name)
{
try
{
return _mapper.Map<ProductDataModel>(
_dbContext.Products.FirstOrDefault(x => x.Name == name && !x.IsDeleted));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(ProductDataModel productDataModel)
{
try
{
_dbContext.Products.Add(_mapper.Map<Product>(productDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
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);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(ProductDataModel productDataModel)
{
try
{
using var transaction = _dbContext.Database.BeginTransaction();
try
{
var element = GetProductById(productDataModel.Id)
?? throw new ElementNotFoundException(productDataModel.Id);
if (element.IsDeleted)
throw new ElementDeletedException(productDataModel.Id);
// Проверяем, если цена изменилась, то добавляем её в историю
if (element.UnitPrice != productDataModel.UnitPrice)
{
_dbContext.ProductHistories.Add(new ProductHistory
{
ProductId = element.Id,
OldPrice = element.UnitPrice
});
_dbContext.SaveChanges();
}
// Обновляем флаг IsDeleted, если он изменился
if (element.IsDeleted != productDataModel.IsDeleted)
{
element.IsDeleted = productDataModel.IsDeleted;
}
// Маппим остальные данные
_mapper.Map(productDataModel, element);
_dbContext.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException postgresEx && postgresEx.SqlState == "23505" && postgresEx.ConstraintName == "IX_Products_Name_IsDeleted")
{
// Обработка ошибки уникальности
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Name", productDataModel.Name);
}
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
{
// Перекидываем только специфичные ошибки
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
// В случае других исключений — логируем ошибку
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetProductById(id) ?? throw new ElementNotFoundException(id);
element.IsDeleted = true;
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Product? GetProductById(string id) =>
_dbContext.Products.FirstOrDefault(x => x.Id == id && !x.IsDeleted);
}

View File

@@ -0,0 +1,106 @@
using AutoMapper;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.StoragesContarcts;
using SladkieBulkiDatabase.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiDatabase.Implementations;
internal class ProductionStorageContract : IProductionStorageContract
{
private readonly SladkieBulkiDbContext _dbContext;
private readonly Mapper _mapper;
public ProductionStorageContract(SladkieBulkiDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Production, ProductionDataModel>();
cfg.CreateMap<ProductionDataModel, Production>()
.ForMember(dest => dest.Worker, opt => opt.Ignore())
.ForMember(dest => dest.Product, opt => opt.Ignore());
});
_mapper = new Mapper(config);
}
public List<ProductionDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? workerId = null, string? productId = null)
{
try
{
var query = _dbContext.Productions.AsQueryable();
if (startDate is not null && endDate is not null)
{
query = query.Where(p => p.ProductionDate >= startDate && p.ProductionDate < endDate);
}
if (!string.IsNullOrEmpty(workerId))
{
query = query.Where(p => p.WorkerId == workerId);
}
if (!string.IsNullOrEmpty(productId))
{
query = query.Where(p => p.ProductId == productId);
}
return [.. query.Select(p => _mapper.Map<ProductionDataModel>(p))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ProductionDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<ProductionDataModel>(GetProductionById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(ProductionDataModel productionDataModel)
{
try
{
_dbContext.Productions.Add(_mapper.Map<Production>(productionDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
var element = GetProductionById(id);
if (element == null)
{
throw new ElementNotFoundException($"Element not found at value = {id}");
}
_dbContext.Productions.Remove(element);
_dbContext.SaveChanges();
}
private Production? GetProductionById(string id)
{
return _dbContext.Productions.FirstOrDefault(p => p.Id == id);
}
}

View File

@@ -0,0 +1,59 @@
using AutoMapper;
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.StoragesContarcts;
using SladkieBulkiDatabase.Models;
using SladkieBulkiDatabase;
using Microsoft.EntityFrameworkCore;
internal class SalaryStorageContract : ISalaryStorageContract
{
private readonly SladkieBulkiDbContext _dbContext;
private readonly Mapper _mapper;
public SalaryStorageContract(SladkieBulkiDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Worker, WorkerDataModel>();
cfg.CreateMap<Salary, SalaryDataModel>();
cfg.CreateMap<SalaryDataModel, Salary>()
.ForMember(dest => dest.WorkerSalary, opt => opt.MapFrom(src => src.WorkerSalary));
});
_mapper = new Mapper(config);
}
public List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? workerId = null)
{
try
{
var query = _dbContext.Salaries.Include(x => x.Worker)
.Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate);
if (workerId is not null)
{
query = query.Where(x => x.WorkerId == workerId);
}
return [.. query.Select(x => _mapper.Map<SalaryDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(SalaryDataModel salaryDataModel)
{
try
{
_dbContext.Salaries.Add(_mapper.Map<Salary>(salaryDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
}

View File

@@ -0,0 +1,168 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.StoragesContarcts;
using SladkieBulkiDatabase.Models;
namespace SladkieBulkiDatabase.Implementations;
internal class WorkerStorageContract : IWorkerStorageContract
{
private readonly SladkieBulkiDbContext _dbContext;
private readonly Mapper _mapper;
public WorkerStorageContract(SladkieBulkiDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Post, PostDataModel>()
.ForMember(x => x.Id, x => x.MapFrom(src => src.PostId));
cfg.CreateMap<Worker, WorkerDataModel>();
cfg.CreateMap<WorkerDataModel, Worker>();
});
_mapper = new Mapper(config);
}
public List<WorkerDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null)
{
try
{
var query = _dbContext.Workers.AsQueryable();
if (onlyActive)
{
query = query.Where(x => !x.IsDeleted);
}
if (postId is not null)
{
query = query.Where(x => x.PostId == postId);
}
if (fromBirthDate is not null && toBirthDate is not null)
{
query = query.Where(x => x.BirthDate >= fromBirthDate && x.BirthDate <= toBirthDate);
}
if (fromEmploymentDate is not null && toEmploymentDate is not null)
{
query = query.Where(x => x.EmploymentDate >= fromEmploymentDate && x.EmploymentDate <= toEmploymentDate);
}
return [.. JoinPost(query).Select(x => _mapper.Map<WorkerDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public WorkerDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<WorkerDataModel>(GetWorkerById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public WorkerDataModel? GetElementByFIO(string fio)
{
try
{
return _mapper.Map<WorkerDataModel>(AddPost(_dbContext.Workers.FirstOrDefault(x => x.FIO == fio && !x.IsDeleted)));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(WorkerDataModel workerDataModel)
{
try
{
_dbContext.Workers.Add(_mapper.Map<Worker>(workerDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", workerDataModel.Id);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(WorkerDataModel workerDataModel)
{
try
{
var element = GetWorkerById(workerDataModel.Id) ?? throw new ElementNotFoundException(workerDataModel.Id);
_dbContext.Workers.Update(_mapper.Map(workerDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetWorkerById(id) ?? throw new ElementNotFoundException(id);
element.IsDeleted = true;
element.DateOfDelete = DateTime.UtcNow;
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public int GetWorkerTrend(DateTime fromPeriod, DateTime toPeriod)
{
try
{
var countWorkersOnBegining = _dbContext.Workers.Count(x => x.EmploymentDate < fromPeriod && (!x.IsDeleted || x.DateOfDelete > fromPeriod));
var countWorkersOnEnding = _dbContext.Workers.Count(x => x.EmploymentDate < toPeriod && (!x.IsDeleted || x.DateOfDelete > toPeriod));
return countWorkersOnEnding - countWorkersOnBegining;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Worker? GetWorkerById(string id) => AddPost(_dbContext.Workers.FirstOrDefault(x => x.Id == id && !x.IsDeleted));
private IQueryable<Worker> JoinPost(IQueryable<Worker> query)
=> query.GroupJoin(_dbContext.Posts.Where(x => x.IsActual), x => x.PostId, y => y.PostId, (x, y) => new { Worker = x, Post = y })
.SelectMany(xy => xy.Post.DefaultIfEmpty(), (x, y) => x.Worker.AddPost(y));
private Worker? AddPost(Worker? worker)
=> worker?.AddPost(_dbContext.Posts.FirstOrDefault(x => x.PostId == worker.PostId && x.IsActual));
}

View File

@@ -0,0 +1,363 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using SladkieBulkiDatabase;
#nullable disable
namespace SladkieBulkiDatabase.Migrations
{
[DbContext(typeof(SladkieBulkiDbContext))]
[Migration("20250520155308_FirstMigration")]
partial class FirstMigration
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.4")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("SladkieBulkiDatabase.Models.Ingredient", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<double>("InitPrice")
.HasColumnType("double precision");
b.Property<string>("NameIngredients")
.IsRequired()
.HasColumnType("text");
b.Property<string>("SizeInit")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("NameIngredients")
.IsUnique();
b.ToTable("Ingredients");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.IngredientHistory", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("IngredienId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("OldPrice")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("IngredienId");
b.ToTable("IngredientHistories");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Post", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<bool>("IsActual")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PostName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("PostType")
.HasColumnType("integer");
b.Property<double>("Salary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("PostId", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.HasIndex("PostName", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.ToTable("Posts");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Product", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int>("ProductType")
.HasColumnType("integer");
b.Property<int>("UnitPrice")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("Name", "IsDeleted")
.IsUnique()
.HasFilter("\"IsDeleted\" = FALSE");
b.ToTable("Products");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.ProductHistory", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("OldPrice")
.HasColumnType("double precision");
b.Property<string>("ProductId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ProductId");
b.ToTable("ProductHistories");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.ProductIngredient", b =>
{
b.Property<string>("ProductId")
.HasColumnType("text");
b.Property<string>("IngredientId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.HasKey("ProductId", "IngredientId");
b.HasIndex("IngredientId");
b.ToTable("ProductIngredients");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Production", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<string>("ProductId")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("ProductionDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ProductId");
b.HasIndex("WorkerId");
b.ToTable("Productions");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Salary", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("SalaryDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("WorkerSalary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("WorkerId");
b.ToTable("Salaries");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Worker", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("BirthDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("EmploymentDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Workers");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.IngredientHistory", b =>
{
b.HasOne("SladkieBulkiDatabase.Models.Ingredient", "Ingredient")
.WithMany("IngredientHistory")
.HasForeignKey("IngredienId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Ingredient");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.ProductHistory", b =>
{
b.HasOne("SladkieBulkiDatabase.Models.Product", "Product")
.WithMany("ProductHistories")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.ProductIngredient", b =>
{
b.HasOne("SladkieBulkiDatabase.Models.Ingredient", "Ingredient")
.WithMany("ProductIngredients")
.HasForeignKey("IngredientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SladkieBulkiDatabase.Models.Product", "Product")
.WithMany("ProductIngredients")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Ingredient");
b.Navigation("Product");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Production", b =>
{
b.HasOne("SladkieBulkiDatabase.Models.Product", "Product")
.WithMany("Productions")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SladkieBulkiDatabase.Models.Worker", "Worker")
.WithMany("Productions")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
b.Navigation("Worker");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Salary", b =>
{
b.HasOne("SladkieBulkiDatabase.Models.Worker", "Worker")
.WithMany("Salaries")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Worker");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Ingredient", b =>
{
b.Navigation("IngredientHistory");
b.Navigation("ProductIngredients");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Product", b =>
{
b.Navigation("ProductHistories");
b.Navigation("ProductIngredients");
b.Navigation("Productions");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Worker", b =>
{
b.Navigation("Productions");
b.Navigation("Salaries");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,280 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SladkieBulkiDatabase.Migrations
{
/// <inheritdoc />
public partial class FirstMigration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Ingredients",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
NameIngredients = table.Column<string>(type: "text", nullable: false),
SizeInit = table.Column<string>(type: "text", nullable: false),
InitPrice = table.Column<double>(type: "double precision", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Ingredients", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Posts",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
PostId = table.Column<string>(type: "text", nullable: false),
PostName = table.Column<string>(type: "text", nullable: false),
PostType = table.Column<int>(type: "integer", nullable: false),
Salary = table.Column<double>(type: "double precision", nullable: false),
IsActual = table.Column<bool>(type: "boolean", nullable: false),
ChangeDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Posts", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Products",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
Name = table.Column<string>(type: "text", nullable: false),
Description = table.Column<string>(type: "text", nullable: false),
ProductType = table.Column<int>(type: "integer", nullable: false),
UnitPrice = table.Column<int>(type: "integer", nullable: false),
IsDeleted = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Products", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Workers",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
FIO = table.Column<string>(type: "text", nullable: false),
PostId = table.Column<string>(type: "text", nullable: false),
BirthDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
EmploymentDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
IsDeleted = table.Column<bool>(type: "boolean", nullable: false),
Email = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Workers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "IngredientHistories",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
IngredienId = table.Column<string>(type: "text", nullable: false),
OldPrice = table.Column<double>(type: "double precision", nullable: false),
ChangeDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_IngredientHistories", x => x.Id);
table.ForeignKey(
name: "FK_IngredientHistories_Ingredients_IngredienId",
column: x => x.IngredienId,
principalTable: "Ingredients",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "ProductHistories",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
ProductId = table.Column<string>(type: "text", nullable: false),
OldPrice = table.Column<double>(type: "double precision", nullable: false),
ChangeDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ProductHistories", x => x.Id);
table.ForeignKey(
name: "FK_ProductHistories_Products_ProductId",
column: x => x.ProductId,
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "ProductIngredients",
columns: table => new
{
ProductId = table.Column<string>(type: "text", nullable: false),
IngredientId = table.Column<string>(type: "text", nullable: false),
Count = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ProductIngredients", x => new { x.ProductId, x.IngredientId });
table.ForeignKey(
name: "FK_ProductIngredients_Ingredients_IngredientId",
column: x => x.IngredientId,
principalTable: "Ingredients",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ProductIngredients_Products_ProductId",
column: x => x.ProductId,
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Productions",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
ProductionDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
Count = table.Column<int>(type: "integer", nullable: false),
Sum = table.Column<double>(type: "double precision", nullable: false),
WorkerId = table.Column<string>(type: "text", nullable: false),
ProductId = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Productions", x => x.Id);
table.ForeignKey(
name: "FK_Productions_Products_ProductId",
column: x => x.ProductId,
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Productions_Workers_WorkerId",
column: x => x.WorkerId,
principalTable: "Workers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Salaries",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
WorkerId = table.Column<string>(type: "text", nullable: false),
SalaryDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
WorkerSalary = table.Column<double>(type: "double precision", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Salaries", x => x.Id);
table.ForeignKey(
name: "FK_Salaries_Workers_WorkerId",
column: x => x.WorkerId,
principalTable: "Workers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_IngredientHistories_IngredienId",
table: "IngredientHistories",
column: "IngredienId");
migrationBuilder.CreateIndex(
name: "IX_Ingredients_NameIngredients",
table: "Ingredients",
column: "NameIngredients",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Posts_PostId_IsActual",
table: "Posts",
columns: new[] { "PostId", "IsActual" },
unique: true,
filter: "\"IsActual\" = TRUE");
migrationBuilder.CreateIndex(
name: "IX_Posts_PostName_IsActual",
table: "Posts",
columns: new[] { "PostName", "IsActual" },
unique: true,
filter: "\"IsActual\" = TRUE");
migrationBuilder.CreateIndex(
name: "IX_ProductHistories_ProductId",
table: "ProductHistories",
column: "ProductId");
migrationBuilder.CreateIndex(
name: "IX_ProductIngredients_IngredientId",
table: "ProductIngredients",
column: "IngredientId");
migrationBuilder.CreateIndex(
name: "IX_Productions_ProductId",
table: "Productions",
column: "ProductId");
migrationBuilder.CreateIndex(
name: "IX_Productions_WorkerId",
table: "Productions",
column: "WorkerId");
migrationBuilder.CreateIndex(
name: "IX_Products_Name_IsDeleted",
table: "Products",
columns: new[] { "Name", "IsDeleted" },
unique: true,
filter: "\"IsDeleted\" = FALSE");
migrationBuilder.CreateIndex(
name: "IX_Salaries_WorkerId",
table: "Salaries",
column: "WorkerId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "IngredientHistories");
migrationBuilder.DropTable(
name: "Posts");
migrationBuilder.DropTable(
name: "ProductHistories");
migrationBuilder.DropTable(
name: "ProductIngredients");
migrationBuilder.DropTable(
name: "Productions");
migrationBuilder.DropTable(
name: "Salaries");
migrationBuilder.DropTable(
name: "Ingredients");
migrationBuilder.DropTable(
name: "Products");
migrationBuilder.DropTable(
name: "Workers");
}
}
}

View File

@@ -0,0 +1,364 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using SladkieBulkiDatabase;
#nullable disable
namespace SladkieBulkiDatabase.Migrations
{
[DbContext(typeof(SladkieBulkiDbContext))]
[Migration("20250520203540_ChangeFieldsInPost")]
partial class ChangeFieldsInPost
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.4")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("SladkieBulkiDatabase.Models.Ingredient", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<double>("InitPrice")
.HasColumnType("double precision");
b.Property<string>("NameIngredients")
.IsRequired()
.HasColumnType("text");
b.Property<string>("SizeInit")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("NameIngredients")
.IsUnique();
b.ToTable("Ingredients");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.IngredientHistory", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("IngredienId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("OldPrice")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("IngredienId");
b.ToTable("IngredientHistories");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Post", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Configuration")
.IsRequired()
.HasColumnType("jsonb");
b.Property<bool>("IsActual")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PostName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("PostType")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("PostId", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.HasIndex("PostName", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.ToTable("Posts");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Product", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int>("ProductType")
.HasColumnType("integer");
b.Property<int>("UnitPrice")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("Name", "IsDeleted")
.IsUnique()
.HasFilter("\"IsDeleted\" = FALSE");
b.ToTable("Products");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.ProductHistory", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("OldPrice")
.HasColumnType("double precision");
b.Property<string>("ProductId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ProductId");
b.ToTable("ProductHistories");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.ProductIngredient", b =>
{
b.Property<string>("ProductId")
.HasColumnType("text");
b.Property<string>("IngredientId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.HasKey("ProductId", "IngredientId");
b.HasIndex("IngredientId");
b.ToTable("ProductIngredients");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Production", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<string>("ProductId")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("ProductionDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ProductId");
b.HasIndex("WorkerId");
b.ToTable("Productions");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Salary", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("SalaryDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("WorkerSalary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("WorkerId");
b.ToTable("Salaries");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Worker", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("BirthDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("EmploymentDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Workers");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.IngredientHistory", b =>
{
b.HasOne("SladkieBulkiDatabase.Models.Ingredient", "Ingredient")
.WithMany("IngredientHistory")
.HasForeignKey("IngredienId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Ingredient");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.ProductHistory", b =>
{
b.HasOne("SladkieBulkiDatabase.Models.Product", "Product")
.WithMany("ProductHistories")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.ProductIngredient", b =>
{
b.HasOne("SladkieBulkiDatabase.Models.Ingredient", "Ingredient")
.WithMany("ProductIngredients")
.HasForeignKey("IngredientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SladkieBulkiDatabase.Models.Product", "Product")
.WithMany("ProductIngredients")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Ingredient");
b.Navigation("Product");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Production", b =>
{
b.HasOne("SladkieBulkiDatabase.Models.Product", "Product")
.WithMany("Productions")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SladkieBulkiDatabase.Models.Worker", "Worker")
.WithMany("Productions")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
b.Navigation("Worker");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Salary", b =>
{
b.HasOne("SladkieBulkiDatabase.Models.Worker", "Worker")
.WithMany("Salaries")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Worker");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Ingredient", b =>
{
b.Navigation("IngredientHistory");
b.Navigation("ProductIngredients");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Product", b =>
{
b.Navigation("ProductHistories");
b.Navigation("ProductIngredients");
b.Navigation("Productions");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Worker", b =>
{
b.Navigation("Productions");
b.Navigation("Salaries");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,40 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SladkieBulkiDatabase.Migrations
{
/// <inheritdoc />
public partial class ChangeFieldsInPost : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Salary",
table: "Posts");
migrationBuilder.AddColumn<string>(
name: "Configuration",
table: "Posts",
type: "jsonb",
nullable: false,
defaultValue: "{\"Rate\": 0, \"Type\": \"PostConfiguration\"}");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Configuration",
table: "Posts");
migrationBuilder.AddColumn<double>(
name: "Salary",
table: "Posts",
type: "double precision",
nullable: false,
defaultValue: 0.0);
}
}
}

View File

@@ -0,0 +1,367 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using SladkieBulkiDatabase;
#nullable disable
namespace SladkieBulkiDatabase.Migrations
{
[DbContext(typeof(SladkieBulkiDbContext))]
[Migration("20250520222914_AddDateOfDeleteInWorker")]
partial class AddDateOfDeleteInWorker
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.4")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("SladkieBulkiDatabase.Models.Ingredient", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<double>("InitPrice")
.HasColumnType("double precision");
b.Property<string>("NameIngredients")
.IsRequired()
.HasColumnType("text");
b.Property<string>("SizeInit")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("NameIngredients")
.IsUnique();
b.ToTable("Ingredients");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.IngredientHistory", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("IngredienId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("OldPrice")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("IngredienId");
b.ToTable("IngredientHistories");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Post", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Configuration")
.IsRequired()
.HasColumnType("jsonb");
b.Property<bool>("IsActual")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PostName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("PostType")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("PostId", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.HasIndex("PostName", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.ToTable("Posts");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Product", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int>("ProductType")
.HasColumnType("integer");
b.Property<int>("UnitPrice")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("Name", "IsDeleted")
.IsUnique()
.HasFilter("\"IsDeleted\" = FALSE");
b.ToTable("Products");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.ProductHistory", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("OldPrice")
.HasColumnType("double precision");
b.Property<string>("ProductId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ProductId");
b.ToTable("ProductHistories");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.ProductIngredient", b =>
{
b.Property<string>("ProductId")
.HasColumnType("text");
b.Property<string>("IngredientId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.HasKey("ProductId", "IngredientId");
b.HasIndex("IngredientId");
b.ToTable("ProductIngredients");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Production", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<string>("ProductId")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("ProductionDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ProductId");
b.HasIndex("WorkerId");
b.ToTable("Productions");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Salary", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("SalaryDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("WorkerSalary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("WorkerId");
b.ToTable("Salaries");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Worker", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("BirthDate")
.HasColumnType("timestamp without time zone");
b.Property<DateTime?>("DateOfDelete")
.HasColumnType("timestamp without time zone");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("EmploymentDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Workers");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.IngredientHistory", b =>
{
b.HasOne("SladkieBulkiDatabase.Models.Ingredient", "Ingredient")
.WithMany("IngredientHistory")
.HasForeignKey("IngredienId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Ingredient");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.ProductHistory", b =>
{
b.HasOne("SladkieBulkiDatabase.Models.Product", "Product")
.WithMany("ProductHistories")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.ProductIngredient", b =>
{
b.HasOne("SladkieBulkiDatabase.Models.Ingredient", "Ingredient")
.WithMany("ProductIngredients")
.HasForeignKey("IngredientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SladkieBulkiDatabase.Models.Product", "Product")
.WithMany("ProductIngredients")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Ingredient");
b.Navigation("Product");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Production", b =>
{
b.HasOne("SladkieBulkiDatabase.Models.Product", "Product")
.WithMany("Productions")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SladkieBulkiDatabase.Models.Worker", "Worker")
.WithMany("Productions")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
b.Navigation("Worker");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Salary", b =>
{
b.HasOne("SladkieBulkiDatabase.Models.Worker", "Worker")
.WithMany("Salaries")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Worker");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Ingredient", b =>
{
b.Navigation("IngredientHistory");
b.Navigation("ProductIngredients");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Product", b =>
{
b.Navigation("ProductHistories");
b.Navigation("ProductIngredients");
b.Navigation("Productions");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Worker", b =>
{
b.Navigation("Productions");
b.Navigation("Salaries");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,29 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SladkieBulkiDatabase.Migrations
{
/// <inheritdoc />
public partial class AddDateOfDeleteInWorker : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTime>(
name: "DateOfDelete",
table: "Workers",
type: "timestamp without time zone",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "DateOfDelete",
table: "Workers");
}
}
}

View File

@@ -0,0 +1,364 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using SladkieBulkiDatabase;
#nullable disable
namespace SladkieBulkiDatabase.Migrations
{
[DbContext(typeof(SladkieBulkiDbContext))]
partial class SladkieBulkiDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.4")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("SladkieBulkiDatabase.Models.Ingredient", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<double>("InitPrice")
.HasColumnType("double precision");
b.Property<string>("NameIngredients")
.IsRequired()
.HasColumnType("text");
b.Property<string>("SizeInit")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("NameIngredients")
.IsUnique();
b.ToTable("Ingredients");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.IngredientHistory", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("IngredienId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("OldPrice")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("IngredienId");
b.ToTable("IngredientHistories");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Post", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Configuration")
.IsRequired()
.HasColumnType("jsonb");
b.Property<bool>("IsActual")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PostName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("PostType")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("PostId", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.HasIndex("PostName", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.ToTable("Posts");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Product", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int>("ProductType")
.HasColumnType("integer");
b.Property<int>("UnitPrice")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("Name", "IsDeleted")
.IsUnique()
.HasFilter("\"IsDeleted\" = FALSE");
b.ToTable("Products");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.ProductHistory", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("OldPrice")
.HasColumnType("double precision");
b.Property<string>("ProductId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ProductId");
b.ToTable("ProductHistories");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.ProductIngredient", b =>
{
b.Property<string>("ProductId")
.HasColumnType("text");
b.Property<string>("IngredientId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.HasKey("ProductId", "IngredientId");
b.HasIndex("IngredientId");
b.ToTable("ProductIngredients");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Production", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<string>("ProductId")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("ProductionDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ProductId");
b.HasIndex("WorkerId");
b.ToTable("Productions");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Salary", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("SalaryDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("WorkerSalary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("WorkerId");
b.ToTable("Salaries");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Worker", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("BirthDate")
.HasColumnType("timestamp without time zone");
b.Property<DateTime?>("DateOfDelete")
.HasColumnType("timestamp without time zone");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("EmploymentDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Workers");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.IngredientHistory", b =>
{
b.HasOne("SladkieBulkiDatabase.Models.Ingredient", "Ingredient")
.WithMany("IngredientHistory")
.HasForeignKey("IngredienId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Ingredient");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.ProductHistory", b =>
{
b.HasOne("SladkieBulkiDatabase.Models.Product", "Product")
.WithMany("ProductHistories")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.ProductIngredient", b =>
{
b.HasOne("SladkieBulkiDatabase.Models.Ingredient", "Ingredient")
.WithMany("ProductIngredients")
.HasForeignKey("IngredientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SladkieBulkiDatabase.Models.Product", "Product")
.WithMany("ProductIngredients")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Ingredient");
b.Navigation("Product");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Production", b =>
{
b.HasOne("SladkieBulkiDatabase.Models.Product", "Product")
.WithMany("Productions")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SladkieBulkiDatabase.Models.Worker", "Worker")
.WithMany("Productions")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
b.Navigation("Worker");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Salary", b =>
{
b.HasOne("SladkieBulkiDatabase.Models.Worker", "Worker")
.WithMany("Salaries")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Worker");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Ingredient", b =>
{
b.Navigation("IngredientHistory");
b.Navigation("ProductIngredients");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Product", b =>
{
b.Navigation("ProductHistories");
b.Navigation("ProductIngredients");
b.Navigation("Productions");
});
modelBuilder.Entity("SladkieBulkiDatabase.Models.Worker", b =>
{
b.Navigation("Productions");
b.Navigation("Salaries");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiDatabase.Models;
internal class Ingredient
{
public required string Id { get; set; } = Guid.NewGuid().ToString();
public required string NameIngredients { get; set; }
public required string SizeInit { get; set; }
public double InitPrice { get; set; }
[ForeignKey("IngredientId")]
public List<ProductIngredient>? ProductIngredients { get; set; }
[ForeignKey("IngredienId")]
public List<IngredientHistory>? IngredientHistory { get; set; }
}

View File

@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiDatabase.Models;
internal class IngredientHistory
{
public string Id { get; set; }
public required string IngredienId { get; set; }
public double OldPrice { get; set; }
public DateTime ChangeDate { get; set; }
public Ingredient Ingredient { get; set; }
}

View File

@@ -0,0 +1,20 @@
using SladkieBulkiContrakts.Enums;
using SladkieBulkiContrakts.Infrastructure.PostConfigurations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiDatabase.Models;
internal class Post
{
public required string Id { get; set; } = Guid.NewGuid().ToString();
public required string PostId { get; set; }
public required string PostName { get; set; }
public PostType PostType { get; set; }
public required PostConfiguration Configuration { get; set; }
public bool IsActual { get; set; }
public DateTime ChangeDate { get; set; }
}

View File

@@ -0,0 +1,30 @@
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace SladkieBulkiDatabase.Models;
internal class Product
{
public required string Id { get; set; }
public required string Name { get; set; }
public required string Description { get; set; }
public ProductType ProductType { get; set; }
public int UnitPrice { get; set; }
public bool IsDeleted { get; set; }
[ForeignKey("ProductId")]
public List<ProductIngredient>? ProductIngredients { get; set; }
[ForeignKey("ProductId")]
public List<Production>? Productions { get; set; }
[ForeignKey("ProductId")]
public List<ProductHistory>? ProductHistories { get; set; }
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiDatabase.Models;
internal class ProductHistory
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string ProductId { get; set; }
public double OldPrice { get; set; }
public DateTime ChangeDate { get; set; } = DateTime.UtcNow;
public Product? Product { get; set; }
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiDatabase.Models;
internal class ProductIngredient
{
public required string ProductId { get; set; }
public required string IngredientId { get; set; }
public int Count { get; set; }
public Ingredient? Ingredient { get; set; }
public Product? Product { get; set; }
}

View File

@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiDatabase.Models;
internal class Production
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public DateTime ProductionDate { get; set; }
public int Count { get; set; }
public double Sum { get; set; }
public required string WorkerId { get; set; }
public required string ProductId { get; set; }
public Worker? Worker { get; set; }
public Product? Product { get; set; }
}

View File

@@ -0,0 +1,18 @@
using AutoMapper;
using SladkieBulkiContrakts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiDatabase.Models;
internal class Salary
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string WorkerId { get; set; }
public DateTime SalaryDate { get; set; }
public double WorkerSalary { get; set; }
public Worker? Worker { get; set; }
}

View File

@@ -0,0 +1,38 @@
using AutoMapper;
using SladkieBulkiContrakts.DataModels;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiDatabase.Models;
[AutoMap(typeof(WorkerDataModel), ReverseMap = true)]
internal class Worker
{
public required string Id { get; set; }
public required string FIO { get; set; }
public required string PostId { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
public bool IsDeleted { get; set; }
public required string Email { get; set; }
public DateTime? DateOfDelete { get; set; }
[NotMapped]
public Post? Post { get; set; }
[ForeignKey("WorkerId")]
public List<Salary>? Salaries { get; set; }
[ForeignKey("WorkerId")]
public List<Production>? Productions { get; set; }
public Worker AddPost(Post? post)
{
Post = post;
return this;
}
}

View File

@@ -0,0 +1,16 @@
using Microsoft.EntityFrameworkCore.Design;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiDatabase;
internal class SampleContextFactory : IDesignTimeDbContextFactory<SladkieBulkiDbContext>
{
public SladkieBulkiDbContext CreateDbContext(string[] args)
{
return new SladkieBulkiDbContext(new DefaultConfigurationDatabase());
}
}

View File

@@ -0,0 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SladkieBulkiContrakts\SladkieBulkiContrakts.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="SladkieBulkiWedApi" />
<InternalsVisibleTo Include="SladkieBulkiTests" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,77 @@
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SladkieBulkiContrakts.Infrastructure;
using SladkieBulkiContrakts.Infrastructure.PostConfigurations;
using SladkieBulkiDatabase.Models;
using System;
namespace SladkieBulkiDatabase;
internal class SladkieBulkiDbContext: DbContext
{
private readonly IConfigurationDatabase? _configurationDatabase;
public SladkieBulkiDbContext(IConfigurationDatabase configurationDatabase)
{
_configurationDatabase = configurationDatabase;
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql(_configurationDatabase?.ConnectionString, o => o.SetPostgresVersion(12, 2));
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Ingredient>().HasIndex(x => x.NameIngredients).IsUnique();
modelBuilder.Entity<Post>()
.HasIndex(e => new { e.PostName, e.IsActual })
.IsUnique()
.HasFilter($"\"{nameof(Post.IsActual)}\" = TRUE");
modelBuilder.Entity<Post>()
.HasIndex(e => new { e.PostId, e.IsActual })
.IsUnique()
.HasFilter($"\"{nameof(Post.IsActual)}\" = TRUE");
modelBuilder.Entity<Product>()
.HasIndex(x => new { x.Name, x.IsDeleted })
.IsUnique()
.HasFilter($"\"{nameof(Product.IsDeleted)}\" = FALSE");
modelBuilder.Entity<ProductIngredient>().HasKey(x => new { x.ProductId, x.IngredientId });
modelBuilder.Entity<Post>()
.Property(x => x.Configuration)
.HasColumnType("jsonb")
.HasConversion(
x => SerializePostConfiguration(x),
x => DeserialzePostConfiguration(x)
);
}
public DbSet<Ingredient> Ingredients { get; set; }
public DbSet<IngredientHistory> IngredientHistories { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<ProductHistory> ProductHistories { get; set; }
public DbSet<Salary> Salaries { get; set; }
public DbSet<Production> Productions { get; set; }
public DbSet<ProductIngredient> ProductIngredients { get; set; }
public DbSet<Worker> Workers { get; set; }
private static string SerializePostConfiguration(PostConfiguration postConfiguration) => JsonConvert.SerializeObject(postConfiguration);
private static PostConfiguration DeserialzePostConfiguration(string jsonString) => JToken.Parse(jsonString).Value<string>("Type") switch
{
nameof(ManufacturerPostConfiguration) => JsonConvert.DeserializeObject<ManufacturerPostConfiguration>(jsonString)!,
nameof(PackerPostConfiguration) => JsonConvert.DeserializeObject<PackerPostConfiguration>(jsonString)!,
_ => JsonConvert.DeserializeObject<PostConfiguration>(jsonString)!,
};
}

View File

@@ -0,0 +1,384 @@
using Moq;
using SladkieBulkiBusinessLogic.Implementations;
using SladkieBulkiContrakts.StoragesContarcts;
using SladkieBulkiContrakts.DataModels;
using Microsoft.Extensions.Logging;
using SladkieBulkiContrakts.Exceptions;
namespace SladkieBulkiTests.BusinessLogicsContractsTests;
[TestFixture]
internal class IngredientBusinessLogicContractTests
{
private IngredientBusinessLogicContract _ingredientBusinessLogicContract;
private Mock<IIngredientStorageContract> _ingredientStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_ingredientStorageContract = new Mock<IIngredientStorageContract>();
_ingredientBusinessLogicContract = new IngredientBusinessLogicContract(_ingredientStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_ingredientStorageContract.Reset();
}
[Test]
public void GetAllIngredients_ReturnListOfRecords_Test()
{
// Arrange
var listOriginal = new List<IngredientDataModel>()
{
new IngredientDataModel(Guid.NewGuid().ToString(), "Sugar", "kg", 100),
new IngredientDataModel(Guid.NewGuid().ToString(), "Flour", "kg", 50),
new IngredientDataModel(Guid.NewGuid().ToString(), "Butter", "kg", 30),
};
_ingredientStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
// Act
var list = _ingredientBusinessLogicContract.GetAllIngredients();
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
}
[Test]
public void GetAllIngredients_ReturnEmptyList_Test()
{
//Arrange
_ingredientStorageContract.Setup(x => x.GetList()).Returns([]);
//Act
var list = _ingredientBusinessLogicContract.GetAllIngredients();
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_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()));
//Act&Assert
Assert.That(() => _ingredientBusinessLogicContract.GetAllIngredients(), Throws.TypeOf<StorageException>());
_ingredientStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetIngredientsBySizeUnit_ReturnListOfIngredients_Test()
{
// Arrange
var sizeUnit = "kg";
var ingredientsList = new List<IngredientDataModel>
{
new IngredientDataModel(Guid.NewGuid().ToString(), "Sugar", "kg", 10),
new IngredientDataModel(Guid.NewGuid().ToString(), "Flour", "kg", 15),
};
_ingredientStorageContract.Setup(x => x.GetElementBySizeUnit(sizeUnit)).Returns(ingredientsList);
// Act
var result = _ingredientBusinessLogicContract.GetIngredientsBySizeUnit(sizeUnit);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result.Count, Is.EqualTo(2));
Assert.That(result[0].SizeInit, Is.EqualTo(sizeUnit));
Assert.That(result[1].SizeInit, Is.EqualTo(sizeUnit));
_ingredientStorageContract.Verify(x => x.GetElementBySizeUnit(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetIngredientById_GetById_ReturnRecord_Test()
{
// Arrange
var id = Guid.NewGuid().ToString();
var record = new IngredientDataModel(id, "Sugar", "kg", 100);
_ingredientStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
// Act
var element = _ingredientBusinessLogicContract.GetIngredientById(id);
// Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_ingredientStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetIngredientByName_GetByName_ReturnRecord_Test()
{
// Arrange
var name = "Sugar";
var record = new IngredientDataModel(Guid.NewGuid().ToString(), name, "kg", 100);
_ingredientStorageContract.Setup(x =>
x.GetElementByName(name)).Returns(record);
// Act
var element = _ingredientBusinessLogicContract.GetIngredientByName(name);
// Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.NameIngredients, Is.EqualTo(name));
_ingredientStorageContract.Verify(x =>
x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetIngredientByData_EmptyData_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _ingredientBusinessLogicContract.GetIngredientById(null),
Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _ingredientBusinessLogicContract.GetIngredientByName(string.Empty),
Throws.TypeOf<ArgumentNullException>());
_ingredientStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Never);
_ingredientStorageContract.Verify(x =>
x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetIngredientById_GetById_NotFoundRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() =>
_ingredientBusinessLogicContract.GetIngredientById(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_ingredientStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Once);
_ingredientStorageContract.Verify(x =>
x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetIngredientByName_GetByName_NotFoundRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _ingredientBusinessLogicContract.GetIngredientByName("Sugar"),
Throws.TypeOf<ElementNotFoundException>());
_ingredientStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Never);
_ingredientStorageContract.Verify(x =>
x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetIngredientByData_StorageThrowError_ThrowException_Test()
{
// Arrange
_ingredientStorageContract.Setup(x =>
x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_ingredientStorageContract.Setup(x =>
x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() =>
_ingredientBusinessLogicContract.GetIngredientById(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
Assert.That(() => _ingredientBusinessLogicContract.GetIngredientByName("Sugar"),
Throws.TypeOf<StorageException>());
_ingredientStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Once);
_ingredientStorageContract.Verify(x =>
x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertIngredient_CorrectRecord_Test()
{
// Arrange
var flag = false;
var record = new IngredientDataModel(Guid.NewGuid().ToString(), "Sugar", "kg", 120.5);
_ingredientStorageContract.Setup(x =>
x.AddElement(It.IsAny<IngredientDataModel>()))
.Callback((IngredientDataModel x) =>
{
flag = x.Id == record.Id &&
x.NameIngredients == record.NameIngredients &&
x.SizeInit == record.SizeInit &&
x.InitPrice == record.InitPrice;
});
// Act
_ingredientBusinessLogicContract.InsertIngredient(record);
// Assert
_ingredientStorageContract.Verify(x =>
x.AddElement(It.IsAny<IngredientDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertIngredient_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_ingredientStorageContract.Setup(x =>
x.AddElement(It.IsAny<IngredientDataModel>()))
.Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() =>
_ingredientBusinessLogicContract.InsertIngredient(
new(Guid.NewGuid().ToString(), "Sugar", "kg", 120.5)),
Throws.TypeOf<ElementExistsException>());
_ingredientStorageContract.Verify(x =>
x.AddElement(It.IsAny<IngredientDataModel>()), Times.Once);
}
[Test]
public void InsertIngredient_NullRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _ingredientBusinessLogicContract.InsertIngredient(null),
Throws.TypeOf<ArgumentNullException>());
_ingredientStorageContract.Verify(x =>
x.AddElement(It.IsAny<IngredientDataModel>()), Times.Never);
}
[Test]
public void InsertIngredient_InvalidRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _ingredientBusinessLogicContract.InsertIngredient(
new("id", "", "", -10)),
Throws.TypeOf<ValidationException>());
_ingredientStorageContract.Verify(x =>
x.AddElement(It.IsAny<IngredientDataModel>()), Times.Never);
}
[Test]
public void InsertIngredient_StorageThrowError_ThrowException_Test()
{
// Arrange
_ingredientStorageContract.Setup(x =>
x.AddElement(It.IsAny<IngredientDataModel>()))
.Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() =>
_ingredientBusinessLogicContract.InsertIngredient(
new(Guid.NewGuid().ToString(), "Sugar", "kg", 120.5)),
Throws.TypeOf<StorageException>());
_ingredientStorageContract.Verify(x =>
x.AddElement(It.IsAny<IngredientDataModel>()), Times.Once);
}
[Test]
public void UpdateIngredient_CorrectRecord_Test()
{
// Arrange
var flag = false;
var record = new IngredientDataModel(Guid.NewGuid().ToString(), "Sugar", "kg", 120.5);
_ingredientStorageContract.Setup(x =>
x.UpdElement(It.IsAny<IngredientDataModel>()))
.Callback((IngredientDataModel x) =>
{
flag = x.Id == record.Id &&
x.NameIngredients == record.NameIngredients &&
x.SizeInit == record.SizeInit &&
x.InitPrice == record.InitPrice;
});
// Act
_ingredientBusinessLogicContract.UpdateIngredient(record);
// Assert
_ingredientStorageContract.Verify(x =>
x.UpdElement(It.IsAny<IngredientDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdateIngredient_RecordWithIncorrectData_ThrowException_Test()
{
// Arrange
_ingredientStorageContract.Setup(x =>
x.UpdElement(It.IsAny<IngredientDataModel>()))
.Throws(new ElementNotFoundException(""));
// Act & Assert
Assert.That(() =>
_ingredientBusinessLogicContract.UpdateIngredient(
new(Guid.NewGuid().ToString(), "Sugar", "kg", 120.5)),
Throws.TypeOf<ElementNotFoundException>());
_ingredientStorageContract.Verify(x =>
x.UpdElement(It.IsAny<IngredientDataModel>()), Times.Once);
}
[Test]
public void UpdateIngredient_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_ingredientStorageContract.Setup(x =>
x.UpdElement(It.IsAny<IngredientDataModel>()))
.Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() =>
_ingredientBusinessLogicContract.UpdateIngredient(
new(Guid.NewGuid().ToString(), "Sugar", "kg", 120.5)),
Throws.TypeOf<ElementExistsException>());
_ingredientStorageContract.Verify(x =>
x.UpdElement(It.IsAny<IngredientDataModel>()), Times.Once);
}
[Test]
public void UpdateIngredient_NullRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _ingredientBusinessLogicContract.UpdateIngredient(null),
Throws.TypeOf<ArgumentNullException>());
_ingredientStorageContract.Verify(x =>
x.UpdElement(It.IsAny<IngredientDataModel>()), Times.Never);
}
[Test]
public void UpdateIngredient_InvalidRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _ingredientBusinessLogicContract.UpdateIngredient(
new("id", "", "", -10)),
Throws.TypeOf<ValidationException>());
_ingredientStorageContract.Verify(x =>
x.UpdElement(It.IsAny<IngredientDataModel>()), Times.Never);
}
[Test]
public void UpdateIngredient_StorageThrowError_ThrowException_Test()
{
// Arrange
_ingredientStorageContract.Setup(x =>
x.UpdElement(It.IsAny<IngredientDataModel>()))
.Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() =>
_ingredientBusinessLogicContract.UpdateIngredient(
new(Guid.NewGuid().ToString(), "Sugar", "kg", 120.5)),
Throws.TypeOf<StorageException>());
_ingredientStorageContract.Verify(x =>
x.UpdElement(It.IsAny<IngredientDataModel>()), Times.Once);
}
}

View File

@@ -0,0 +1,445 @@
using SladkieBulkiBusinessLogic.Implementations;
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Enums;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.StoragesContarcts;
using Microsoft.Extensions.Logging;
using Moq;
using SladkieBulkiContrakts.Infrastructure.PostConfigurations;
namespace SladkieBulkiTests.BusinessLogicsContractsTests;
[TestFixture]
internal class PostBusinessLogicContractTests
{
private PostBusinessLogicContract _postBusinessLogicContract;
private Mock<IPostStorageContract> _postStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_postStorageContract = new Mock<IPostStorageContract>();
_postBusinessLogicContract = new PostBusinessLogicContract(_postStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_postStorageContract.Reset();
}
[Test]
public void GetAllPosts_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<PostDataModel>()
{
new(Guid.NewGuid().ToString(),"name 1", PostType.Manufacturer, new PostConfiguration() { Rate = 10 }),
new(Guid.NewGuid().ToString(), "name 2", PostType.Manufacturer, new PostConfiguration() { Rate = 10 }),
new(Guid.NewGuid().ToString(), "name 3", PostType.Manufacturer, new PostConfiguration() { Rate = 10 }),
};
_postStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
//Act
var list = _postBusinessLogicContract.GetAllPosts();
//Assert
Assert.Multiple(() =>
{
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_postStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllPosts_ReturnEmptyList_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetList()).Returns([]);
//Act
var list = _postBusinessLogicContract.GetAllPosts();
//Assert
Assert.Multiple(() =>
{
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
});
}
[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()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllPosts(), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllDataOfPost_ReturnListOfRecords_Test()
{
//Arrange
var postId = Guid.NewGuid().ToString();
var listOriginal = new List<PostDataModel>()
{
new(postId, "name 1", PostType.Manufacturer, new PostConfiguration() { Rate = 10 }),
new(postId, "name 2", PostType.Manufacturer, new PostConfiguration() { Rate = 10 })
};
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _postBusinessLogicContract.GetAllDataOfPost(postId);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
_postStorageContract.Verify(x => x.GetPostWithHistory(postId), Times.Once);
}
[Test]
public void GetAllDataOfPost_ReturnEmptyList_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns([]);
//Act
var list = _postBusinessLogicContract.GetAllDataOfPost(Guid.NewGuid().ToString());
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllDataOfPost_PostIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(string.Empty), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllDataOfPost_PostIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost("id"), Throws.TypeOf<ValidationException>());
_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()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new PostDataModel(id, "name", PostType.Manufacturer, new PostConfiguration() { Rate = 10 });
_postStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_GetByName_ReturnRecord_Test()
{
//Arrange
var postName = "name";
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.Manufacturer, new PostConfiguration() { Rate = 10 });
_postStorageContract.Setup(x => x.GetElementByName(postName)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(postName);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.PostName, Is.EqualTo(postName));
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _postBusinessLogicContract.GetPostByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetPostByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetPostByData_GetByName_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData("name"), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _postBusinessLogicContract.GetPostByData("name"), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertPost_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Preform, new PostConfiguration() { Rate = 10 });
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>()))
.Callback((PostDataModel x) =>
{
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.ConfigurationModel.Rate == record.ConfigurationModel.Rate;
});
//Act
_postBusinessLogicContract.InsertPost(record);
//Assert
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertPost_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_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);
}
[Test]
public void InsertPost_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(null), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void InsertPost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Preform, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void InsertPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_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);
}
[Test]
public void UpdatePost_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Preform, new PostConfiguration() { Rate = 10 });
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>()))
.Callback((PostDataModel x) =>
{
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.ConfigurationModel.Rate == record.ConfigurationModel.Rate;
});
//Act
_postBusinessLogicContract.UpdatePost(record);
//Assert
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdatePost_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_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);
}
[Test]
public void UpdatePost_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_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);
}
[Test]
public void UpdatePost_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(null), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void UpdatePost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Preform, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void UpdatePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_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);
}
[Test]
public void DeletePost_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_postStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_postBusinessLogicContract.DeletePost(id);
//Assert
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void DeletePost_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_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);
}
[Test]
public void DeletePost_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _postBusinessLogicContract.DeletePost(string.Empty), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeletePost_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost("id"), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeletePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_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);
}
[Test]
public void RestorePost_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_postStorageContract.Setup(x => x.ResElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_postBusinessLogicContract.RestorePost(id);
//Assert
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void RestorePost_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_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);
}
[Test]
public void RestorePost_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _postBusinessLogicContract.RestorePost(string.Empty), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void RestorePost_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost("id"), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void RestorePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_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

@@ -0,0 +1,479 @@
using Microsoft.Extensions.Logging;
using Moq;
using SladkieBulkiBusinessLogic.Implementations;
using SladkieBulkiContrakts.DataModels;
using SladkieBulkiContrakts.Enums;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.StoragesContarcts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiTests.BusinessLogicsContractsTests;
[TestFixture]
internal class ProductBusinessLogicContractTests
{
private ProductBusinessLogicContract _productBusinessLogicContract;
private Mock<IProductStorageContract> _productStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_productStorageContract = new Mock<IProductStorageContract>();
_productBusinessLogicContract = new ProductBusinessLogicContract(_productStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_productStorageContract.Reset();
}
[Test]
public void GetAllProducts_ReturnListOfRecords_Test()
{
// Arrange
var listOriginal = new List<ProductDataModel>
{
new(Guid.NewGuid().ToString(), "name 1", "description 1", ProductType.Workpiece, [new ProductIngredientDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)], 10, true),
new(Guid.NewGuid().ToString(), "name 2", "description 2", ProductType.Workpiece, [new ProductIngredientDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)], 10, false),
new(Guid.NewGuid().ToString(), "name 3", "description 3", ProductType.Workpiece, [new ProductIngredientDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)], 10, true)
};
_productStorageContract.Setup(x => x.GetList(true)).Returns(listOriginal);
_productStorageContract.Setup(x => x.GetList(false)).Returns(listOriginal);
// Act
var listOnlyActive = _productBusinessLogicContract.GetAllProducts(true);
var list = _productBusinessLogicContract.GetAllProducts(false);
// Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_productStorageContract.Verify(x => x.GetList(true), Times.Once);
_productStorageContract.Verify(x => x.GetList(false), Times.Once);
}
[Test]
public void GetAllProducts_ReturnEmptyList_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Returns([]);
//Act
var listOnlyActive = _productBusinessLogicContract.GetAllProducts(true);
var list = _productBusinessLogicContract.GetAllProducts(false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(list, Has.Count.EqualTo(0));
});
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Exactly(2));
}
[Test]
public void GetAllProducts_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_productBusinessLogicContract.GetAllProducts(It.IsAny<bool>()),
Throws.TypeOf<NullListException>());
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Once);
}
[Test]
public void GetAllProducts_StorageThrowError_ThrowException_Test()
{
// Arrange
_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>());
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Once);
}
[Test]
public void GetProductHistoryByProduct_ReturnListOfRecords_Test()
{
//Arrange
var productId = Guid.NewGuid().ToString();
var listOriginal = new List<ProductHistoryDataModel>()
{
new(Guid.NewGuid().ToString(), 10),
new(Guid.NewGuid().ToString(), 15),
new(Guid.NewGuid().ToString(), 10),
};
_productStorageContract.Setup(x => x.GetHistoryByProductId(It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _productBusinessLogicContract.GetProductHistoryByProduct(productId);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_productStorageContract.Verify(x => x.GetHistoryByProductId(productId), Times.Once);
}
[Test]
public void GetProductHistoryByProduct_ReturnEmptyList_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetHistoryByProductId(It.IsAny<string>())).Returns([]);
//Act
var list = _productBusinessLogicContract.GetProductHistoryByProduct(Guid.NewGuid().ToString(
));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductHistoryByProduct_ProductIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(null),
Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(string.Empty),
Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetProductHistoryByProduct_ProductIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct("productId"),
Throws.TypeOf<ValidationException>());
_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()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new ProductDataModel(id, "name", "desk", ProductType.Workpiece, [], 10, false);
_productStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _productBusinessLogicContract.GetProductByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_productStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_GetByName_ReturnRecord_Test()
{
//Arrange
var name = "name";
var record = new ProductDataModel(Guid.NewGuid().ToString(), name, Guid.NewGuid().ToString(), ProductType.Workpiece, [new ProductIngredientDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)], 10, false);
_productStorageContract.Setup(x => x.GetElementByName(name)).Returns(record);
//Act
var element = _productBusinessLogicContract.GetProductByData(name);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Name, Is.EqualTo(name));
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _productBusinessLogicContract.GetProductByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetProductByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_productBusinessLogicContract.GetProductByData(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_GetByName_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_productBusinessLogicContract.GetProductByData("name"),
Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x =>
x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x =>
x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException()));
_productStorageContract.Setup(x =>
x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException()));
//Act&Assert
Assert.That(() =>
_productBusinessLogicContract.GetProductByData(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
Assert.That(() =>
_productBusinessLogicContract.GetProductByData("name"),
Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Once);
_productStorageContract.Verify(x =>
x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertProduct_CorrectRecord_Test()
{
// Arrange
var flag = false;
var record = new ProductDataModel(Guid.NewGuid().ToString(), "name", "description", ProductType.Workpiece, [new ProductIngredientDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)], 10, false);
_productStorageContract.Setup(x => x.AddElement(It.IsAny<ProductDataModel>()))
.Callback((ProductDataModel x) =>
{
flag = x.Id == record.Id && x.Name == record.Name && x.ProductType == record.ProductType && x.UnitPrice == record.UnitPrice && x.IsDeleted == record.IsDeleted;
});
// Act
_productBusinessLogicContract.InsertProduct(record);
// Assert
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertProduct_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_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)),
Throws.TypeOf<ElementExistsException>());
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Once);
}
[Test]
public void InsertProduct_NullRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _productBusinessLogicContract.InsertProduct(null), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Never);
}
[Test]
public void InsertProduct_InvalidRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _productBusinessLogicContract.InsertProduct(new ProductDataModel("id", "name", Guid.NewGuid().ToString(), ProductType.Workpiece, [new ProductIngredientDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)], 10, false)),
Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Never);
}
[Test]
public void InsertProduct_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.AddElement(It.IsAny<ProductDataModel>())).Throws(new StorageException(new
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);
}
[Test]
public void UpdateProduct_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new ProductDataModel(Guid.NewGuid().ToString(), "name", Guid.NewGuid().ToString(), ProductType.Workpiece, [new ProductIngredientDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)], 10, false);
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<ProductDataModel>())).Callback((ProductDataModel x) =>
{
flag = x.Id == record.Id && x.Name == record.Name && x.ProductType == record.ProductType && x.UnitPrice == record.UnitPrice && x.IsDeleted == record.IsDeleted;
});
//Act
_productBusinessLogicContract.UpdateProduct(record);
//Assert
_productStorageContract.Verify(x =>
x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdateProduct_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x =>
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)),
Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x =>
x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
}
[Test]
public void UpdateProduct_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x =>
x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new
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)),
Throws.TypeOf<ElementExistsException>());
_productStorageContract.Verify(x =>
x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
}
[Test]
public void UpdateProduct_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(null),
Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x =>
x.UpdElement(It.IsAny<ProductDataModel>()), Times.Never);
}
[Test]
public void UpdateProduct_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(new ProductDataModel("id", "name", Guid.NewGuid().ToString(), ProductType.Workpiece, [new ProductIngredientDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)], 10, false)), Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x =>
x.UpdElement(It.IsAny<ProductDataModel>()), Times.Never);
}
[Test]
public void UpdateProduct_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x =>
x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new StorageException(new
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)),
Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x =>
x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
}
[Test]
public void DeleteProduct_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_productStorageContract.Setup(x => x.DelElement(It.Is((string x) => x
== id))).Callback(() => { flag = true; });
//Act
_productBusinessLogicContract.DeleteProduct(id);
//Assert
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()),
Times.Once);
Assert.That(flag);
}
[Test]
public void DeleteProduct_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_productStorageContract.Setup(x =>
x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() =>
_productBusinessLogicContract.DeleteProduct(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()),
Times.Once);
}
[Test]
public void DeleteProduct_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.DeleteProduct(null),
Throws.TypeOf<ArgumentNullException>());
Assert.That(() =>
_productBusinessLogicContract.DeleteProduct(string.Empty),
Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteProduct_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.DeleteProduct("id"),
Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()),
Times.Never);
}
[Test]
public void DeleteProduct_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x =>
x.DelElement(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException()));
//Act&Assert
Assert.That(() =>
_productBusinessLogicContract.DeleteProduct(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()),
Times.Once);
}
}

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