6 Commits

154 changed files with 12184 additions and 901 deletions

View File

@@ -0,0 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>preview</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="EntityFramework" Version="6.5.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.4" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.4" />
<PackageReference Include="Npgsql" Version="9.0.3" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AndDietCokeProject\AndDietCokeContracts.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="AndDietCokeTests" />
<InternalsVisibleTo Include="AndDietCokeWebApi" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,76 @@
using AndDietCokeContracts.BisnessLogicsContracts;
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Extensions;
using AndDietCokeContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace AndDietCokeBuisnessLogic.Implementations;
internal class BuyerBusinessLogicContract(IBuyerStorageContract buyerStorageContract, ILogger logger) : IBuyerBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IBuyerStorageContract _buyerStorageContract = buyerStorageContract;
public List<BuyerDataModel> GetAllBuyers()
{
_logger.LogInformation("GetAllBuyers");
return _buyerStorageContract.GetList() ?? throw new NullListException();
}
public BuyerDataModel GetBuyerByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _buyerStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
if (Regex.IsMatch(data, @"^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7,10}$"))
{
return _buyerStorageContract.GetElementByPhoneNumber(data) ?? throw new ElementNotFoundException(data);
}
return _buyerStorageContract.GetElementByFIO(data) ?? throw new ElementNotFoundException(data);
}
public void InsertBuyer(BuyerDataModel buyerDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(buyerDataModel));
ArgumentNullException.ThrowIfNull(buyerDataModel);
buyerDataModel.Validate();
_buyerStorageContract.AddElement(buyerDataModel);
}
public void UpdateBuyer(BuyerDataModel buyerDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(buyerDataModel));
ArgumentNullException.ThrowIfNull(buyerDataModel);
buyerDataModel.Validate();
_buyerStorageContract.UpdElement(buyerDataModel);
}
public void DeleteBuyer(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");
}
_buyerStorageContract.DelElement(id);
}
}

View File

@@ -0,0 +1,80 @@
using AndDietCokeContracts.BisnessLogicsContracts;
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Enums;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Extensions;
using AndDietCokeContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace AndDietCokeBuisnessLogic.Implementations;
internal class DishBusinessLogicContract(IDishStorageContract dishStorageContract, ILogger logger) : IDishBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IDishStorageContract _dishStorageContract = dishStorageContract;
public List<DishDataModel> GetAllDishes(bool onlyActive)
{
_logger.LogInformation("GetAllDishes params: {onlyActive}", onlyActive);
return _dishStorageContract.GetList(onlyActive) ?? throw new NullListException();
}
public List<DishHistoryDataModel> GetDishHistoryByDish(string dishId)
{
_logger.LogInformation("GetDishHistoryByDish for {dishId}", dishId);
if (dishId.IsEmpty())
{
throw new ArgumentNullException(nameof(dishId));
}
if (!dishId.IsGuid())
{
throw new ValidationException("The value in the field dishId is not a unique identifier.");
}
return _dishStorageContract.GetHistoryByDishId(dishId) ?? throw new NullListException();
}
public DishDataModel GetDishByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _dishStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
return _dishStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data);
}
public void InsertDish(DishDataModel dishDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(dishDataModel));
ArgumentNullException.ThrowIfNull(dishDataModel);
dishDataModel.Validate();
_dishStorageContract.AddElement(dishDataModel);
}
public void UpdateDish(DishDataModel dishDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(dishDataModel));
ArgumentNullException.ThrowIfNull(dishDataModel);
dishDataModel.Validate();
_dishStorageContract.UpdElement(dishDataModel);
}
public void DeleteDish(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");
}
_dishStorageContract.DelElement(id);
}
}

View File

@@ -0,0 +1,99 @@
using AndDietCokeContracts.BisnessLogicsContracts;
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Enums;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Extensions;
using AndDietCokeContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace AndDietCokeBuisnessLogic.Implementations;
public class PostBusinessLogicContract(IPostStorageContract postStorageContract, ILogger logger) : IPostBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IPostStorageContract _postStorageContract = postStorageContract;
public List<PostDataModel> GetAllPosts(bool onlyActive = true)
{
_logger.LogInformation("GetAllPosts params: {onlyActive}", onlyActive);
return _postStorageContract.GetList(onlyActive) ?? 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,68 @@
using AndDietCokeContracts.BisnessLogicsContracts;
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Extensions;
using AndDietCokeContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static AndDietCokeBuisnessLogic.Implementations.SalaryBusinessLogicContract;
namespace AndDietCokeBuisnessLogic.Implementations;
internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract,
ISaleStorageContract saleStorageContract, IPostStorageContract postStorageContract, IWorkerStorageContract workerStorageContract, ILogger logger) : ISalaryBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISalaryStorageContract _salaryStorageContract = salaryStorageContract;
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
private readonly IWorkerStorageContract _workerStorageContract = workerStorageContract;
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 = _saleStorageContract.GetList(startDate, finishDate, workerId: worker.Id)?.Sum(x => x.Dishes!.Count) ??
throw new NullListException();
var salary = 100 + sales * 0.1;
_logger.LogDebug("The employee {workerId} was paid a salary of {salary}", worker.Id, salary);
_salaryStorageContract.AddElement(new SalaryDataModel(Guid.NewGuid().ToString(), worker.Id, finishDate, salary));
}
}
}

View File

@@ -0,0 +1,120 @@
using AndDietCokeContracts.BisnessLogicsContracts;
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Extensions;
using AndDietCokeContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace AndDietCokeBuisnessLogic.Implementations;
internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContract, ILogger logger) : ISaleBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
public List<SaleDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {fromDate}, {toDate}", fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _saleStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
}
public List<SaleDataModel> GetAllSalesByWorkerByPeriod(string workerId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales 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 _saleStorageContract.GetList(fromDate, toDate, workerId: workerId) ?? throw new NullListException();
}
public List<SaleDataModel> GetAllSalesByBuyerByPeriod(string buyerId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {buyerId}, {fromDate}, {toDate}", buyerId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (buyerId.IsEmpty())
{
throw new ArgumentNullException(nameof(buyerId));
}
if (!buyerId.IsGuid())
{
throw new ValidationException("The value in the field buyerId is not a unique identifier.");
}
return _saleStorageContract.GetList(fromDate, toDate, buyerId: buyerId) ?? throw new NullListException();
}
public List<SaleDataModel> GetAllSalesByDishByPeriod(string dishId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {dishId}, {fromDate}, {toDate}", dishId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (dishId.IsEmpty())
{
throw new ArgumentNullException(nameof(dishId));
}
if (!dishId.IsGuid())
{
throw new ValidationException("The value in the field dishId is not a unique identifier.");
}
return _saleStorageContract.GetList(fromDate, toDate, dishId: dishId) ?? throw new NullListException();
}
public SaleDataModel GetSaleByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (!data.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
return _saleStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
public void InsertSale(SaleDataModel saleDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(saleDataModel));
ArgumentNullException.ThrowIfNull(saleDataModel);
saleDataModel.Validate();
_saleStorageContract.AddElement(saleDataModel);
}
public void CancelSale(string id)
{
_logger.LogInformation("Cancel by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_saleStorageContract.DelElement(id);
}
}

View File

@@ -0,0 +1,104 @@
using AndDietCokeContracts.BisnessLogicsContracts;
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Extensions;
using AndDietCokeContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace AndDietCokeBuisnessLogic.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

@@ -1,9 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -1,45 +0,0 @@
using AndDietCokeContracts.Enums;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Extensions;
using AndDietCokeContracts.Infrastructure;
namespace AndDietCokeContracts.DataModels;
public class DishDataModel(string id, string name, DishType dishType, double price, string orderid) : IValidation
{
public string Id { get; private set; } = id;
public string Name { get; private set; } = name;
public DishType DishType { get; private set; } = dishType;
public double Price { get; private set; } = price;
public string OrderId { get; private set; } = orderid;
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 (Price <= 0)
throw new ValidationException("Field Price is less than or equal to 0");
if (DishType == DishType.None)
throw new ValidationException("Field DishType is empty");
if (OrderId.IsEmpty())
throw new ValidationException("Field OrderId is empty");
if (!OrderId.IsGuid())
throw new ValidationException("The value in the field OrderId is not a unique identifier");
}
}

View File

@@ -1,39 +0,0 @@
using AndDietCokeContracts.Enums;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Extensions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace AndDietCokeContracts.DataModels;
public class Dish_OrderDataModel(string orderid, string dishid, int count)
{
public string OrderId { get; private set; } = orderid;
public string DishId { get; private set; } = dishid;
public int Count { get; private set; } = count;
public void Validate()
{
if (OrderId.IsEmpty())
throw new ValidationException("Field OrderId is empty");
if (!OrderId.IsGuid())
throw new ValidationException("The value in the field OrderId is not a unique identifier");
if (DishId.IsEmpty())
throw new ValidationException("Field DishId is empty");
if (!DishId.IsGuid())
throw new ValidationException("The value in the field DishId is not a unique identifier");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
}
}

View File

@@ -1,31 +0,0 @@
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Extensions;
using AndDietCokeContracts.Infrastructure;
namespace AndDietCokeContracts.DataModels;
public class OrderDataModels(string id, string clientid, string employeedid, List<Dish_OrderDataModel> dishes) : IValidation
{
public string Id { get; private set; } = id;
public string ClientId { get; private set; } = clientid;
public string EmloyeedId { get; private set; } = employeedid;
public List<Dish_OrderDataModel> Dishes { get; private set; } = dishes;
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException("Field SaleId is empty");
if (!Id.IsGuid())
throw new ValidationException("The value in the field SaleId is not a unique identifier");
if (ClientId.IsEmpty())
throw new ValidationException("Field ClientId is empty");
if (!ClientId.IsGuid())
throw new ValidationException("The value in the field ClientId is not a unique identifier");
if (EmloyeedId.IsEmpty())
throw new ValidationException("Field ClientId is empty");
if (!EmloyeedId.IsGuid())
throw new ValidationException("The value in the field ClientId is not a unique identifier");
if ((Dishes?.Count ?? 0) == 0)
throw new ValidationException("The sale must include dishes");
}
}

View File

@@ -1,36 +0,0 @@
using AndDietCokeContracts.Enums;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Extensions;
using AndDietCokeContracts.Infrastructure;
using System.Text.RegularExpressions;
using System.Xml;
namespace AndDietCokeContracts.DataModels;
public class PositionDataModell(string id, string positionId, string positionName, PositionType positionType, double salary, bool isActual, DateTime changeDate) : IValidation
{
public string Id { get; private set; } = id;
public string PositionId { get; private set; } = positionId;
public string PositionName { get; private set; } = positionName;
public PositionType PositionType { get; private set; } = positionType;
public double Salary { get; private set; } = salary;
public bool IsActual { get; private set; } = isActual;
public DateTime ChangeDate { get; private set; } = changeDate;
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 (PositionId.IsEmpty())
throw new ValidationException("Field PostId is empty");
if (!PositionId.IsGuid())
throw new ValidationException("The value in the field PostId is not a unique identifier");
if (PositionName.IsEmpty())
throw new ValidationException("Field PostName is empty");
if (PositionType == PositionType.None)
throw new ValidationException("Field PostType is empty");
if (Salary <= 0)
throw new ValidationException("Field Salary is empty");
}
}

View File

@@ -1,28 +0,0 @@
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Extensions;
using AndDietCokeContracts.Infrastructure;
namespace AndDietCokeContracts.DataModels;
public class SalaryDataModel(string id, DateTime salaryDate, double salary, string employeedid) : IValidation
{
public string Id { get; private set; } = id;
public DateTime SalaryDate { get; private set; } = salaryDate;
public double Salary { get; private set; } = salary;
public string EmloyeedId { get; private set; } = employeedid;
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 (Salary <= 0)
throw new ValidationException("Field Salary is less than or equal to 0");
if (EmloyeedId.IsEmpty())
throw new ValidationException("Field ClientId is empty");
if (!EmloyeedId.IsGuid())
throw new ValidationException("The value in the field ClientId is not a unique identifier");
}
}

View File

@@ -1,33 +0,0 @@
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Extensions;
using AndDietCokeContracts.Infrastructure;
using System.Text.RegularExpressions;
namespace AndDietCokeContracts.DataModels;
public class СlientDataModel(string id, string fio, string contact, double discountsize) : IValidation
{
public string Id { get; private set; } = id;
public string FIO { get; private set; } = fio;
public string Contact { get; private set; } = contact;
public double DiscountSize { get; private set; } = discountsize;
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 (Contact.IsEmpty())
throw new ValidationException("Field PhoneNumber is empty");
if (!Regex.IsMatch(Contact , @"^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\-]?)?[\d\- ]{7,10}$"))
throw new ValidationException("Field PhoneNumber is not a phone number");
}
}

View File

@@ -1,11 +0,0 @@
namespace AndDietCokeContracts.Enums;
[Flags]
public enum DiscountType
{
None = 0,
OnSale = 1,
RegularCustumer = 2,
Certificate = 4
}

View File

@@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>preview</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="EntityFramework" Version="6.5.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.4" />
<PackageReference Include="Npgsql" Version="9.0.3" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AndDietCokeProject\AndDietCokeContracts.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="AndDietCokeTests" />
<InternalsVisibleTo Include="AndDietCokeWebApi" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,63 @@
using AndDietCokeDatabase.Models;
using AndDietCokeContracts.Infrastrusture;
using Microsoft.EntityFrameworkCore;
namespace AndDietCokeDatabase;
public class AndDietCokeDbContext : DbContext
{
private readonly IConfigurationDatabase? _configurationDatabase;
public AndDietCokeDbContext(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<Buyer>()
.HasIndex(x => x.PhoneNumber).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<Dish>()
.HasIndex(x => new { x.DishName, x.IsDeleted })
.IsUnique()
.HasFilter($"\"{nameof(Dish.IsDeleted)}\" = FALSE");
modelBuilder.Entity<OrderDish>()
.HasKey(x => new { x.OrderId, x.DishId });
}
public DbSet<Buyer> Buyers { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<Dish> Dishes { get; set; }
public DbSet<DishHistory> DishHistories { get; set; }
public DbSet<Salary> Salaries { get; set; }
public DbSet<Sale> Sales { get; set; }
public DbSet<OrderDish> OrderDishes { get; set; }
public DbSet<Worker> Workers { get; set; }
}

View File

@@ -0,0 +1,153 @@
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.StoragesContracts;
using AndDietCokeDatabase.Models;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeDatabase.Implementations;
internal class BuyerStorageContract : IBuyerStorageContract
{
private readonly AndDietCokeDbContext _dbContext;
private readonly Mapper _mapper;
public BuyerStorageContract(AndDietCokeDbContext andDietCokeDbContext)
{
_dbContext = andDietCokeDbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(AndDietCokeDbContext).Assembly);
});
_mapper = new Mapper(config);
}
public List<BuyerDataModel> GetList()
{
try
{
return [.. _dbContext.Buyers.Select(x => _mapper.Map<BuyerDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public BuyerDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<BuyerDataModel>(GetBuyerById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public BuyerDataModel? GetElementByFIO(string fio)
{
try
{
return _mapper.Map<BuyerDataModel>(_dbContext.Buyers.FirstOrDefault(x => x.FIO == fio));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public BuyerDataModel? GetElementByPhoneNumber(string phoneNumber)
{
try
{
return _mapper.Map<BuyerDataModel>(_dbContext.Buyers.FirstOrDefault(x => x.PhoneNumber == phoneNumber));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(BuyerDataModel buyerDataModel)
{
try
{
_dbContext.Buyers.Add(_mapper.Map<Buyer>(buyerDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", buyerDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Buyers_PhoneNumber" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PhoneNumber", buyerDataModel.PhoneNumber);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(BuyerDataModel buyerDataModel)
{
try
{
var element = GetBuyerById(buyerDataModel.Id) ?? throw new ElementNotFoundException(buyerDataModel.Id);
_dbContext.Buyers.Update(_mapper.Map(buyerDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Buyers_PhoneNumber" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PhoneNumber", buyerDataModel.PhoneNumber);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetBuyerById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Buyers.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Buyer? GetBuyerById(string id) => _dbContext.Buyers.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,176 @@
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.StoragesContracts;
using AndDietCokeDatabase.Models;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeDatabase.Implementations;
internal class DishStorageContract : IDishStorageContract
{
private readonly AndDietCokeDbContext _dbContext;
private readonly Mapper _mapper;
public DishStorageContract(AndDietCokeDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Dish, DishDataModel>();
cfg.CreateMap<DishDataModel, Dish>()
.ForMember(x => x.IsDeleted, x => x.MapFrom(src => false));
cfg.CreateMap<DishHistory, DishHistoryDataModel>();
});
_mapper = new Mapper(config);
}
public List<DishDataModel> GetList(bool onlyActive = true)
{
try
{
var query = _dbContext.Dishes.AsQueryable();
if (onlyActive)
{
query = query.Where(x => !x.IsDeleted);
}
return [.. query.Select(x => _mapper.Map<DishDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public List<DishHistoryDataModel> GetHistoryByDishId(string dishId)
{
try
{
return [.. _dbContext.DishHistories.Include(x => x.Dish).Where(x => x.DishId == dishId).OrderByDescending(x => x.ChangeDate).Select(x => _mapper.Map<DishHistoryDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public DishDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<DishDataModel>(GetDishById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public DishDataModel? GetElementByName(string name)
{
try
{
return _mapper.Map<DishDataModel>(_dbContext.Dishes.FirstOrDefault(x => x.DishName == name && !x.IsDeleted));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(DishDataModel dishDataModel)
{
try
{
_dbContext.Dishes.Add(_mapper.Map<Dish>(dishDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", dishDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Dishes_DishName_IsDeleted" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("DishName", dishDataModel.DishName);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(DishDataModel dishDataModel)
{
try
{
var transaction = _dbContext.Database.BeginTransaction();
try
{
var element = GetDishById(dishDataModel.Id) ?? throw new ElementNotFoundException(dishDataModel.Id);
if (element.Price != dishDataModel.Price)
{
_dbContext.DishHistories.Add(new DishHistory() { DishId = element.Id, OldPrice = element.Price });
_dbContext.SaveChanges();
}
_dbContext.Dishes.Update(_mapper.Map(dishDataModel, element));
_dbContext.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Dishes_DishName_IsDeleted" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("DishName", dishDataModel.DishName);
}
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 = GetDishById(id) ?? throw new ElementNotFoundException(id);
element.IsDeleted = true;
_dbContext.SaveChanges();
}
catch (ElementNotFoundException ex)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Dish? GetDishById(string id) => _dbContext.Dishes.FirstOrDefault(x => x.Id == id && !x.IsDeleted);
}

View File

@@ -0,0 +1,191 @@
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.StoragesContracts;
using AndDietCokeDatabase.Models;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeDatabase.Implementations;
internal class PostStorageContract : IPostStorageContract
{
private readonly AndDietCokeDbContext _dbContext;
private readonly Mapper _mapper;
public PostStorageContract(AndDietCokeDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Post, PostDataModel>()
.ForMember(x => x.Id, opt => opt.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));
});
_mapper = new Mapper(config);
}
public List<PostDataModel> GetList(bool onlyActual = true)
{
try
{
var query = _dbContext.Posts.AsQueryable();
return [.. query.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,64 @@
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.StoragesContracts;
using AndDietCokeDatabase.Models;
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeDatabase.Implementations;
internal class SalaryStorageContract : ISalaryStorageContract
{
private readonly AndDietCokeDbContext _dbContext;
private readonly Mapper _mapper;
public SalaryStorageContract(AndDietCokeDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Worker, WorkerDataModel>();
cfg.CreateMap<WorkerDataModel, Worker>();
cfg.CreateMap<Salary, SalaryDataModel>();
cfg.CreateMap<SalaryDataModel, Salary>()
.ForMember(dest => dest.WorkerSalary, opt => opt.MapFrom(src => src.Salary));
});
_mapper = new Mapper(config);
}
public List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? workerId = null)
{
try
{
var query = _dbContext.Salaries.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,121 @@
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.StoragesContracts;
using AndDietCokeDatabase.Models;
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace AndDietCokeDatabase.Implementations;
internal class SaleStorageContract : ISaleStorageContract
{
private readonly AndDietCokeDbContext _dbContext;
private readonly Mapper _mapper;
public SaleStorageContract(AndDietCokeDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Buyer, BuyerDataModel>();
cfg.CreateMap<Dish, DishDataModel>();
cfg.CreateMap<Worker, WorkerDataModel>();
cfg.CreateMap<OrderDish, OrderDishDataModel>();
cfg.CreateMap<Sale, SaleDataModel>();
cfg.CreateMap<OrderDishDataModel, OrderDish>();
cfg.CreateMap<SaleDataModel, Sale>()
.ForMember(x => x.IsCancel, x => x.MapFrom(src => false))
.ForMember(x => x.OrderDishes, x => x.MapFrom(src => src.Dishes));
});
_mapper = new Mapper(config);
}
public List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? workerId = null, string? buyerId = null, string? dishId = null)
{
try
{
var query = _dbContext.Sales.Include(x => x.Buyer).Include(x => x.Worker).Include(x => x.OrderDishes)!.ThenInclude(x => x.Dish).AsQueryable();
if (startDate is not null && endDate is not null)
{
query = query.Where(x => x.SaleDate >= startDate && x.SaleDate < endDate);
}
if (workerId is not null)
{
query = query.Where(x => x.WorkerId == workerId);
}
if (buyerId is not null)
{
query = query.Where(x => x.BuyerId == buyerId);
}
if (dishId is not null)
{
query = query.Where(x => x.OrderDishes!.Any(y => y.DishId == dishId));
}
return [.. query.Select(x => _mapper.Map<SaleDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public SaleDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<SaleDataModel>(GetSaleById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(SaleDataModel saleDataModel)
{
try
{
_dbContext.Sales.Add(_mapper.Map<Sale>(saleDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetSaleById(id) ?? throw new ElementNotFoundException(id);
if (element.IsCancel)
{
throw new ElementDeletedException(id);
}
element.IsCancel = true;
_dbContext.SaveChanges();
}
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Sale? GetSaleById(string id) => _dbContext.Sales.Include(x => x.Buyer).Include(x => x.Worker).Include(x => x.OrderDishes)!.ThenInclude(x => x.Dish).FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,155 @@
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.StoragesContracts;
using AndDietCokeDatabase.Models;
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeDatabase.Implementations;
internal class WorkerStorageContract : IWorkerStorageContract
{
private readonly AndDietCokeDbContext _dbContext;
private readonly Mapper _mapper;
public WorkerStorageContract(AndDietCokeDbContext 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;
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
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,25 @@
using AndDietCokeContracts.DataModels;
using AutoMapper;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeDatabase.Models;
[AutoMap(typeof(BuyerDataModel), ReverseMap = true)]
public class Buyer
{
public required string Id { get; set; }
public required string FIO { get; set; }
public required string PhoneNumber { get; set; }
public double DiscountSize { get; set; }
[ForeignKey("BuyerId")]
public List<Sale>? Sales { get; set; }
}

View File

@@ -0,0 +1,26 @@
using AndDietCokeContracts.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeDatabase.Models;
public class Dish
{
public required string Id { get; set; }
public required string DishName { get; set; }
public DishType DishType { get; set; }
public double Price { get; set; }
public bool IsDeleted { get; set; }
[ForeignKey("DishId")]
public List<DishHistory>? DishHistories { get; set; }
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeDatabase.Models;
public class DishHistory
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string DishId { get; set; }
public double OldPrice { get; set; }
public DateTime ChangeDate { get; set; }
public Dish? Dish { get; set; }
}

View File

@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeDatabase.Models;
public class OrderDish
{
public required string OrderId { get; set; }
public required string DishId { get; set; }
public int Count { get; set; }
public double Price { get; set; }
public Sale? Sale { get; set; }
public Dish? Dish { get; set; }
}

View File

@@ -0,0 +1,25 @@
using AndDietCokeContracts.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeDatabase.Models;
public 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 double Salary { get; set; }
public bool IsActual { get; set; }
public DateTime ChangeDate { get; set; }
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeDatabase.Models;
public 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,32 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeDatabase.Models;
public class Sale
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string WorkerId { get; set; }
public string? BuyerId { get; set; }
public DateTime SaleDate { get; set; }
public double Sum { get; set; }
public bool IsConstantClient { get; set; }
public bool IsCancel { get; set; }
public Worker? Worker { get; set; }
public Buyer? Buyer { get; set; }
[ForeignKey("SaleId")]
public List<OrderDish>? OrderDishes { get; set; }
}

View File

@@ -0,0 +1,41 @@
using AndDietCokeContracts.DataModels;
using AutoMapper;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeDatabase.Models;
[AutoMap(typeof(WorkerDataModel), ReverseMap = true)]
public 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; }
[NotMapped]
public Post? Post { get; set; }
[ForeignKey("WorkerId")]
public List<Salary>? Salaries { get; set; }
[ForeignKey("WorkerId")]
public List<Sale>? Sales { get; set; }
public Worker AddPost(Post? post)
{
Post = post;
return this;
}
}

View File

@@ -1,11 +1,20 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.12.35707.178
VisualStudioVersion = 17.7.34024.191
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AndDietCokeContracts", "AndDietCokeContracts\AndDietCokeContracts.csproj", "{775E4654-C135-47D1-A1FF-4B26160CA6CB}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AndDietCokeContracts", "AndDietCokeProject\AndDietCokeContracts.csproj", "{624595D1-D7AA-4448-AA30-4D5AA21AE6D6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AndDietCokeTests", "AndDietCokeTests\AndDietCokeTests.csproj", "{97CF49C2-6F17-4FCB-B2AD-D84AED6A1AF9}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AndDietCokeTests", "AndDietCokeTests\AndDietCokeTests.csproj", "{EABA3AD5-7690-448A-BEE6-010499DD8790}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AndDietCokeBuisnessLogic", "AndDietCokeBuisnessLogic\AndDietCokeBuisnessLogic.csproj", "{3C1C0E8F-5CB4-4E93-B20C-86FF4B248ECF}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AndDietCokeDatabase", "AndDietCokeDatabase\AndDietCokeDatabase.csproj", "{4AFC4FDC-F8CA-4CC5-84E2-162ADA98EDD4}"
ProjectSection(ProjectDependencies) = postProject
{624595D1-D7AA-4448-AA30-4D5AA21AE6D6} = {624595D1-D7AA-4448-AA30-4D5AA21AE6D6}
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AndDietCokeWebApi", "AndDietCokeWebApi\AndDietCokeWebApi.csproj", "{59659F17-4A33-47B1-951B-A329A547B3BF}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -13,16 +22,31 @@ Global
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{775E4654-C135-47D1-A1FF-4B26160CA6CB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{775E4654-C135-47D1-A1FF-4B26160CA6CB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{775E4654-C135-47D1-A1FF-4B26160CA6CB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{775E4654-C135-47D1-A1FF-4B26160CA6CB}.Release|Any CPU.Build.0 = Release|Any CPU
{97CF49C2-6F17-4FCB-B2AD-D84AED6A1AF9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{97CF49C2-6F17-4FCB-B2AD-D84AED6A1AF9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{97CF49C2-6F17-4FCB-B2AD-D84AED6A1AF9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{97CF49C2-6F17-4FCB-B2AD-D84AED6A1AF9}.Release|Any CPU.Build.0 = Release|Any CPU
{624595D1-D7AA-4448-AA30-4D5AA21AE6D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{624595D1-D7AA-4448-AA30-4D5AA21AE6D6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{624595D1-D7AA-4448-AA30-4D5AA21AE6D6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{624595D1-D7AA-4448-AA30-4D5AA21AE6D6}.Release|Any CPU.Build.0 = Release|Any CPU
{EABA3AD5-7690-448A-BEE6-010499DD8790}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EABA3AD5-7690-448A-BEE6-010499DD8790}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EABA3AD5-7690-448A-BEE6-010499DD8790}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EABA3AD5-7690-448A-BEE6-010499DD8790}.Release|Any CPU.Build.0 = Release|Any CPU
{3C1C0E8F-5CB4-4E93-B20C-86FF4B248ECF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3C1C0E8F-5CB4-4E93-B20C-86FF4B248ECF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3C1C0E8F-5CB4-4E93-B20C-86FF4B248ECF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3C1C0E8F-5CB4-4E93-B20C-86FF4B248ECF}.Release|Any CPU.Build.0 = Release|Any CPU
{4AFC4FDC-F8CA-4CC5-84E2-162ADA98EDD4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4AFC4FDC-F8CA-4CC5-84E2-162ADA98EDD4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4AFC4FDC-F8CA-4CC5-84E2-162ADA98EDD4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4AFC4FDC-F8CA-4CC5-84E2-162ADA98EDD4}.Release|Any CPU.Build.0 = Release|Any CPU
{59659F17-4A33-47B1-951B-A329A547B3BF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{59659F17-4A33-47B1-951B-A329A547B3BF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{59659F17-4A33-47B1-951B-A329A547B3BF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{59659F17-4A33-47B1-951B-A329A547B3BF}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {9D9DF4B3-57A3-423C-B4C4-78AD94A0FD6E}
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,22 @@
using AndDietCokeContracts.AdapterContracts.OperationResponses;
using AndDietCokeContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.AdapterContracts;
public interface IBuyerAdapter
{
BuyerOperationResponse GetList();
BuyerOperationResponse GetElement(string data);
BuyerOperationResponse RegisterBuyer(BuyerBindingModel buyerModel);
BuyerOperationResponse ChangeBuyerInfo(BuyerBindingModel buyerModel);
BuyerOperationResponse RemoveBuyer(string id);
}

View File

@@ -0,0 +1,24 @@
using AndDietCokeContracts.AdapterContracts.OperationResponses;
using AndDietCokeContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.AdapterContracts;
public interface IDishAdapter
{
DishOperationResponse GetList(bool includeDeleted);
DishOperationResponse GetHistory(string id);
DishOperationResponse GetElement(string data);
DishOperationResponse RegisterDish(DishBindingModel dishModel);
DishOperationResponse ChangeDishInfo(DishBindingModel dishModel);
DishOperationResponse RemoveDish(string id);
}

View File

@@ -0,0 +1,26 @@
using AndDietCokeContracts.AdapterContracts.OperationResponses;
using AndDietCokeContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.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,15 @@
using AndDietCokeContracts.AdapterContracts.OperationResponses;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.AdapterContracts;
public interface ISalaryAdapter
{
SalaryOperationResponse GetListByPeriod(DateTime fromDate, DateTime toDate);
SalaryOperationResponse GetListByPeriodByEmployee(DateTime fromDate, DateTime toDate, string employeeId);
SalaryOperationResponse CalculateSalary(DateTime date);
}

View File

@@ -0,0 +1,26 @@
using AndDietCokeContracts.AdapterContracts.OperationResponses;
using AndDietCokeContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.AdapterContracts;
public interface ISaleAdapter
{
SaleOperationResponse GetList(DateTime fromDate, DateTime toDate);
SaleOperationResponse GetWorkerList(string id, DateTime fromDate, DateTime toDate);
SaleOperationResponse GetBuyerList(string id, DateTime fromDate, DateTime toDate);
SaleOperationResponse GetDishList(string id, DateTime fromDate, DateTime toDate);
SaleOperationResponse GetElement(string id);
SaleOperationResponse MakeSale(SaleBindingModel saleModel);
SaleOperationResponse CancelSale(string id);
}

View File

@@ -0,0 +1,28 @@
using AndDietCokeContracts.AdapterContracts.OperationResponses;
using AndDietCokeContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.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,24 @@
using AndDietCokeContracts.Infrastrusture;
using AndDietCokeContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.AdapterContracts.OperationResponses;
public class BuyerOperationResponse : OperationResponse
{
public static BuyerOperationResponse OK(List<BuyerViewModel> data) => OK<BuyerOperationResponse, List<BuyerViewModel>>(data);
public static BuyerOperationResponse OK(BuyerViewModel data) => OK<BuyerOperationResponse, BuyerViewModel>(data);
public static BuyerOperationResponse NoContent() => NoContent<BuyerOperationResponse>();
public static BuyerOperationResponse BadRequest(string message) => BadRequest<BuyerOperationResponse>(message);
public static BuyerOperationResponse NotFound(string message) => NotFound<BuyerOperationResponse>(message);
public static BuyerOperationResponse InternalServerError(string message) => InternalServerError<BuyerOperationResponse>(message);
}

View File

@@ -0,0 +1,26 @@
using AndDietCokeContracts.Infrastrusture;
using AndDietCokeContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.AdapterContracts.OperationResponses;
public class DishOperationResponse : OperationResponse
{
public static DishOperationResponse OK(List<DishViewModel> data) => OK<DishOperationResponse, List<DishViewModel>>(data);
public static DishOperationResponse OK(List<DishHistoryViewModel> data) => OK<DishOperationResponse, List<DishHistoryViewModel>>(data);
public static DishOperationResponse OK(DishViewModel data) => OK<DishOperationResponse, DishViewModel>(data);
public static DishOperationResponse NoContent() => NoContent<DishOperationResponse>();
public static DishOperationResponse NotFound(string message) => NotFound<DishOperationResponse>(message);
public static DishOperationResponse BadRequest(string message) => BadRequest<DishOperationResponse>(message);
public static DishOperationResponse InternalServerError(string message) => InternalServerError<DishOperationResponse>(message);
}

View File

@@ -0,0 +1,24 @@
using AndDietCokeContracts.Infrastrusture;
using AndDietCokeContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.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,22 @@
using AndDietCokeContracts.Infrastrusture;
using AndDietCokeContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.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,24 @@
using AndDietCokeContracts.Infrastrusture;
using AndDietCokeContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.AdapterContracts.OperationResponses;
public class SaleOperationResponse : OperationResponse
{
public static SaleOperationResponse OK(List<SaleViewModel> data) => OK<SaleOperationResponse, List<SaleViewModel>>(data);
public static SaleOperationResponse OK(SaleViewModel data) => OK<SaleOperationResponse, SaleViewModel>(data);
public static SaleOperationResponse NoContent() => NoContent<SaleOperationResponse>();
public static SaleOperationResponse NotFound(string message) => NotFound<SaleOperationResponse>(message);
public static SaleOperationResponse BadRequest(string message) => BadRequest<SaleOperationResponse>(message);
public static SaleOperationResponse InternalServerError(string message) => InternalServerError<SaleOperationResponse>(message);
}

View File

@@ -0,0 +1,24 @@
using AndDietCokeContracts.Infrastrusture;
using AndDietCokeContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.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,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>preview</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="EntityFramework" Version="6.5.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.3.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.4" />
<PackageReference Include="Npgsql" Version="9.0.3" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,12 @@
namespace AndDietCokeContracts.BindingModels;
public class BuyerBindingModel
{
public string? Id { get; set; }
public string? FIO { get; set; }
public string? PhoneNumber { get; set; }
public double DiscountSize { 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 AndDietCokeContracts.BindingModels;
public class DishBindingModel
{
public string? Id { get; set; }
public string? DishName { get; set; }
public int DishType { get; set; }
public double Price { 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 AndDietCokeContracts.BindingModels;
public class OrderDishBindingModel
{
public string? SaleId { get; set; }
public string? DishId { get; set; }
public int Count { get; set; }
public double Price { get; set; }
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.BindingModels;
public class PostBindingModel
{
public string? Id { get; set; }
public string? PostId => Id;
public string? PostName { get; set; }
public string? PostType { get; set; }
public double Salary { 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 AndDietCokeContracts.BindingModels;
public class SaleBindingModel
{
public string? Id { get; set; }
public string? WorkerId { get; set; }
public string? BuyerId { get; set; }
public List<OrderDishBindingModel>? Dishes { get; set; }
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.BindingModels;
public class WorkerBindingModel
{
public string? Id { get; set; }
public string? FIO { get; set; }
public string? PostId { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
}

View File

@@ -0,0 +1,18 @@
using AndDietCokeContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.BisnessLogicsContracts;
public interface IBuyerBusinessLogicContract
{
List<BuyerDataModel> GetAllBuyers();
BuyerDataModel GetBuyerByData(string data);
void InsertBuyer(BuyerDataModel buyerDataModel);
void UpdateBuyer(BuyerDataModel buyerDataModel);
void DeleteBuyer(string id);
}

View File

@@ -0,0 +1,19 @@
using AndDietCokeContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.BisnessLogicsContracts;
public interface IDishBusinessLogicContract
{
List<DishDataModel> GetAllDishes(bool onlyActive = true);
List<DishHistoryDataModel> GetDishHistoryByDish(string dishId);
DishDataModel GetDishByData(string data);
void InsertDish(DishDataModel dishDataModel);
void UpdateDish(DishDataModel dishDataModel);
void DeleteDish(string id);
}

View File

@@ -0,0 +1,20 @@
using AndDietCokeContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.BisnessLogicsContracts;
public interface IPostBusinessLogicContract
{
List<PostDataModel> GetAllPosts(bool onlyActive);
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,15 @@
using AndDietCokeContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.BisnessLogicsContracts;
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 AndDietCokeContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.BisnessLogicsContracts;
public interface ISaleBusinessLogicContract
{
List<SaleDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate);
List<SaleDataModel> GetAllSalesByWorkerByPeriod(string workerId, DateTime fromDate, DateTime toDate);
List<SaleDataModel> GetAllSalesByBuyerByPeriod(string buyerId, DateTime fromDate, DateTime toDate);
List<SaleDataModel> GetAllSalesByDishByPeriod(string dishId, DateTime fromDate, DateTime toDate);
SaleDataModel GetSaleByData(string data);
void InsertSale(SaleDataModel saleDataModel);
void CancelSale(string id);
}

View File

@@ -0,0 +1,20 @@
using AndDietCokeContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.BisnessLogicsContracts;
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,37 @@
using AndDietCokeContracts.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;
using System.Xml;
using AndDietCokeContracts.Infrastrusture;
using AndDietCokeContracts.Exceptions;
namespace AndDietCokeContracts.DataModels;
public class BuyerDataModel(string id, string fio, string phoneNumber, double discountSize) : IValidation
{
public string Id { get; private set; } = id;
public string FIO { get; private set; } = fio;
public string PhoneNumber { get; private set; } = phoneNumber;
public double DiscountSize { get; private set; } = discountSize;
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 (PhoneNumber.IsEmpty())
throw new ValidationException("Field PhoneNumber is empty");
if (!Regex.IsMatch(PhoneNumber, @"^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7,10}$"))
throw new ValidationException("Field PhoneNumber is not a phone number");
if (!Regex.IsMatch(FIO, @"^[А-ЯЁA-Z][а-яёa-z]+(?:-[А-ЯЁA-Z][а-яёa-z]+)?\s[А-ЯЁA-Z][а-яёa-z]+(?:\s[А-ЯЁA-Z][а-яёa-z]+)?$"))
throw new ValidationException("Incorrect FIO input");
}
}

View File

@@ -0,0 +1,37 @@
using AndDietCokeContracts.Extensions;
using AndDietCokeContracts.Infrastrusture;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace AndDietCokeContracts.DataModels;
public class DishDataModel(string id, string dishName, DishType dishType, double price, bool isDeleted) : IValidation
{
public string Id { get; private set; } = id;
public string DishName { get; private set; } = dishName;
public DishType DishType { get; private set; } = dishType;
public double Price { get; private set; } = price;
public bool IsDeleted { get; private set; } = isDeleted;
public DishDataModel(string id, string dishName, int dishType, double price) : this(id, dishName, (DishType)dishType, price, 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 (DishName.IsEmpty())
throw new ValidationException("Field DishName is empty");
if (DishType == DishType.None)
throw new ValidationException("Field DishType is empty");
if (Price <= 0)
throw new ValidationException("Field Price is less than or equal to 0");
}
}

View File

@@ -1,6 +1,6 @@
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Extensions;
using AndDietCokeContracts.Infrastructure;
using AndDietCokeContracts.Extensions;
using AndDietCokeContracts.Infrastrusture;
using AndDietCokeContracts.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -9,13 +9,20 @@ using System.Threading.Tasks;
namespace AndDietCokeContracts.DataModels;
public class DishHistoryDataModel(string productId, double oldPrice, string orderid) : IValidation
public class DishHistoryDataModel(string dishId, double oldPrice) : IValidation
{
public string DishId { get; private set; } = productId;
private readonly DishDataModel? _dish;
public string DishId { get; private set; } = dishId;
public double OldPrice { get; private set; } = oldPrice;
public DateTime ChangeDate { get; private set; } = DateTime.UtcNow;
public string OrderId { get; private set; } = orderid;
public string DishName => _dish!.DishName;
public DishHistoryDataModel(string dishId, double oldPrice, DateTime changeDate, DishDataModel dish) : this(dishId, oldPrice)
{
ChangeDate = changeDate;
_dish = dish;
}
public void Validate()
{
if (DishId.IsEmpty())
@@ -24,10 +31,6 @@ public class DishHistoryDataModel(string productId, double oldPrice, string orde
throw new ValidationException("The value in the field DishId is not a unique identifier");
if (OldPrice <= 0)
throw new ValidationException("Field OldPrice is less than or equal to 0");
if (OrderId.IsEmpty())
throw new ValidationException("Field OrderId is empty");
if (!OrderId.IsGuid())
throw new ValidationException("The value in the field OrderId is not a unique identifier");
}
}

View File

@@ -0,0 +1,40 @@
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Extensions;
using AndDietCokeContracts.Infrastrusture;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.DataModels;
public class OrderDishDataModel(string orderId, string dishId, int count, double price) : IValidation
{
private readonly DishDataModel? _dish;
public string OrderId { get; private set; } = orderId;
public string DishId { get; private set; } = dishId;
public int Count { get; private set; } = count;
public double Price { get; private set; } = price;
public string DishName => _dish?.DishName ?? string.Empty;
public OrderDishDataModel(string saleId, string dishId, int count, double price, DishDataModel dish) : this(saleId, dishId, count, price)
{
_dish = dish;
}
public void Validate()
{
if (OrderId.IsEmpty())
throw new ValidationException("Field OrderId is empty");
if (!OrderId.IsGuid())
throw new ValidationException("The value in the field OrderId is not a unique identifier");
if (DishId.IsEmpty())
throw new ValidationException("Field DishId is empty");
if (!DishId.IsGuid())
throw new ValidationException("The value in the field DishId 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 AndDietCokeContracts.Enums;
using AndDietCokeContracts.Extensions;
using AndDietCokeContracts.Infrastrusture;
using AndDietCokeContracts.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace AndDietCokeContracts.DataModels;
public class PostDataModel(string id, string postName, PostType postType, double salary) : IValidation
{
public string Id { get; private set; } = id;
public string PostName { get; private set; } = postName;
public PostType PostType { get; private set; } = postType;
public double Salary { get; private set; } = salary;
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 (Salary <= 0)
throw new ValidationException("Field Salary is empty");
}
}

View File

@@ -0,0 +1,41 @@
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Extensions;
using AndDietCokeContracts.Infrastrusture;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.DataModels;
public class SalaryDataModel(string id, string workerId, DateTime salaryDate, double
workerSalary) : IValidation
{
private readonly WorkerDataModel? _worker;
public string Id { get; private set; } = id;
public string WorkerId { get; private set; } = workerId;
public DateTime SalaryDate { get; private set; } = salaryDate;
public double Salary { get; private set; } = workerSalary;
public string WorkerFIO => _worker?.FIO ?? string.Empty;
public SalaryDataModel(string id, string workerId, DateTime salaryDate, double salary, WorkerDataModel worker) : this(id, workerId, salaryDate, salary)
{
_worker = worker;
}
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException("Salary Id is empty");
if (!Id.IsGuid())
throw new ValidationException("Salary Id is not a valid GUID");
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 (Salary <= 0)
throw new ValidationException("Field Salary is less than or equal to 0");
}
}

View File

@@ -0,0 +1,68 @@
using AndDietCokeContracts.Enums;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Extensions;
using AndDietCokeContracts.Infrastrusture;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace AndDietCokeContracts.DataModels;
public class SaleDataModel : IValidation
{
private readonly BuyerDataModel? _buyer;
private readonly WorkerDataModel? _worker;
public string Id { get; private set; }
public string WorkerId { get; private set; }
public string? BuyerId { get; private set; }
public DateTime SaleDate { get; private set; } = DateTime.UtcNow;
public double Sum { get; private set; }
public bool IsConstantClient { get; private set; }
public bool IsCancel { get; private set; }
public List<OrderDishDataModel>? Dishes { get; private set; }
public string BuyerFIO => _buyer?.FIO ?? string.Empty;
public string WorkerFIO => _worker?.FIO ?? string.Empty;
public SaleDataModel(string id, string workerId, string? buyerId, bool isConstantClient, bool isCancel, List<OrderDishDataModel> orderDishes)
{
Id = id;
WorkerId = workerId;
BuyerId = buyerId;
IsCancel = isCancel;
IsConstantClient = isConstantClient;
Dishes = orderDishes;
Sum = Dishes?.Sum(x => x.Price * x.Count) ?? 0;
}
public SaleDataModel(string id, string workerId, string? buyerId, double sum, bool isConstantClient, bool isCancel, List<OrderDishDataModel> orderDishes, WorkerDataModel worker, BuyerDataModel? buyer) : this(id, workerId, buyerId, isConstantClient, isCancel, orderDishes)
{
Sum = sum;
_worker = worker;
_buyer = buyer;
}
public SaleDataModel(string id, string workerId, string? buyerId, List<OrderDishDataModel> dishes) : this(id, workerId, buyerId, true, false, dishes) { }
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 (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 (!BuyerId?.IsGuid() ?? !BuyerId?.IsEmpty() ?? false)
throw new ValidationException("The value in the field BuyerId is not a unique identifier");
if (Sum <= 0)
throw new ValidationException("Field Sum is less than or equal to 0");
if ((Dishes?.Count ?? 0) == 0)
throw new ValidationException("The sale must include dishes");
}
}

View File

@@ -1,50 +1,52 @@
using AndDietCokeContracts.Enums;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Extensions;
using AndDietCokeContracts.Infrastructure;
using System.Text.RegularExpressions;
using AndDietCokeContracts.Infrastrusture;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace AndDietCokeContracts.DataModels;
public class EmployeeDataModel(string id, string fio, string positionId, PositionType positiontype, DateTime birthDate, DateTime employmentDate, bool isDeleted) : IValidation
public class WorkerDataModel(string id, string fio, string postId, DateTime
birthDate, DateTime employmentDate, bool isDeleted) : IValidation
{
private readonly PostDataModel? _post;
public string Id { get; private set; } = id;
public string FIO { get; private set; } = fio;
public string PositionId { get; private set; } = positionId;
public PositionType PositionType { get; private set; } = positiontype;
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 PostName => _post?.PostName ?? string.Empty;
public WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted, PostDataModel post) : this(id, fio, postId, birthDate, employmentDate, isDeleted)
{
_post = post;
}
public WorkerDataModel(string id, string fio,string postId, DateTime birthDate, DateTime employmentDate) : this(id, fio, postId, birthDate, employmentDate, 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 (FIO.IsEmpty())
throw new ValidationException("Field FIO is empty");
if (!Regex.IsMatch(FIO, @"^([А-ЯЁ][а-яё]*(-[А-ЯЁ][а-яё]*)?)\s([А-ЯЁ]\.?\s?([А-ЯЁ]\.?\s?)?)?$"))
throw new ValidationException("Field FIO is not a fio");
if (PositionId.IsEmpty())
if (PostId.IsEmpty())
throw new ValidationException("Field PostId is empty");
if (!PositionId.IsGuid())
if (!PostId.IsGuid())
throw new ValidationException("The value in the field PostId is not a unique identifier");
if (BirthDate.Date > DateTime.Now.AddYears(-14).Date)
if (BirthDate.Date > DateTime.Now.AddYears(-16).Date)
throw new ValidationException($"Minors cannot be hired (BirthDate = {BirthDate.ToShortDateString()})");
if (PositionType == PositionType.None)
throw new ValidationException("Field PositionType is empty");
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 < 14)
throw new ValidationException($"Minors cannot be hired (EmploymentDate - {EmploymentDate.ToShortDateString()}, BirthDate -{BirthDate.ToShortDateString()})");
if ((EmploymentDate - BirthDate).TotalDays / 365 < 16) //EmploymentDate.Year - BirthDate.Year
throw new ValidationException($"Minors cannot be hired (EmploymentDate - {EmploymentDate.ToShortDateString()}, BirthDate - {BirthDate.ToShortDateString()})");
}
}
}

View File

@@ -9,10 +9,7 @@ namespace AndDietCokeContracts.Enums;
public enum DishType
{
None = 0,
Margherita = 1,
Pepperoni = 2,
BBQChicken = 3,
Veggie = 4,
Cola = 5
Base = 1,
Dessert = 2,
Drink = 3
}

View File

@@ -6,11 +6,11 @@ using System.Threading.Tasks;
namespace AndDietCokeContracts.Enums;
public enum PositionType
public enum PostType
{
None = 0,
Waiter = 1,
Сhef = 2,
Manager = 3,
Assistant = 4
Chef = 2,
Packer = 3
}

View File

@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.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 AndDietCokeContracts.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 AndDietCokeContracts.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,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace AndDietCokeContracts.Exceptions;
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 AndDietCokeContracts.Exceptions;
public class NullListException : Exception
{
public NullListException() : base("The returned list is null") { }
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.Exceptions;
public class StorageException : Exception
{
public StorageException(Exception ex) : base($"Error while working in storage: { ex.Message}", ex) { }
}

View File

@@ -8,8 +8,5 @@ namespace AndDietCokeContracts.Exceptions;
public class ValidationException : Exception
{
public ValidationException(string message) : base(message)
{
}
public ValidationException(string message) : base(message) { }
}

View File

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

View File

@@ -0,0 +1,6 @@
namespace AndDietCokeContracts.Infrastrusture;
public interface IConfigurationDatabase
{
string ConnectionString { get; }
}

View File

@@ -4,10 +4,9 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.Infrastructure
namespace AndDietCokeContracts.Infrastrusture;
public interface IValidation
{
public interface IValidation
{
void Validate();
}
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 AndDietCokeContracts.Infrastrusture;
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,19 @@
using AndDietCokeContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.StoragesContracts;
public interface IBuyerStorageContract
{
List<BuyerDataModel> GetList();
BuyerDataModel? GetElementById(string id);
BuyerDataModel? GetElementByPhoneNumber(string phoneNumber);
BuyerDataModel? GetElementByFIO(string fio);
void AddElement(BuyerDataModel buyerDataModel);
void UpdElement(BuyerDataModel buyerDataModel);
void DelElement(string id);
}

View File

@@ -0,0 +1,18 @@
using AndDietCokeContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.StoragesContracts;
public interface IDishStorageContract
{
List<DishDataModel> GetList(bool onlyActive = true);
List<DishHistoryDataModel> GetHistoryByDishId(string dishId);
DishDataModel? GetElementById(string id);
DishDataModel? GetElementByName(string name);
void AddElement(DishDataModel dishDataModel);
void UpdElement(DishDataModel dishDataModel);
void DelElement(string id);
}

View File

@@ -0,0 +1,21 @@
using AndDietCokeContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.StoragesContracts;
public interface IPostStorageContract
{
List<PostDataModel> GetList(bool onlyActual = true);
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,15 @@
using AndDietCokeContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.StoragesContracts;
public interface ISalaryStorageContract
{
List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string?
workerId = null);
void AddElement(SalaryDataModel salaryDataModel);
}

View File

@@ -0,0 +1,17 @@
using AndDietCokeContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.StoragesContracts;
public interface ISaleStorageContract
{
List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? workerId = null, string? buyerId = null, string? dishId = null);
SaleDataModel? GetElementById(string id);
void AddElement(SaleDataModel saleDataModel);
void DelElement(string id);
}

View File

@@ -0,0 +1,19 @@
using AndDietCokeContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.StoragesContracts;
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);
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.ViewModels;
public class BuyerViewModel
{
public required string Id { get; set; }
public required string FIO { get; set; }
public required string PhoneNumber { get; set; }
public double DiscountSize { 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 AndDietCokeContracts.ViewModels;
public class DishHistoryViewModel
{
public required string DishName { get; set; }
public double OldPrice { get; set; }
public DateTime ChangeDate { get; set; }
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.ViewModels;
public class DishViewModel
{
public required string Id { get; set; }
public required string DishName { get; set; }
public required string DishType { get; set; }
public double Price { get; set; }
public bool IsDeleted { 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 AndDietCokeContracts.ViewModels;
public class OrderDishViewModel
{
public required string DishId { get; set; }
public required string DishName { get; set; }
public int Count { get; set; }
public double Price { 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 AndDietCokeContracts.ViewModels;
public class PostViewModel
{
public required string Id { get; set; }
public required string PostName { get; set; }
public required string PostType { get; set; }
public double Salary { 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 AndDietCokeContracts.ViewModels;
public class SalaryViewModel
{
public required string WorkerId { get; set; }
public required string WorkerFIO { get; set; }
public DateTime SalaryDate { get; set; }
public double Salary { get; set; }
}

View File

@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.ViewModels;
public class SaleViewModel
{
public required string Id { get; set; }
public required string WorkerId { get; set; }
public required string WorkerFIO { get; set; }
public string? BuyerId { get; set; }
public string? BuyerFIO { get; set; }
public DateTime SaleDate { get; set; }
public double Sum { get; set; }
public bool IsConstantClient { get; private set; }
public bool IsCancel { get; set; }
public required List<OrderDishViewModel> Dishes { get; set; }
}

View File

@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.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 bool IsDeleted { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
}

View File

@@ -1,28 +1,48 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
<LangVersion>preview</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="EntityFramework" Version="6.5.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.4" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="9.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.4" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.4" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.13.0" />
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="Npgsql" Version="9.0.3" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
<PackageReference Include="NUnit" Version="4.3.2" />
<PackageReference Include="NUnit3TestAdapter" Version="5.0.0" />
<PackageReference Include="NUnit.Analyzers" Version="4.7.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="6.0.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Serilog" Version="4.2.0" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="NUnit" Version="3.14.0" />
<PackageReference Include="NUnit.Analyzers" Version="3.9.0" />
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AndDietCokeBuisnessLogic\AndDietCokeBuisnessLogic.csproj" />
<ProjectReference Include="..\AndDietCokeDatabase\AndDietCokeDatabase.csproj" />
<ProjectReference Include="..\AndDietCokeProject\AndDietCokeContracts.csproj" />
<ProjectReference Include="..\AndDietCokeWebApi\AndDietCokeWebApi.csproj" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AndDietCokeContracts\AndDietCokeContracts.csproj" />
</ItemGroup>
<ItemGroup>
<Using Include="NUnit.Framework" />
</ItemGroup>
<ItemGroup>
<Using Include="NUnit.Framework" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,356 @@
using AndDietCokeContracts.BisnessLogicsContracts;
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.StoragesContracts;
using AndDietCokeBuisnessLogic.Implementations;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Extensions;
using NUnit.Framework;
using System;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Moq;
namespace AndDietCokeTests.BuisnessLogicsContractsTests;
[TestFixture]
internal class BuyerBusinessLogicContractTests
{
private BuyerBusinessLogicContract _buyerBusinessLogicContract;
private Mock<IBuyerStorageContract> _buyerStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_buyerStorageContract = new Mock<IBuyerStorageContract>();
_buyerBusinessLogicContract = new BuyerBusinessLogicContract(_buyerStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_buyerStorageContract.Reset();
}
[Test]
public void GetAllBuyers_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<BuyerDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", "+7-111-111-11-11", 10),
new(Guid.NewGuid().ToString(), "fio 2", "+7-555-444-33-23", 10),
new(Guid.NewGuid().ToString(), "fio 3", "+7-777-777-7777", 10),
};
_buyerStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
//Act
var list = _buyerBusinessLogicContract.GetAllBuyers();
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
}
[Test]
public void GetAllBuyers_ReturnEmptyList_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.GetList()).Returns([]);
//Act
var list = _buyerBusinessLogicContract.GetAllBuyers();
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_buyerStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllBuyers_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.GetAllBuyers(), Throws.TypeOf<NullListException>());
_buyerStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllBuyers_StorageThrowError_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.GetAllBuyers(), Throws.TypeOf<StorageException>());
_buyerStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetBuyerByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new BuyerDataModel(id, "fio", "+7-111-111-11-11", 10);
_buyerStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _buyerBusinessLogicContract.GetBuyerByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_buyerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetBuyerByData_GetByFio_ReturnRecord_Test()
{
//Arrange
var fio = "fio";
var record = new BuyerDataModel(Guid.NewGuid().ToString(), fio, "+7-111-111-11-11", 10);
_buyerStorageContract.Setup(x => x.GetElementByFIO(fio)).Returns(record);
//Act
var element = _buyerBusinessLogicContract.GetBuyerByData(fio);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.FIO, Is.EqualTo(fio));
_buyerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetBuyerByData_GetByPhoneNumber_ReturnRecord_Test()
{
//Arrange
var phoneNumber = "+7-111-111-11-11";
var record = new BuyerDataModel(Guid.NewGuid().ToString(), "fio", phoneNumber, 10);
_buyerStorageContract.Setup(x => x.GetElementByPhoneNumber(phoneNumber)).Returns(record);
//Act
var element = _buyerBusinessLogicContract.GetBuyerByData(phoneNumber);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.PhoneNumber, Is.EqualTo(phoneNumber));
_buyerStorageContract.Verify(x => x.GetElementByPhoneNumber(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetBuyerByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.GetBuyerByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _buyerBusinessLogicContract.GetBuyerByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_buyerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_buyerStorageContract.Verify(x => x.GetElementByPhoneNumber(It.IsAny<string>()), Times.Never);
_buyerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetBuyerByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.GetBuyerByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_buyerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_buyerStorageContract.Verify(x => x.GetElementByPhoneNumber(It.IsAny<string>()), Times.Never);
_buyerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetBuyerByData_GetByFio_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.GetBuyerByData("fio"), Throws.TypeOf<ElementNotFoundException>());
_buyerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_buyerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
_buyerStorageContract.Verify(x => x.GetElementByPhoneNumber(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetBuyerByData_GetByPhoneNumber_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.GetBuyerByData("+7-111-111-11-12"), Throws.TypeOf<ElementNotFoundException>());
_buyerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_buyerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
_buyerStorageContract.Verify(x => x.GetElementByPhoneNumber(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetBuyerByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_buyerStorageContract.Setup(x => x.GetElementByFIO(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_buyerStorageContract.Setup(x => x.GetElementByPhoneNumber(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.GetBuyerByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _buyerBusinessLogicContract.GetBuyerByData("fio"), Throws.TypeOf<StorageException>());
Assert.That(() => _buyerBusinessLogicContract.GetBuyerByData("+7-111-111-11-12"), Throws.TypeOf<StorageException>());
_buyerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_buyerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
_buyerStorageContract.Verify(x => x.GetElementByPhoneNumber(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertBuyer_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new BuyerDataModel(Guid.NewGuid().ToString(), "Петров Иван Александрович", "+7-111-111-11-11", 10);
_buyerStorageContract.Setup(x => x.AddElement(It.IsAny<BuyerDataModel>()))
.Callback((BuyerDataModel x) =>
{
flag = x.Id == record.Id && x.FIO == record.FIO && x.PhoneNumber == record.PhoneNumber;
});
//Act
_buyerBusinessLogicContract.InsertBuyer(record);
//Assert
_buyerStorageContract.Verify(x => x.AddElement(It.IsAny<BuyerDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertBuyer_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.AddElement(It.IsAny<BuyerDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.InsertBuyer(new(Guid.NewGuid().ToString(), "Петров Иван Александрович", "+7-111-111-11-11", 10)), Throws.TypeOf<ElementExistsException>());
_buyerStorageContract.Verify(x => x.AddElement(It.IsAny<BuyerDataModel>()), Times.Once);
}
[Test]
public void InsertBuyer_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.InsertBuyer(null), Throws.TypeOf<ArgumentNullException>());
_buyerStorageContract.Verify(x => x.AddElement(It.IsAny<BuyerDataModel>()), Times.Never);
}
[Test]
public void InsertBuyer_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.InsertBuyer(new BuyerDataModel("id", "fio", "+7-111-111-11-11", 10)), Throws.TypeOf<ValidationException>());
_buyerStorageContract.Verify(x => x.AddElement(It.IsAny<BuyerDataModel>()), Times.Never);
}
[Test]
public void InsertBuyer_StorageThrowError_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.AddElement(It.IsAny<BuyerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.InsertBuyer(new(Guid.NewGuid().ToString(), "Петров Иван Александрович", "+7-111-111-11-11", 10)), Throws.TypeOf<StorageException>());
_buyerStorageContract.Verify(x => x.AddElement(It.IsAny<BuyerDataModel>()), Times.Once);
}
[Test]
public void UpdateBuyer_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new BuyerDataModel(Guid.NewGuid().ToString(), "Петров Иван Александрович", "+7-111-111-11-11", 10);
_buyerStorageContract.Setup(x => x.UpdElement(It.IsAny<BuyerDataModel>()))
.Callback((BuyerDataModel x) =>
{
flag = x.Id == record.Id && x.FIO == record.FIO && x.PhoneNumber == record.PhoneNumber;
});
//Act
_buyerBusinessLogicContract.UpdateBuyer(record);
//Assert
_buyerStorageContract.Verify(x => x.UpdElement(It.IsAny<BuyerDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdateBuyer_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.UpdElement(It.IsAny<BuyerDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.UpdateBuyer(new(Guid.NewGuid().ToString(), "Петров Иван Александрович", "+7-111-111-11-11", 10)), Throws.TypeOf<ElementNotFoundException>());
_buyerStorageContract.Verify(x => x.UpdElement(It.IsAny<BuyerDataModel>()), Times.Once);
}
[Test]
public void UpdateBuyer_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.UpdElement(It.IsAny<BuyerDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.UpdateBuyer(new(Guid.NewGuid().ToString(), "Петров Иван Александрович", "+7-111-111-11-11", 10)), Throws.TypeOf<ElementExistsException>());
_buyerStorageContract.Verify(x => x.UpdElement(It.IsAny<BuyerDataModel>()), Times.Once);
}
[Test]
public void UpdateBuyer_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.UpdateBuyer(null), Throws.TypeOf<ArgumentNullException>());
_buyerStorageContract.Verify(x => x.UpdElement(It.IsAny<BuyerDataModel>()), Times.Never);
}
[Test]
public void UpdateBuyer_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.UpdateBuyer(new BuyerDataModel("id", "Петров Иван Александрович", "+7-111-111-11-11", 10)), Throws.TypeOf<ValidationException>());
_buyerStorageContract.Verify(x => x.UpdElement(It.IsAny<BuyerDataModel>()), Times.Never);
}
[Test]
public void UpdateBuyer_StorageThrowError_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.UpdElement(It.IsAny<BuyerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.UpdateBuyer(new(Guid.NewGuid().ToString(), "Петров Иван Александрович", "+7-111-111-11-11", 10)), Throws.TypeOf<StorageException>());
_buyerStorageContract.Verify(x => x.UpdElement(It.IsAny<BuyerDataModel>()), Times.Once);
}
[Test]
public void DeleteBuyer_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_buyerStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_buyerBusinessLogicContract.DeleteBuyer(id);
//Assert
_buyerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void DeleteBuyer_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.DeleteBuyer(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_buyerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeleteBuyer_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.DeleteBuyer(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _buyerBusinessLogicContract.DeleteBuyer(string.Empty), Throws.TypeOf<ArgumentNullException>());
_buyerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteBuyer_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.DeleteBuyer("id"), Throws.TypeOf<ValidationException>());
_buyerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteBuyer_StorageThrowError_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.DeleteBuyer(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_buyerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -0,0 +1,404 @@
using AndDietCokeContracts.Exceptions;
using AndDietCokeBuisnessLogic.Implementations;
using AndDietCokeContracts.StoragesContracts;
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Enums;
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
using static NUnit.Framework.Internal.OSPlatform;
namespace AndDietCokeTests.BuisnessLogicsContractsTests;
internal class DishBusinessLogicContractTests
{
private DishBusinessLogicContract _dishBusinessLogicContract;
private Mock<IDishStorageContract> _dishStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_dishStorageContract = new Mock<IDishStorageContract>();
_dishBusinessLogicContract = new DishBusinessLogicContract(_dishStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_dishStorageContract.Reset();
}
[Test]
public void GetAllDishes_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<DishDataModel>()
{
new(Guid.NewGuid().ToString(), "name 1", DishType.Dessert, 10, false),
new(Guid.NewGuid().ToString(), "name 2", DishType.Dessert, 10, true),
new(Guid.NewGuid().ToString(), "name 3", DishType.Dessert, 10, false),
};
_dishStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Returns(listOriginal);
//Act
var listOnlyActive = _dishBusinessLogicContract.GetAllDishes(true);
var list = _dishBusinessLogicContract.GetAllDishes(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));
});
_dishStorageContract.Verify(x => x.GetList(true), Times.Once);
_dishStorageContract.Verify(x => x.GetList(false), Times.Once);
}
[Test]
public void GetAllDishes_ReturnEmptyList_Test()
{
//Arrange
_dishStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Returns([]);
//Act
var listOnlyActive = _dishBusinessLogicContract.GetAllDishes(true);
var list = _dishBusinessLogicContract.GetAllDishes(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));
});
_dishStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Exactly(2));
}
[Test]
public void GetAllDishes_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.GetAllDishes(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_dishStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Once);
}
[Test]
public void GetAllDishes_StorageThrowError_ThrowException_Test()
{
//Arrange
_dishStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.GetAllDishes(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_dishStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Once);
}
[Test]
public void GetDishHistoryByDish_ReturnListOfRecords_Test()
{
//Arrange
var dishId = Guid.NewGuid().ToString();
var listOriginal = new List<DishHistoryDataModel>()
{
new(Guid.NewGuid().ToString(), 10),
new(Guid.NewGuid().ToString(), 15),
new(Guid.NewGuid().ToString(), 10),
};
_dishStorageContract.Setup(x => x.GetHistoryByDishId(It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _dishBusinessLogicContract.GetDishHistoryByDish(dishId);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_dishStorageContract.Verify(x => x.GetHistoryByDishId(dishId), Times.Once);
}
[Test]
public void GetDishHistoryByDish_ReturnEmptyList_Test()
{
//Arrange
_dishStorageContract.Setup(x => x.GetHistoryByDishId(It.IsAny<string>())).Returns([]);
//Act
var list = _dishBusinessLogicContract.GetDishHistoryByDish(Guid.NewGuid().ToString());
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_dishStorageContract.Verify(x => x.GetHistoryByDishId(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetDishHistoryByDish_DishIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.GetDishHistoryByDish(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _dishBusinessLogicContract.GetDishHistoryByDish(string.Empty), Throws.TypeOf<ArgumentNullException>());
_dishStorageContract.Verify(x => x.GetHistoryByDishId(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetDishHistoryByDish_DishIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.GetDishHistoryByDish("dishId"), Throws.TypeOf<ValidationException>());
_dishStorageContract.Verify(x => x.GetHistoryByDishId(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetDishHistoryByDish_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.GetDishHistoryByDish(Guid.NewGuid().ToString()), Throws.TypeOf<NullListException>());
_dishStorageContract.Verify(x => x.GetHistoryByDishId(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetDishHistoryByDish_StorageThrowError_ThrowException_Test()
{
//Arrange
_dishStorageContract.Setup(x => x.GetHistoryByDishId(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.GetDishHistoryByDish(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_dishStorageContract.Verify(x => x.GetHistoryByDishId(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetDishByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new DishDataModel(id, "name", DishType.Dessert, 10, false);
_dishStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _dishBusinessLogicContract.GetDishByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_dishStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetDishByData_GetByName_ReturnRecord_Test()
{
//Arrange
var name = "name";
var record = new DishDataModel(Guid.NewGuid().ToString(), name, DishType.Dessert, 10, false);
_dishStorageContract.Setup(x => x.GetElementByName(name)).Returns(record);
//Act
var element = _dishBusinessLogicContract.GetDishByData(name);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.DishName, Is.EqualTo(name));
_dishStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetDishByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.GetDishByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _dishBusinessLogicContract.GetDishByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_dishStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
_dishStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetDishByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.GetDishByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_dishStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetDishByData_GetByName_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.GetDishByData("name"), Throws.TypeOf<ElementNotFoundException>());
_dishStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetDishByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_dishStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_dishStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.GetDishByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _dishBusinessLogicContract.GetDishByData("name"), Throws.TypeOf<StorageException>());
_dishStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_dishStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertDish_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new DishDataModel(Guid.NewGuid().ToString(), "name", DishType.Dessert, 10, false);
_dishStorageContract.Setup(x => x.AddElement(It.IsAny<DishDataModel>()))
.Callback((DishDataModel x) =>
{
flag = x.Id == record.Id && x.DishName == record.DishName && x.DishType == record.DishType && x.Price == record.Price && x.IsDeleted == record.IsDeleted;
});
//Act
_dishBusinessLogicContract.InsertDish(record);
//Assert
_dishStorageContract.Verify(x => x.AddElement(It.IsAny<DishDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertDish_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_dishStorageContract.Setup(x => x.AddElement(It.IsAny<DishDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.InsertDish(new(Guid.NewGuid().ToString(), "name", DishType.Dessert, 10, false)), Throws.TypeOf<ElementExistsException>());
_dishStorageContract.Verify(x => x.AddElement(It.IsAny<DishDataModel>()), Times.Once);
}
[Test]
public void InsertDish_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.InsertDish(null), Throws.TypeOf<ArgumentNullException>());
_dishStorageContract.Verify(x => x.AddElement(It.IsAny<DishDataModel>()), Times.Never);
}
[Test]
public void InsertDish_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.InsertDish(new DishDataModel("id", "name", DishType.Dessert, 10, false)), Throws.TypeOf<ValidationException>());
_dishStorageContract.Verify(x => x.AddElement(It.IsAny<DishDataModel>()), Times.Never);
}
[Test]
public void InsertDish_StorageThrowError_ThrowException_Test()
{
//Arrange
_dishStorageContract.Setup(x => x.AddElement(It.IsAny<DishDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.InsertDish(new(Guid.NewGuid().ToString(), "name", DishType.Dessert, 10, false)), Throws.TypeOf<StorageException>());
_dishStorageContract.Verify(x => x.AddElement(It.IsAny<DishDataModel>()), Times.Once);
}
[Test]
public void UpdateDish_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new DishDataModel(Guid.NewGuid().ToString(), "name", DishType.Dessert, 10, false);
_dishStorageContract.Setup(x => x.UpdElement(It.IsAny<DishDataModel>()))
.Callback((DishDataModel x) =>
{
flag = x.Id == record.Id && x.DishName == record.DishName && x.DishType == record.DishType && x.Price == record.Price && x.IsDeleted == record.IsDeleted;
});
//Act
_dishBusinessLogicContract.UpdateDish(record);
//Assert
_dishStorageContract.Verify(x => x.UpdElement(It.IsAny<DishDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdateDish_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_dishStorageContract.Setup(x => x.UpdElement(It.IsAny<DishDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.UpdateDish(new(Guid.NewGuid().ToString(), "name", DishType.Dessert, 10, false)), Throws.TypeOf<ElementNotFoundException>());
_dishStorageContract.Verify(x => x.UpdElement(It.IsAny<DishDataModel>()), Times.Once);
}
[Test]
public void UpdateDish_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_dishStorageContract.Setup(x => x.UpdElement(It.IsAny<DishDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.UpdateDish(new(Guid.NewGuid().ToString(), "anme", DishType.Dessert, 10, false)), Throws.TypeOf<ElementExistsException>());
_dishStorageContract.Verify(x => x.UpdElement(It.IsAny<DishDataModel>()), Times.Once);
}
[Test]
public void UpdateDish_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.UpdateDish(null), Throws.TypeOf<ArgumentNullException>());
_dishStorageContract.Verify(x => x.UpdElement(It.IsAny<DishDataModel>()), Times.Never);
}
[Test]
public void UpdateDish_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.UpdateDish(new DishDataModel("id", "name", DishType.Dessert, 10, false)), Throws.TypeOf<ValidationException>());
_dishStorageContract.Verify(x => x.UpdElement(It.IsAny<DishDataModel>()), Times.Never);
}
[Test]
public void UpdateDish_StorageThrowError_ThrowException_Test()
{
//Arrange
_dishStorageContract.Setup(x => x.UpdElement(It.IsAny<DishDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.UpdateDish(new(Guid.NewGuid().ToString(), "name", DishType.Dessert, 10, false)), Throws.TypeOf<StorageException>());
_dishStorageContract.Verify(x => x.UpdElement(It.IsAny<DishDataModel>()), Times.Once);
}
[Test]
public void DeleteDish_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_dishStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_dishBusinessLogicContract.DeleteDish(id);
//Assert
_dishStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void DeleteDish_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_dishStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.DeleteDish(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_dishStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeleteDish_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.DeleteDish(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _dishBusinessLogicContract.DeleteDish(string.Empty), Throws.TypeOf<ArgumentNullException>());
_dishStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteDish_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.DeleteDish("id"), Throws.TypeOf<ValidationException>());
_dishStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteDish_StorageThrowError_ThrowException_Test()
{
//Arrange
_dishStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _dishBusinessLogicContract.DeleteDish(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_dishStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -0,0 +1,425 @@
using AndDietCokeContracts.BisnessLogicsContracts;
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Enums;
using AndDietCokeContracts.StoragesContracts;
using AndDietCokeBuisnessLogic.Implementations;
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using AndDietCokeContracts.Exceptions;
namespace AndDietCokeTests.BuisnessLogicsContractsTests;
[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.Chef, 10),
new(Guid.NewGuid().ToString(),"name 2", PostType.Chef, 10),
new(Guid.NewGuid().ToString(),"name 3", PostType.Chef, 10)
};
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Returns(listOriginal);
//Act
var listOnlyActive = _postBusinessLogicContract.GetAllPosts(true);
var listAll = _postBusinessLogicContract.GetAllPosts(false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(listAll, Is.Not.Null);
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(listAll, Is.EquivalentTo(listOriginal));
});
_postStorageContract.Verify(x => x.GetList(true), Times.Once);
_postStorageContract.Verify(x => x.GetList(false), Times.Once);
}
[Test]
public void GetAllPosts_ReturnEmptyList_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Returns([]);
//Act
var list = _postBusinessLogicContract.GetAllPosts(true);
//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(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_postStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Once);
}
[Test]
public void GetAllPosts_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllPosts(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Once);
}
[Test]
public void GetAllDataOfPost_ReturnListOfRecords_Test()
{
//Arrange
var postId = Guid.NewGuid().ToString();
var listOriginal = new List<PostDataModel>()
{
new(postId,"name 1", PostType.Chef, 10),
new(postId,"name 2", PostType.Chef, 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.Chef, 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(), "name", PostType.Chef, 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.Chef, 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.Salary == record.Salary;
});
//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.Chef, 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.Chef, 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.Chef, 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.Chef, 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.Salary == record.Salary;
});
//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.Chef, 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(), "name", PostType.Chef, 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.Chef, 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.Chef, 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,299 @@
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Enums;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.StoragesContracts;
using AndDietCokeBuisnessLogic.Implementations;
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace AndDietCokeTests.BuisnessLogicsContractsTests;
[TestFixture]
internal class SalaryBuisnessLogicContractTests
{
private SalaryBusinessLogicContract _salaryBusinessLogicContract;
private Mock<ISalaryStorageContract> _salaryStorageContract;
private Mock<ISaleStorageContract> _saleStorageContract;
private Mock<IPostStorageContract> _postStorageContract;
private Mock<IWorkerStorageContract> _workerStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_salaryStorageContract = new Mock<ISalaryStorageContract>();
_saleStorageContract = new Mock<ISaleStorageContract>();
_postStorageContract = new Mock<IPostStorageContract>();
_workerStorageContract = new Mock<IWorkerStorageContract>();
_salaryBusinessLogicContract = new SalaryBusinessLogicContract(_salaryStorageContract.Object,
_saleStorageContract.Object, _postStorageContract.Object, _workerStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_salaryStorageContract.Reset();
_saleStorageContract.Reset();
_postStorageContract.Reset();
_workerStorageContract.Reset();
}
[Test]
public void GetAllSalaries_ReturnListOfRecords_Test()
{
//Arrange
var startDate = DateTime.UtcNow;
var endDate = DateTime.UtcNow.AddDays(1);
var listOriginal = new List<SalaryDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DateTime.UtcNow, 10),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DateTime.UtcNow.AddDays(1), 14),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DateTime.UtcNow.AddDays(-1), 30),
};
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _salaryBusinessLogicContract.GetAllSalariesByPeriod(startDate, endDate);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_salaryStorageContract.Verify(x => x.GetList(startDate, endDate, null), Times.Once);
}
[Test]
public void GetAllSalaries_ReturnEmptyList_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Returns([]);
//Act
var list = _salaryBusinessLogicContract.GetAllSalariesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalaries_IncorrectDates_ThrowException_Test()
{
//Arrange
var dateTime = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriod(dateTime, dateTime), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriod(dateTime, dateTime.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalaries_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalaries_StorageThrowError_ThrowException_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalariesByWorker_ReturnListOfRecords_Test()
{
//Arrange
var startDate = DateTime.UtcNow;
var endDate = DateTime.UtcNow.AddDays(1);
var workerId = Guid.NewGuid().ToString();
var listOriginal = new List<SalaryDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DateTime.UtcNow, 10),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DateTime.UtcNow.AddDays(1), 14),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DateTime.UtcNow.AddDays(-1), 30),
};
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(startDate, endDate, workerId);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_salaryStorageContract.Verify(x => x.GetList(startDate, endDate, workerId), Times.Once);
}
[Test]
public void GetAllSalariesByWorker_ReturnEmptyList_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Returns([]);
//Act
var list = _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), Guid.NewGuid().ToString());
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalariesByWorker_IncorrectDates_ThrowException_Test()
{
//Arrange
var dateTime = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(dateTime, dateTime, Guid.NewGuid().ToString()), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(dateTime, dateTime.AddSeconds(-1), Guid.NewGuid().ToString()), Throws.TypeOf<IncorrectDatesException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalariesByWorker_WorkerIdIsNUllOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), string.Empty), Throws.TypeOf<ArgumentNullException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalariesByWorker_WorkerIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), "workerId"), Throws.TypeOf<ValidationException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalariesByWorker_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), Guid.NewGuid().ToString()), Throws.TypeOf<NullListException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalariesByWorker_StorageThrowError_ThrowException_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void CalculateSalaryByMounth_WithSeveralWorkers_Test()
{
//Arrange
var worker1Id = Guid.NewGuid().ToString();
var worker2Id = Guid.NewGuid().ToString();
var worker3Id = Guid.NewGuid().ToString();
var list = new List<WorkerDataModel>() {
new(worker1Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
new(worker2Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
new(worker3Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), worker1Id, null, true, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), worker1Id, null, true, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), worker2Id, null, true, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), worker3Id, null, true, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), worker3Id, null, true, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, 2000));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns(list);
//Act
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
//Assert
_salaryStorageContract.Verify(x => x.AddElement(It.IsAny<SalaryDataModel>()), Times.Exactly(list.Count));
}
[Test]
public void CalculateSalaryByMounth_WithoitSalesByWorker_Test()
{
//Arrange
var postSalary = 2000.0;
var workerId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, postSalary));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
var sum = 0.0;
var expectedSum = 100;
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
.Callback((SalaryDataModel x) =>
{
sum = x.Salary;
});
//Act
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
//Assert
Assert.That(sum, Is.EqualTo(expectedSum));
}
[Test]
public void CalculateSalaryByMounth_SaleStorageReturnNull_ThrowException_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, 2000));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
[Test]
public void CalculateSalaryByMounth_WorkerStorageReturnNull_ThrowException_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, true, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, 2000));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
[Test]
public void CalculateSalaryByMounth_SaleStorageThrowException_ThrowException_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, 2000));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
}
[Test]
public void CalculateSalaryByMounth_WorkerStorageThrowException_ThrowException_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, true, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, 2000));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
}
}

View File

@@ -0,0 +1,502 @@
using AndDietCokeBuisnessLogic.Implementations;
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.StoragesContracts;
using AndDietCokeContracts.Enums;
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
namespace AndDietCokeTests.BuisnessLogicsContractsTests;
[TestFixture]
internal class SaleBuisnessLogicContractTests
{
private SaleBusinessLogicContract _saleBusinessLogicContract;
private Mock<ISaleStorageContract> _saleStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_saleStorageContract = new Mock<ISaleStorageContract>();
_saleBusinessLogicContract = new SaleBusinessLogicContract(_saleStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_saleStorageContract.Reset();
}
[Test]
public void GetAllSalesByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var listOriginal = new List<SaleDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, true, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, true, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, true, false, []),
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByPeriod(date, date.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_saleStorageContract.Verify(x => x.GetList(date, date.AddDays(1), null, null, null), Times.Once);
}
[Test]
public void GetAllSalesByPeriod_ReturnEmptyList_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns([]);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByWorkerByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var workerId = Guid.NewGuid().ToString();
var listOriginal = new List<SaleDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, true, false,
[new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 20, 5)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, true, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, true, false, []),
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(workerId, date, date.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_saleStorageContract.Verify(x => x.GetList(date, date.AddDays(1), workerId, null, null), Times.Once);
}
[Test]
public void GetAllSalesByWorkerByPeriod_ReturnEmptyList_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns([]);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByWorkerByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(Guid.NewGuid().ToString(), date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(Guid.NewGuid().ToString(), date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByWorkerByPeriod_WorkerIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(null, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(string.Empty, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByWorkerByPeriod_WorkerIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod("workerId", DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByWorkerByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByWorkerByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByBuyerByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var buyerId = Guid.NewGuid().ToString();
var listOriginal = new List<SaleDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, true, false,
[new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 20, 5)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, true, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, true, false, []),
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(buyerId, date, date.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_saleStorageContract.Verify(x => x.GetList(date, date.AddDays(1), null, buyerId, null), Times.Once);
}
[Test]
public void GetAllSalesByBuyerByPeriod_ReturnEmptyList_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns([]);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByBuyerByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(Guid.NewGuid().ToString(), date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(Guid.NewGuid().ToString(), date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByBuyerByPeriod_BuyerIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(null, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(string.Empty, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByBuyerByPeriod_BuyerIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod("buyerId", DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByBuyerByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByBuyerByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByDishByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var dishId = Guid.NewGuid().ToString();
var listOriginal = new List<SaleDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, true, false,
[new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 20, 5)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, true, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, true, false, []),
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByDishByPeriod(dishId, date, date.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_saleStorageContract.Verify(x => x.GetList(date, date.AddDays(1), null, null, dishId), Times.Once);
}
[Test]
public void GetAllSalesByDishByPeriod_ReturnEmptyList_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns([]);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByDishByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByDishByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByDishByPeriod(Guid.NewGuid().ToString(), date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByDishByPeriod(Guid.NewGuid().ToString(), date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByDishByPeriod_DishIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByDishByPeriod(null, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByDishByPeriod(string.Empty, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByDishByPeriod_DishIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByDishByPeriod("dishId", DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByDishByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByDishByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByDishByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByDishByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetSaleByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new SaleDataModel(id, Guid.NewGuid().ToString(), null, true, false,
[new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 20, 5)]);
_saleStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _saleBusinessLogicContract.GetSaleByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetSaleByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetSaleByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetSaleByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetSaleByData_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetSaleByData("saleId"), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetSaleByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetSaleByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetSaleByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetSaleByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertSale_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new SaleDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), true, false, [new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 20, 5)]);
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>()))
.Callback((SaleDataModel x) =>
{
flag = x.Id == record.Id && x.WorkerId == record.WorkerId && x.BuyerId == record.BuyerId &&
x.SaleDate == record.SaleDate && x.Sum == record.Sum && x.IsCancel == record.IsCancel && x.Dishes.Count == record.Dishes.Count &&
x.Dishes.First().DishId == record.Dishes.First().DishId &&
x.Dishes.First().Count == record.Dishes.First().Count;
});
//Act
_saleBusinessLogicContract.InsertSale(record);
//Assert
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertSale_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), true, false, [new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 20, 5)])), Throws.TypeOf<ElementExistsException>());
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
}
[Test]
public void InsertSale_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertSale(null), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Never);
}
[Test]
public void InsertSale_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertSale(new SaleDataModel("id", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), true, false, [])), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Never);
}
[Test]
public void InsertSale_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), true, false, [new OrderDishDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 20, 5)])), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
}
[Test]
public void CancelSale_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_saleStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_saleBusinessLogicContract.CancelSale(id);
//Assert
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void CancelSale_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.CancelSale(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void CancelSale_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.CancelSale(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.CancelSale(string.Empty), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void CancelSale_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.CancelSale("id"), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void CancelSale_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.CancelSale(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -0,0 +1,562 @@
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.StoragesContracts;
using AndDietCokeBuisnessLogic.Implementations;
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeTests.BuisnessLogicsContractsTests;
internal class WorkerBusinessLogicContractTests
{
private WorkerBusinessLogicContract _workerBusinessLogicContract;
private Mock<IWorkerStorageContract> _workerStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_workerStorageContract = new Mock<IWorkerStorageContract>();
_workerBusinessLogicContract = new WorkerBusinessLogicContract(_workerStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_workerStorageContract.Reset();
}
[Test]
public void GetAllWorkers_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<WorkerDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
};
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllWorkers(true);
var list = _workerBusinessLogicContract.GetAllWorkers(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));
});
_workerStorageContract.Verify(x => x.GetList(true, null, null, null, null, null), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, null, null, null, null, null), Times.Once);
}
[Test]
public void GetAllWorkers_ReturnEmptyList_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns([]);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllWorkers(true);
var list = _workerBusinessLogicContract.GetAllWorkers(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));
});
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), null, null, null, null, null), Times.Exactly(2));
}
[Test]
public void GetAllWorkers_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkers(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkers_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkers(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), null, null, null, null, null), Times.Once);
}
[Test]
public void GetAllWorkersByPost_ReturnListOfRecords_Test()
{
//Arrange
var postId = Guid.NewGuid().ToString();
var listOriginal = new List<WorkerDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
};
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllWorkersByPost(postId, true);
var list = _workerBusinessLogicContract.GetAllWorkersByPost(postId, 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));
});
_workerStorageContract.Verify(x => x.GetList(true, postId, null, null, null, null), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, postId, null, null, null, null), Times.Once);
}
[Test]
public void GetAllWorkersByPost_ReturnEmptyList_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns([]);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllWorkersByPost(Guid.NewGuid().ToString(), true);
var list = _workerBusinessLogicContract.GetAllWorkersByPost(Guid.NewGuid().ToString(), 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));
});
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Exactly(2));
}
[Test]
public void GetAllWorkersByPost_PostIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByPost(null, It.IsAny<bool>()), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByPost(string.Empty, It.IsAny<bool>()), Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllWorkersByPost_PostIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByPost("postId", It.IsAny<bool>()), Throws.TypeOf<ValidationException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllWorkersByPost_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByPost(Guid.NewGuid().ToString(), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkersByPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByPost(Guid.NewGuid().ToString(), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkersByBirthDate_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var listOriginal = new List<WorkerDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
};
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllWorkersByBirthDate(date, date.AddDays(1), true);
var list = _workerBusinessLogicContract.GetAllWorkersByBirthDate(date, date.AddDays(1), 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));
});
_workerStorageContract.Verify(x => x.GetList(true, null, date, date.AddDays(1), null, null), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, null, date, date.AddDays(1), null, null), Times.Once);
}
[Test]
public void GetAllWorkersByBirthDate_ReturnEmptyList_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns([]);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllWorkersByBirthDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), true);
var list = _workerBusinessLogicContract.GetAllWorkers(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));
});
_workerStorageContract.Verify(x => x.GetList(true, null, It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), null, null), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, null, It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), null, null), Times.Once);
}
[Test]
public void GetAllWorkersByBirthDate_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByBirthDate(date, date, It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByBirthDate(date, date.AddSeconds(-1), It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllWorkersByBirthDate_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByBirthDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkersByBirthDate_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByBirthDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkersByEmploymentDate_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var listOriginal = new List<WorkerDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
};
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(date, date.AddDays(1), true);
var list = _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(date, date.AddDays(1), 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));
});
_workerStorageContract.Verify(x => x.GetList(true, null, null, null, date, date.AddDays(1)), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, null, null, null, date, date.AddDays(1)), Times.Once);
}
[Test]
public void GetAllWorkersByEmploymentDate_ReturnEmptyList_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns([]);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), true);
var list = _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), 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));
});
_workerStorageContract.Verify(x => x.GetList(true, null, null, null, It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, null, null, null, It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkersByEmploymentDate_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(date, date, It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(date, date.AddSeconds(-1), It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllWorkersByEmploymentDate_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkersByEmploymentDate_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetWorkerByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new WorkerDataModel(id, "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false);
_workerStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _workerBusinessLogicContract.GetWorkerByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_workerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetWorkerByData_GetByFio_ReturnRecord_Test()
{
//Arrange
var fio = "fio";
var record = new WorkerDataModel(Guid.NewGuid().ToString(), fio, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false);
_workerStorageContract.Setup(x => x.GetElementByFIO(fio)).Returns(record);
//Act
var element = _workerBusinessLogicContract.GetWorkerByData(fio);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.FIO, Is.EqualTo(fio));
_workerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetWorkerByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_workerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetWorkerByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_workerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetWorkerByData_GetByFio_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData("fio"), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_workerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetWorkerByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.GetElementByFIO(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData("fio"), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_workerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertWorker_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new WorkerDataModel(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false);
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>()))
.Callback((WorkerDataModel x) =>
{
flag = x.Id == record.Id && x.FIO == record.FIO && x.PostId == record.PostId && x.BirthDate == record.BirthDate &&
x.EmploymentDate == record.EmploymentDate && x.IsDeleted == record.IsDeleted;
});
//Act
_workerBusinessLogicContract.InsertWorker(record);
//Assert
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertWorker_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementExistsException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Once);
}
[Test]
public void InsertWorker_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.InsertWorker(null), Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Never);
}
[Test]
public void InsertWorker_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new WorkerDataModel("id", "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ValidationException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Never);
}
[Test]
public void InsertWorker_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Once);
}
[Test]
public void UpdateWorker_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new WorkerDataModel(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false);
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>()))
.Callback((WorkerDataModel x) =>
{
flag = x.Id == record.Id && x.FIO == record.FIO && x.PostId == record.PostId && x.BirthDate == record.BirthDate &&
x.EmploymentDate == record.EmploymentDate && x.IsDeleted == record.IsDeleted;
});
//Act
_workerBusinessLogicContract.UpdateWorker(record);
//Assert
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdateWorker_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Once);
}
[Test]
public void UpdateWorker_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(null), Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Never);
}
[Test]
public void UpdateWorker_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new WorkerDataModel("id", "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ValidationException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Never);
}
[Test]
public void UpdateWorker_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Once);
}
[Test]
public void DeleteWorker_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_workerStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_workerBusinessLogicContract.DeleteWorker(id);
//Assert
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void DeleteWorker_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_workerStorageContract.Setup(x => x.DelElement(It.Is((string x) => x != id))).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.DeleteWorker(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeleteWorker_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.DeleteWorker(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _workerBusinessLogicContract.DeleteWorker(string.Empty), Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteWorker_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.DeleteWorker("id"), Throws.TypeOf<ValidationException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteWorker_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.DeleteWorker(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

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