33 Commits

Author SHA1 Message Date
user
9d12ff2500 вроде доделал тесты адаптера 2025-04-20 23:22:17 +04:00
c28acf5bd5 В процессе написания адаптер тестов 2025-04-20 14:54:37 +04:00
user
957d5adc0d вроде finish 2025-04-18 14:40:33 +04:00
user
45687ed29a Merge branch 'Task_3Hard' into Task_4Hard 2025-04-18 04:18:55 +04:00
user
eed08a91b2 В процессе 2025-04-18 04:17:43 +04:00
user
73dee8107d merge task3 hard 2025-04-10 01:23:12 +04:00
a74de025fa Сданный вариант 2025-04-05 10:13:18 +04:00
user
32bc39635c вроде finish 2025-04-05 00:43:28 +04:00
user
5779b9695a вроде finish 2025-04-04 23:26:45 +04:00
user
9a0e2ec59d Вроде финиш 2025-04-03 21:47:45 +04:00
user
4c7ae6bd67 начало 2025-03-30 17:33:47 +04:00
user
bce6d47a99 Merge branch 'Task_2Hard' into Task_3Hard 2025-03-30 17:26:47 +04:00
user
78d614b893 fix 2.0 2025-03-30 17:21:43 +04:00
user
22c101c77c Revert "supply fix"
This reverts commit 4e3fd46750.
2025-03-30 17:11:34 +04:00
user
4e3fd46750 supply fix 2025-03-30 17:09:41 +04:00
user
2cb5ce2793 Revert "supply fix 2.0"
This reverts commit cc7d7289f7.
2025-03-30 16:54:19 +04:00
user
cc7d7289f7 supply fix 2.0 2025-03-30 16:40:30 +04:00
user
015a963762 InsertSupply fix 2025-03-30 16:19:57 +04:00
user
69c63f5499 InsertSupply 2025-03-30 14:28:02 +04:00
user
d9d1a19ee8 Незавершенный вариант 2025-03-22 01:18:27 +04:00
user
94f2c60a08 Наследование ISaleStorage 2025-03-17 02:39:08 +04:00
user
e54574147a Revert "Добавил наследование от ISaleStorage"
This reverts commit 9045e90326.
2025-03-17 02:38:38 +04:00
user
9045e90326 Добавил наследование от ISaleStorage 2025-03-17 02:38:26 +04:00
72d33599fc Сданный вариант 2025-03-12 12:45:28 +04:00
eb3191410a Сданный вариант, Automap 2025-03-12 11:49:17 +04:00
c9753ff960 поменял переменную 2025-03-12 10:59:48 +04:00
ab45eb0546 3 готовая 2025-03-12 08:58:59 +04:00
user
98f99f607f готовая 2 hard 2025-03-12 01:01:36 +04:00
de63a5844a До начала тестов! 2025-03-10 12:22:57 +04:00
03e10326d0 начал делать 2025-03-02 23:27:51 +04:00
679672a33b Merge branch 'Task_1Hard' into Task_2Hard 2025-02-22 10:10:22 +04:00
user
21258b1c31 Вроде все сделанно 2025-02-21 22:47:51 +04:00
9730a641c4 Сделал datamodels 2025-02-21 17:37:05 +04:00
155 changed files with 11490 additions and 178 deletions

View File

@@ -9,7 +9,7 @@ using SquirrelContract.DataModels;
namespace SquirrelBusinessLogic.Implementations;
internal class ClientBusinessLogicContract(IClientStorageContract clientStorageContract, ILogger logger) : IClientBusinessLogicContract
public class ClientBusinessLogicContract(IClientStorageContract clientStorageContract, ILogger logger) : IClientBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IClientStorageContract _clientStorageContract = clientStorageContract;

View File

@@ -9,7 +9,7 @@ using System.Text.RegularExpressions;
namespace SquirrelBusinessLogic.Implementations;
internal class CocktailBusinessLogicContract(ICocktailStorageContract cocktailStorageContract, ILogger logger) : ICocktailBusinessLogicContract
public class CocktailBusinessLogicContract(ICocktailStorageContract cocktailStorageContract, ILogger logger) : ICocktailBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ICocktailStorageContract _cocktailStorageContract = cocktailStorageContract;

View File

@@ -9,7 +9,7 @@ using System.Text.RegularExpressions;
namespace SquirrelBusinessLogic.Implementations;
internal class EmployeeBusinessLogicContract(IEmployeeStorageContract employeeStorageContract, ILogger logger) : IEmployeeBusinessLogicContract
public class EmployeeBusinessLogicContract(IEmployeeStorageContract employeeStorageContract, ILogger logger) : IEmployeeBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IEmployeeStorageContract _employeeStorageContract = employeeStorageContract;

View File

@@ -8,14 +8,14 @@ using System.Text.Json;
namespace SquirrelBusinessLogic.Implementations;
internal class PostBusinessLogicContract(IPostStorageContract postStorageContract, ILogger logger) : IPostBusinessLogicContract
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)
public List<PostDataModel> GetAllPosts()
{
_logger.LogInformation("GetAllPosts params: {onlyActive}", onlyActive);
return _postStorageContract.GetList(onlyActive) ?? throw new NullListException();
_logger.LogInformation("GetAllPosts");
return _postStorageContract.GetList() ?? throw new NullListException();
}
public List<PostDataModel> GetAllDataOfPost(string postId)

View File

@@ -7,7 +7,7 @@ using SquirrelContract.StoragesContracts;
namespace SquirrelBusinessLogic.Implementations;
internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract,
public class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract,
ISaleStorageContract saleStorageContract, IPostStorageContract postStorageContract, IEmployeeStorageContract employeeStorageContract, ILogger logger) : ISalaryBusinessLogicContract
{
private readonly ILogger _logger = logger;
@@ -57,7 +57,7 @@ internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageC
throw new NullListException();
var salary = post.Salary + sales * 0.1;
_logger.LogDebug("The employee {employeeId} was paid a salary of {salary}", employee.Id, salary);
_salaryStorageContract.AddElement(new SalaryDataModel(employee.Id, finishDate, salary));
_salaryStorageContract.AddElement(new SalaryDataModel(employee.Id, DateTime.SpecifyKind(finishDate, DateTimeKind.Utc), salary));
}
}
}

View File

@@ -8,11 +8,11 @@ using System.Text.Json;
namespace SquirrelBusinessLogic.Implementations;
internal class SaleBusinessLogicContract(ISaleStorageContract
saleStorageContract, ILogger logger) : ISaleBusinessLogicContract
public class SaleBusinessLogicContract(ISaleStorageContract saleStorageContract, IWarehouseStorageContract warehouseStorageContract, ILogger logger) : ISaleBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
private readonly IWarehouseStorageContract _warehouseStorageContract = warehouseStorageContract;
public List<SaleDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate)
{
@@ -97,6 +97,10 @@ saleStorageContract, ILogger logger) : ISaleBusinessLogicContract
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(saleDataModel));
ArgumentNullException.ThrowIfNull(saleDataModel);
saleDataModel.Validate();
if (!_warehouseStorageContract.CheckCocktails(saleDataModel))
{
throw new InsufficientStockException("Dont have cocktails in warehouse");
}
_saleStorageContract.AddElement(saleDataModel);
}

View File

@@ -0,0 +1,103 @@
using Microsoft.Extensions.Logging;
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.StoragesContracts;
using System.Text.Json;
namespace SquirrelBusinessLogic.Implementations;
public class SupplyBusinessLogicContract(ISupplyStorageContract supplyStorageContract, IWarehouseStorageContract warehouseStorageContract, ILogger logger) : ISupplyBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISupplyStorageContract _supplyStorageContract = supplyStorageContract;
private readonly IWarehouseStorageContract _warehouseStorageContract = warehouseStorageContract;
public List<SupplyDataModel> GetAllSuppliesByPeriod(DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSupplies params: {fromDate}, {toDate}", fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _supplyStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
}
public List<SupplyDataModel> GetAllSuppliesByCocktailByPeriod(string cocktailId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSupplies params: {cocktailId}, {fromDate}, {toDate}", cocktailId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (cocktailId.IsEmpty())
{
throw new ArgumentNullException(nameof(cocktailId));
}
if (!cocktailId.IsGuid())
{
throw new ValidationException("The value in the field cocktailId is not a unique identifier.");
}
return _supplyStorageContract.GetList(fromDate, toDate, cocktailId: cocktailId) ?? throw new NullListException();
}
public SupplyDataModel GetSupplyByData(string data)
{
_logger.LogInformation("Get supply by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (!data.IsGuid())
{
throw new ElementNotFoundException(data);
}
return _supplyStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
public void ProcessSupply(SupplyDataModel supplyDataModel)
{
_logger.LogInformation("Processing supply: {json}", JsonSerializer.Serialize(supplyDataModel));
ArgumentNullException.ThrowIfNull(supplyDataModel);
supplyDataModel.Validate();
foreach (var supplyCocktail in supplyDataModel.Cocktails)
{
var warehouses = _warehouseStorageContract.GetList();
var targetWarehouse = warehouses.FirstOrDefault(w =>
w.Cocktails.Any(c => c.CocktailId == supplyCocktail.CocktailId));
if (targetWarehouse == null)
{
targetWarehouse = warehouses.FirstOrDefault();
if (targetWarehouse == null)
{
throw new ElementNotFoundException("No warehouse found for supply.");
}
}
_warehouseStorageContract.UpdWarehouseOnSupply(targetWarehouse.Id, supplyCocktail.CocktailId, supplyCocktail.Count);
}
}
public void InsertSupply(SupplyDataModel supplyDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(supplyDataModel));
ArgumentNullException.ThrowIfNull(supplyDataModel);
supplyDataModel.Validate();
_supplyStorageContract.AddElement(supplyDataModel);
ProcessSupply(supplyDataModel);
}
public void UpdateSupply(SupplyDataModel supplyDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(supplyDataModel));
ArgumentNullException.ThrowIfNull(supplyDataModel);
supplyDataModel.Validate();
_supplyStorageContract.UpdateElement(supplyDataModel);
ProcessSupply(supplyDataModel);
}
}

View File

@@ -0,0 +1,65 @@
using Microsoft.Extensions.Logging;
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.StoragesContracts;
using System.Text.Json;
namespace SquirrelBusinessLogic.Implementations;
public class WarehouseBusinessLogicContract(IWarehouseStorageContract warehouseStorageContract, ILogger logger) : IWarehouseBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IWarehouseStorageContract _warehouseStorageContract = warehouseStorageContract;
public List<WarehouseDataModel> GetAllWarehouses()
{
_logger.LogInformation("GetAllWarehouses");
return _warehouseStorageContract.GetList() ?? throw new NullListException();
}
public WarehouseDataModel GetWarehouseByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _warehouseStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
return _warehouseStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data);
}
public void InsertWarehouse(WarehouseDataModel warehouseDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(warehouseDataModel));
ArgumentNullException.ThrowIfNull(warehouseDataModel);
warehouseDataModel.Validate();
_warehouseStorageContract.AddElement(warehouseDataModel);
}
public void UpdateWarehouse(WarehouseDataModel warehouseDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(warehouseDataModel));
ArgumentNullException.ThrowIfNull(warehouseDataModel);
warehouseDataModel.Validate();
_warehouseStorageContract.UpdElement(warehouseDataModel);
}
public void DeleteWarehouse(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");
}
_warehouseStorageContract.DelElement(id);
}
}

View File

@@ -9,6 +9,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SquirrelTests", "SquirrelTe
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SquirrelBusinessLogic", "SquirrelBusinessLogic\SquirrelBusinessLogic.csproj", "{C03D0604-CD06-42DA-99CB-23B8306C3714}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SquirrelDatabase", "SquirrelDatabase\SquirrelDatabase.csproj", "{A8A7A434-A278-4362-8D34-C2E3CAA938C1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SquirrelWebApi", "SquirrelWebApi\SquirrelWebApi.csproj", "{45D1F24F-AFCD-4259-88C2-3076E38254A9}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -27,8 +31,19 @@ Global
{C03D0604-CD06-42DA-99CB-23B8306C3714}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C03D0604-CD06-42DA-99CB-23B8306C3714}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C03D0604-CD06-42DA-99CB-23B8306C3714}.Release|Any CPU.Build.0 = Release|Any CPU
{A8A7A434-A278-4362-8D34-C2E3CAA938C1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A8A7A434-A278-4362-8D34-C2E3CAA938C1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A8A7A434-A278-4362-8D34-C2E3CAA938C1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A8A7A434-A278-4362-8D34-C2E3CAA938C1}.Release|Any CPU.Build.0 = Release|Any CPU
{45D1F24F-AFCD-4259-88C2-3076E38254A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{45D1F24F-AFCD-4259-88C2-3076E38254A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{45D1F24F-AFCD-4259-88C2-3076E38254A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{45D1F24F-AFCD-4259-88C2-3076E38254A9}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {E3B65E92-8603-4ED7-8214-9DA9A305DAFF}
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,16 @@
namespace SquirrelContract.AdapterContracts;
using SquirrelContract.AdapterContracts.OperationResponses;
using SquirrelContract.BindingModels;
public interface IClientAdapter
{
ClientOperationResponse GetList();
ClientOperationResponse GetElement(string data);
ClientOperationResponse RegisterClient(ClientBindingModel clientModel);
ClientOperationResponse ChangeClientInfo(ClientBindingModel clientModel);
ClientOperationResponse RemoveClient(string id);
}

View File

@@ -0,0 +1,19 @@
using SquirrelContract.BindingModels;
using SquirrelContract.AdapterContracts.OperationResponses;
namespace SquirrelContract.AdapterContracts;
public interface ICocktailAdapter
{
CocktailOperationResponse GetList(bool includeDeleted);
CocktailOperationResponse GetHistory(string id);
CocktailOperationResponse GetElement(string data);
CocktailOperationResponse RegisterCocktail(CocktailBindingModel cocktailModel);
CocktailOperationResponse ChangeCocktailInfo(CocktailBindingModel cocktailModel);
CocktailOperationResponse RemoveCocktail(string id);
}

View File

@@ -0,0 +1,23 @@
using SquirrelContract.AdapterContracts.OperationResponses;
using SquirrelContract.BindingModels;
namespace SquirrelContract.AdapterContracts;
public interface IEmployeeAdapter
{
EmployeeOperationResponse GetList(bool includeDeleted);
EmployeeOperationResponse GetPostList(string id, bool includeDeleted);
EmployeeOperationResponse GetListByBirthDate(DateTime fromDate, DateTime toDate, bool includeDeleted);
EmployeeOperationResponse GetListByEmploymentDate(DateTime fromDate, DateTime toDate, bool includeDeleted);
EmployeeOperationResponse GetElement(string data);
EmployeeOperationResponse RegisterEmployee(EmployeeBindingModel employeeModel);
EmployeeOperationResponse ChangeEmployeeInfo(EmployeeBindingModel employeeModel);
EmployeeOperationResponse RemoveEmployee(string id);
}

View File

@@ -0,0 +1,21 @@
using SquirrelContract.AdapterContracts.OperationResponses;
using SquirrelContract.BindingModels;
namespace SquirrelContract.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,10 @@
using SquirrelContract.AdapterContracts.OperationResponses;
namespace SquirrelContract.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,21 @@
using SquirrelContract.AdapterContracts.OperationResponses;
using SquirrelContract.BindingModels;
namespace SquirrelContract.AdapterContracts;
public interface ISaleAdapter
{
SaleOperationResponse GetList(DateTime fromDate, DateTime toDate);
SaleOperationResponse GetEmployeeList(string id, DateTime fromDate, DateTime toDate);
SaleOperationResponse GetClientList(string id, DateTime fromDate, DateTime toDate);
SaleOperationResponse GetCocktailList(string id, DateTime fromDate, DateTime toDate);
SaleOperationResponse GetElement(string id);
SaleOperationResponse MakeSale(SaleBindingModel saleModel);
SaleOperationResponse CancelSale(string id);
}

View File

@@ -0,0 +1,15 @@
using SquirrelContract.BindingModels;
using SquirrelContract.AdapterContracts.OperationResponses;
using SquirrelContract.DataModels;
namespace SquirrelContract.AdapterContracts;
public interface ISupplyAdapter
{
SupplyOperationResponse GetAllSuppliesByPeriod(DateTime fromDate, DateTime toDate);
SupplyOperationResponse GetCocktailList(string id, DateTime fromDate, DateTime toDate);
SupplyOperationResponse GetSupplyByData(string data);
SupplyOperationResponse InsertSupply(SupplyBindingModel supplyDataModel);
SupplyOperationResponse UpdateSupply(SupplyBindingModel supplyDataModel);
}

View File

@@ -0,0 +1,13 @@
using SquirrelContract.AdapterContracts.OperationResponses;
using SquirrelContract.BindingModels;
namespace SquirrelContract.AdapterContracts;
public interface IWarehouseAdapter
{
WarehouseOperationResponse GetAllWarehouses();
WarehouseOperationResponse GetWarehouseByData(string data);
WarehouseOperationResponse InsertWarehouse(WarehouseBindingModel warehouseDataModel);
WarehouseOperationResponse UpdateWarehouse(WarehouseBindingModel warehouseDataModel);
WarehouseOperationResponse DeleteWarehouse(string id);
}

View File

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

View File

@@ -0,0 +1,21 @@
using SquirrelContract.ViewModels;
using SquirrelContract.Infrastructure;
namespace SquirrelContract.AdapterContracts.OperationResponses;
public class CocktailOperationResponse : OperationResponse
{
public static CocktailOperationResponse OK(List<CocktailViewModel> data) => OK<CocktailOperationResponse, List<CocktailViewModel>>(data);
public static CocktailOperationResponse OK(List<CocktailHistoryViewModel> data) => OK<CocktailOperationResponse, List<CocktailHistoryViewModel>>(data);
public static CocktailOperationResponse OK(CocktailViewModel data) => OK<CocktailOperationResponse, CocktailViewModel>(data);
public static CocktailOperationResponse NoContent() => NoContent<CocktailOperationResponse>();
public static CocktailOperationResponse NotFound(string message) => NotFound<CocktailOperationResponse>(message);
public static CocktailOperationResponse BadRequest(string message) => BadRequest<CocktailOperationResponse>(message);
public static CocktailOperationResponse InternalServerError(string message) => InternalServerError<CocktailOperationResponse>(message);
}

View File

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

View File

@@ -0,0 +1,19 @@
using SquirrelContract.Infrastructure;
using SquirrelContract.ViewModels;
namespace SquirrelContract.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,13 @@
using SquirrelContract.Infrastructure;
using SquirrelContract.ViewModels;
namespace SquirrelContract.AdapterContracts.OperationResponses;
public class SalaryOperationResponse : OperationResponse
{
public static SalaryOperationResponse OK(List<SalaryViewModel> data) => OK<SalaryOperationResponse, List<SalaryViewModel>>(data);
public static SalaryOperationResponse NoContent() => NoContent<SalaryOperationResponse>();
public static SalaryOperationResponse NotFound(string message) => NotFound<SalaryOperationResponse>(message);
public static SalaryOperationResponse BadRequest(string message) => BadRequest<SalaryOperationResponse>(message);
public static SalaryOperationResponse InternalServerError(string message) => InternalServerError<SalaryOperationResponse>(message);
}

View File

@@ -0,0 +1,19 @@
using SquirrelContract.ViewModels;
using SquirrelContract.Infrastructure;
namespace SquirrelContract.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,19 @@
using SquirrelContract.Infrastructure;
using SquirrelContract.ViewModels;
namespace SquirrelContract.AdapterContracts.OperationResponses;
public class SupplyOperationResponse : OperationResponse
{
public static SupplyOperationResponse OK(List<SupplyViewModel> data) => OK<SupplyOperationResponse, List<SupplyViewModel>>(data);
public static SupplyOperationResponse OK(SupplyViewModel data) => OK<SupplyOperationResponse, SupplyViewModel>(data);
public static SupplyOperationResponse NoContent() => NoContent<SupplyOperationResponse>();
public static SupplyOperationResponse NotFound(string message) => NotFound<SupplyOperationResponse>(message);
public static SupplyOperationResponse BadRequest(string message) => BadRequest<SupplyOperationResponse>(message);
public static SupplyOperationResponse InternalServerError(string message) => InternalServerError<SupplyOperationResponse>(message);
}

View File

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

View File

@@ -0,0 +1,12 @@
namespace SquirrelContract.BindingModels;
public class ClientBindingModel
{
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,9 @@
namespace SquirrelContract.BindingModels;
public class CocktailBindingModel
{
public string? Id { get; set; }
public string? CocktailName { get; set; }
public double Price { get; set; }
public string? BaseAlcohol { get; set; }
}

View File

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

View File

@@ -0,0 +1,14 @@
namespace SquirrelContract.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,14 @@
namespace SquirrelContract.BindingModels;
public class SaleBindingModel
{
public string? Id { get; set; }
public string? EmployeeId { get; set; }
public string? ClientId { get; set; }
public int DiscountType { get; set; }
public List<SaleCocktailBindingModel>? Cocktails { get; set; }
}

View File

@@ -0,0 +1,12 @@
namespace SquirrelContract.BindingModels;
public class SaleCocktailBindingModel
{
public string? SaleId { get; set; }
public string? CocktailId { get; set; }
public int Count { get; set; }
public double Price { get; set; }
}

View File

@@ -0,0 +1,9 @@
namespace SquirrelContract.BindingModels;
public class SupplyBindingModel
{
public string? Id { get; set; }
public DateTime SupplyDate { get; set; }
public int Count { get; set; }
public List<SupplyCocktailBindingModel>? Cocktails { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace SquirrelContract.BindingModels;
public class SupplyCocktailBindingModel
{
public string? SupplyId { get; set; }
public string? CocktailId { get; set; }
public int Count { get; set; }
}

View File

@@ -0,0 +1,9 @@
namespace SquirrelContract.BindingModels;
public class WarehouseBindingModel
{
public string? Id { get; set; }
public string? Name { get; set; }
public int Count { get; set; }
public List<WarehouseCocktailBindingModel>? Cocktails { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace SquirrelContract.BindingModels;
public class WarehouseCocktailBindingModel
{
public string? WarehouseId { get; set; }
public string? CocktailId { get; set; }
public int Count { get; set; }
}

View File

@@ -4,7 +4,7 @@ namespace SquirrelContract.BusinessLogicContracts;
public interface IPostBusinessLogicContract
{
List<PostDataModel> GetAllPosts(bool onlyActive);
List<PostDataModel> GetAllPosts();
List<PostDataModel> GetAllDataOfPost(string postId);

View File

@@ -0,0 +1,17 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.BusinessLogicContracts;
public interface ISupplyBusinessLogicContract
{
List<SupplyDataModel> GetAllSuppliesByPeriod(DateTime fromDate, DateTime toDate);
List<SupplyDataModel> GetAllSuppliesByCocktailByPeriod(string cocktailId, DateTime fromDate, DateTime toDate);
SupplyDataModel GetSupplyByData(string data);
void InsertSupply(SupplyDataModel supplyDataModel);
void UpdateSupply(SupplyDataModel supplyDataModel);
}

View File

@@ -0,0 +1,16 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.BusinessLogicContracts;
public interface IWarehouseBusinessLogicContract
{
List<WarehouseDataModel> GetAllWarehouses();
WarehouseDataModel GetWarehouseByData(string data);
void InsertWarehouse(WarehouseDataModel cocktailDataModel);
void UpdateWarehouse(WarehouseDataModel cocktailDataModel);
void DeleteWarehouse(string id);
}

View File

@@ -6,12 +6,22 @@ namespace SquirrelContract.DataModels;
public class CocktailHistoryDataModel(string cocktailId, double oldPrice) : IValidation
{
private readonly CocktailDataModel? _cocktail;
public string CocktailId { get; private set; } = cocktailId;
public double OldPrice { get; private set; } = oldPrice;
public DateTime ChangeDate { get; private set; } = DateTime.UtcNow;
public string CocktailName => _cocktail?.CocktailName ?? string.Empty;
public CocktailHistoryDataModel(string cocktailId, double oldPrice, DateTime changeDate, CocktailDataModel cocktail) : this(cocktailId, oldPrice)
{
ChangeDate = changeDate;
_cocktail = cocktail;
}
public void Validate()
{
if (CocktailId.IsEmpty())

View File

@@ -7,6 +7,8 @@ namespace SquirrelContract.DataModels;
public class EmployeeDataModel(string id, string fio, string email, 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;
@@ -21,6 +23,15 @@ public class EmployeeDataModel(string id, string fio, string email, string postI
public bool IsDeleted { get; private set; } = isDeleted;
public string PostName => _post?.PostName ?? string.Empty;
public EmployeeDataModel(string id, string fio, string email, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted, PostDataModel post) : this(id, fio, email, postId, birthDate, employmentDate, isDeleted)
{
_post = post;
}
public EmployeeDataModel(string id, string fio, string email, string postId, DateTime birthDate, DateTime employmentDate) : this(id, fio, email, postId, birthDate, employmentDate, false) { }
public void Validate()
{
if (Id.IsEmpty())

View File

@@ -5,9 +5,9 @@ using SquirrelContract.Infastructure;
namespace SquirrelContract.DataModels;
public class PostDataModel(string id, string postName, PostType postType, double salary, bool isActual, DateTime changeDate) : IValidation
public class PostDataModel(string postId, string postName, PostType postType, double salary) : IValidation
{
public string Id { get; private set; } = id;
public string Id { get; private set; } = postId;
public string PostName { get; private set; } = postName;
@@ -15,10 +15,6 @@ public class PostDataModel(string id, string postName, PostType postType, double
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())

View File

@@ -1,4 +1,5 @@
using SquirrelContract.Exceptions;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
@@ -6,12 +7,21 @@ namespace BarBelochkaContract.DataModels;
public class SalaryDataModel(string employeeId, DateTime salaryDate, double employeeSalary) : IValidation
{
private readonly EmployeeDataModel? _employee;
public string EmployeeId { get; private set; } = employeeId;
public DateTime SalaryDate { get; private set; } = salaryDate;
public double Salary { get; private set; } = employeeSalary;
public string EmployeeFIO => _employee?.FIO ?? string.Empty;
public SalaryDataModel(string employeeId, DateTime salaryDate, double employeeSalary, EmployeeDataModel employee) : this(employeeId, salaryDate, employeeSalary)
{
_employee = employee;
}
public void Validate()
{
if (EmployeeId.IsEmpty())

View File

@@ -4,14 +4,25 @@ using SquirrelContract.Infastructure;
namespace SquirrelContract.DataModels;
public class SaleCocktailDataModel(string saleId, string cocktailId, int count) : IValidation
public class SaleCocktailDataModel(string saleId, string cocktailId, int count, double price) : IValidation
{
private readonly CocktailDataModel? _cocktail;
public string SaleId { get; private set; } = saleId;
public string CocktailId { get; private set; } = cocktailId;
public int Count { get; private set; } = count;
public double Price { get; private set; } = price;
public string CocktailName => _cocktail?.CocktailName ?? string.Empty;
public SaleCocktailDataModel(string saleId, string cocktailId, int count, double price, CocktailDataModel cocktail) : this(saleId, cocktailId, count, price)
{
_cocktail = cocktail;
}
public void Validate()
{
if (SaleId.IsEmpty())
@@ -21,12 +32,15 @@ public class SaleCocktailDataModel(string saleId, string cocktailId, int count)
throw new ValidationException("The value in the field SaleId is not a unique identifier");
if (CocktailId.IsEmpty())
throw new ValidationException("Field ProductId is empty");
throw new ValidationException("Field CocktailId is empty");
if (!CocktailId.IsGuid())
throw new ValidationException("The value in the field ProductId is not a unique identifier");
throw new ValidationException("The value in the field CocktailId is not a unique identifier");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
if (Price <= 0)
throw new ValidationException("Field Price is less than or equal to 0");
}
}

View File

@@ -5,25 +5,76 @@ using SquirrelContract.Infastructure;
namespace SquirrelContract.DataModels;
public class SaleDataModel(string id, string employeeId, string? clientId, double sum, DiscountType discountType, double discount, bool isCancel, List<SaleCocktailDataModel> cocktails) : IValidation
public class SaleDataModel : IValidation
{
public string Id { get; private set; } = id;
private readonly ClientDataModel? _client;
public string EmployeeId { get; private set; } = employeeId;
private readonly EmployeeDataModel? _employee;
public string? ClientId { get; private set; } = clientId;
public string Id { get; private set; }
public string EmployeeId { get; private set; }
public string? ClientId { get; private set; }
public DateTime SaleDate { get; private set; } = DateTime.UtcNow;
public double Sum { get; private set; } = sum;
public double Sum { get; private set; }
public DiscountType DiscountType { get; private set; } = discountType;
public DiscountType DiscountType { get; private set; }
public double Discount { get; private set; } = discount;
public double Discount { get; private set; }
public bool IsCancel { get; private set; } = isCancel;
public bool IsCancel { get; private set; }
public List<SaleCocktailDataModel> Cocktails { get; private set; } = cocktails;
public List<SaleCocktailDataModel>? Cocktails { get; private set; }
public string ClientFIO => _client?.FIO ?? string.Empty;
public string EmployeeFIO => _employee?.FIO ?? string.Empty;
public SaleDataModel(string id, string employeeId, string? clientId, DiscountType discountType, bool isCancel, List<SaleCocktailDataModel> saleCocktails)
{
Id = id;
EmployeeId = employeeId;
ClientId = clientId;
DiscountType = discountType;
IsCancel = isCancel;
Cocktails = saleCocktails;
var percent = 0.0;
foreach (DiscountType elem in Enum.GetValues<DiscountType>())
{
if ((elem & discountType) != 0)
{
switch (elem)
{
case DiscountType.None:
break;
case DiscountType.OnSale:
percent += 0.1;
break;
case DiscountType.RegularCustomer:
percent += 0.5;
break;
case DiscountType.Certificate:
percent += 0.3;
break;
}
}
}
Sum = Cocktails?.Sum(x => x.Price * x.Count) ?? 0;
Discount = Sum * percent;
}
public SaleDataModel(string id, string employeeId, string? clientId, double sum, DiscountType discountType, double discount, bool isCancel, List<SaleCocktailDataModel> saleCocktails, EmployeeDataModel employee, ClientDataModel? client) : this(id, employeeId, clientId, discountType, isCancel, saleCocktails)
{
Sum = sum;
Discount = discount;
_employee = employee;
_client = client;
}
public SaleDataModel(string id, string employeeId, string? clientId, int discountType, List<SaleCocktailDataModel> cocktails) : this(id, employeeId, clientId, (DiscountType)discountType, false, cocktails) { }
public void Validate()
{
@@ -40,7 +91,7 @@ public class SaleDataModel(string id, string employeeId, string? clientId, doubl
throw new ValidationException("The value in the field EmployeeId is not a unique identifier");
if (!ClientId?.IsGuid() ?? !ClientId?.IsEmpty() ?? false)
throw new ValidationException("The value in the field BuyerId is not a unique identifier");
throw new ValidationException("The value in the field ClientId is not a unique identifier");
if (Sum <= 0)
throw new ValidationException("Field Sum is less than or equal to 0");

View File

@@ -0,0 +1,33 @@
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
using System.ComponentModel;
namespace SquirrelContract.DataModels;
public class SupplyCocktailDataModel(string? supplyId, string? cocktailId, int count) : IValidation
{
public string SupplyId { get; private set; } = supplyId;
public string CocktailId { get; private set; } = cocktailId;
public int Count { get; private set; } = count;
public void Validate()
{
if (SupplyId.IsEmpty())
throw new ValidationException("Field SupplyId is empty");
if (!SupplyId.IsGuid())
throw new ValidationException("The value in the field SupplyId is not a unique identifier");
if (CocktailId.IsEmpty())
throw new ValidationException("Field CocktailId is empty");
if (!CocktailId.IsGuid())
throw new ValidationException("The value in the field CocktailId 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,29 @@
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
namespace SquirrelContract.DataModels;
public class SupplyDataModel(string id, DateTime supplyDate, List<SupplyCocktailDataModel> cocktails) : IValidation
{
public string Id { get; private set; } = id;
public DateTime SupplyDate { get; private set; } = supplyDate;
public List<SupplyCocktailDataModel> Cocktails { get; private set; } = cocktails;
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 (SupplyDate.Date > DateTime.Now)
throw new ValidationException($"It is impossible to supply things in the future");
if ((Cocktails?.Count ?? 0) == 0)
throw new ValidationException("The components must include products");
}
}

View File

@@ -0,0 +1,32 @@
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
namespace SquirrelContract.DataModels;
public class WarehouseCocktailDataModel(string? warehouseId, string? cocktailId, int count) : IValidation
{
public string WarehouseId { get; private set; } = warehouseId;
public string CocktailId { get; private set; } = cocktailId;
public int Count { get; private set; } = count;
public void Validate()
{
if (WarehouseId.IsEmpty())
throw new ValidationException("Field WarehouseId is empty");
if (!WarehouseId.IsGuid())
throw new ValidationException("The value in the field WarehouseId is not a unique identifier");
if (CocktailId.IsEmpty())
throw new ValidationException("Field CocktailId is empty");
if (!CocktailId.IsGuid())
throw new ValidationException("The value in the field CocktailId 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,30 @@
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
using System.Xml.Linq;
namespace SquirrelContract.DataModels;
public class WarehouseDataModel(string? id, string name, List<WarehouseCocktailDataModel> cocktails) : IValidation
{
public string Id { get; private set; } = id;
public string Name { get; private set; } = name;
public List<WarehouseCocktailDataModel> Cocktails { get; private set; } = cocktails;
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 ((Cocktails?.Count ?? 0) == 0)
throw new ValidationException("The cocktails must include drinks");
}
}

View File

@@ -0,0 +1,6 @@
namespace SquirrelContract.Exceptions;
public class ElementDeletedException : Exception
{
public ElementDeletedException(string id) : base($"Cannot modify a deleted item (id: {id})") { }
}

View File

@@ -0,0 +1,5 @@
namespace SquirrelContract.Exceptions;
public class InsufficientStockException(string message) : Exception(message)
{
}

View File

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

View File

@@ -0,0 +1,37 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net;
namespace SquirrelContract.Infrastructure;
public class OperationResponse
{
public HttpStatusCode StatusCode { get; set; }
public 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

@@ -6,4 +6,9 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.3.0" />
</ItemGroup>
</Project>

View File

@@ -4,7 +4,7 @@ namespace SquirrelContract.StoragesContracts;
public interface IPostStorageContract
{
List<PostDataModel> GetList(bool onlyActual = true);
List<PostDataModel> GetList();
List<PostDataModel> GetPostWithHistory(string postId);
PostDataModel? GetElementById(string id);
PostDataModel? GetElementByName(string name);

View File

@@ -4,7 +4,7 @@ namespace SquirrelContract.StoragesContracts;
public interface ISalaryStorageContract
{
List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? employeeId = null);
List<SalaryDataModel> GetList(DateTime? startDate, DateTime? endDate, string? employeeId = null);
void AddElement(SalaryDataModel salaryDataModel);
}

View File

@@ -0,0 +1,11 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.StoragesContracts;
public interface ISupplyStorageContract
{
List<SupplyDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? cocktailId = null);
SupplyDataModel? GetElementById(string id);
void AddElement(SupplyDataModel warehouseDataModel);
void UpdateElement(SupplyDataModel warehouseDataModel);
}

View File

@@ -0,0 +1,15 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.StoragesContracts;
public interface IWarehouseStorageContract
{
List<WarehouseDataModel> GetList();
WarehouseDataModel? GetElementByName(string name);
WarehouseDataModel? GetElementById(string id);
void AddElement(WarehouseDataModel warehouseDataModel);
void UpdElement(WarehouseDataModel warehouseDataModel);
void UpdWarehouseOnSupply(string warehouseId, string cocktailId, int count);
void DelElement(string id);
bool CheckCocktails(SaleDataModel saleDataModel);
}

View File

@@ -0,0 +1,12 @@
namespace SquirrelContract.ViewModels;
public class ClientViewModel
{
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,10 @@
namespace SquirrelContract.ViewModels;
public class CocktailHistoryViewModel
{
public required string CocktailName { get; set; }
public double OldPrice { get; set; }
public DateTime ChangeDate { get; set; }
}

View File

@@ -0,0 +1,13 @@
namespace SquirrelContract.ViewModels;
public class CocktailViewModel
{
public required string Id { get; set; }
public required string CocktailName { get; set; }
public required string BaseAlcohol { get; set; }
public double Price { get; set; }
}

View File

@@ -0,0 +1,20 @@
namespace SquirrelContract.ViewModels;
public class EmployeeViewModel
{
public required string Id { get; set; }
public required string FIO { get; set; }
public string Email { 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

@@ -0,0 +1,12 @@
namespace SquirrelContract.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,9 @@
namespace SquirrelContract.ViewModels;
public class SalaryViewModel
{
public required string EmployeeId { get; set; }
public required string EmployeeFIO { get; set; }
public DateTime SalaryDate { get; set; }
public double Salary { get; set; }
}

View File

@@ -0,0 +1,12 @@
namespace SquirrelContract.ViewModels;
public class SaleCocktailViewModel
{
public required string CocktailId { get; set; }
public required string CocktailName { get; set; }
public int Count { get; set; }
public double Price { get; set; }
}

View File

@@ -0,0 +1,26 @@
namespace SquirrelContract.ViewModels;
public class SaleViewModel
{
public required string Id { get; set; }
public required string EmployeeId { get; set; }
public required string EmployeeFIO { get; set; }
public string? ClientId { get; set; }
public string? ClientFIO { get; set; }
public DateTime SaleDate { get; set; }
public double Sum { get; set; }
public required string DiscountType { get; set; }
public double Discount { get; set; }
public bool IsCancel { get; set; }
public required List<SaleCocktailViewModel> Cocktails { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace SquirrelContract.ViewModels;
public class SupplyCocktailViewModel
{
public required string SupplyId { get; set; }
public required string CocktailId { get; set; }
public int Count { get; set; }
}

View File

@@ -0,0 +1,9 @@
namespace SquirrelContract.ViewModels;
public class SupplyViewModel
{
public required string Id { get; set; }
public DateTime SupplyDate { get; set; }
public int Count { get; set; }
public required List<SupplyCocktailViewModel> Cocktails { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace SquirrelContract.ViewModels;
public class WarehouseCocktailViewModel
{
public required string WarehouseId { get; set; }
public required string CocktailId { get; set; }
public int Count { get; set; }
}

View File

@@ -0,0 +1,9 @@
namespace SquirrelContract.ViewModels;
public class WarehouseViewModel
{
public required string Id { get; set; }
public required string Name { get; set; }
public required int Count { get; set; }
public required List<WarehouseCocktailViewModel> Cocktails { get; set; }
}

View File

@@ -0,0 +1,149 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
using System;
namespace SquirrelDatabase.Implementations;
public class ClientStorageContract : IClientStorageContract
{
private readonly SquirrelDbContext _dbContext;
private readonly Mapper _mapper;
public ClientStorageContract(SquirrelDbContext squirrelDbContext)
{
_dbContext = squirrelDbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(SquirrelDbContext).Assembly);
});
_mapper = new Mapper(config);
}
public List<ClientDataModel> GetList()
{
try
{
return [.. _dbContext.Clients.Select(x => _mapper.Map<ClientDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ClientDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<ClientDataModel>(GetClientById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ClientDataModel? GetElementByFIO(string fio)
{
try
{
return _mapper.Map<ClientDataModel>(_dbContext.Clients.FirstOrDefault(x => x.FIO == fio));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ClientDataModel? GetElementByPhoneNumber(string phoneNumber)
{
try
{
return _mapper.Map<ClientDataModel>(_dbContext.Clients.FirstOrDefault(x => x.PhoneNumber == phoneNumber));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(ClientDataModel clientDataModel)
{
try
{
_dbContext.Clients.Add(_mapper.Map<Client>(clientDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", clientDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Clients_PhoneNumber" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PhoneNumber", clientDataModel.PhoneNumber);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(ClientDataModel clientDataModel)
{
try
{
var element = GetClientById(clientDataModel.Id) ?? throw new ElementNotFoundException(clientDataModel.Id);
_dbContext.Clients.Update(_mapper.Map(clientDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Clients_PhoneNumber" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PhoneNumber", clientDataModel.PhoneNumber);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetClientById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Clients.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Client? GetClientById(string id) => _dbContext.Clients.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,179 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
namespace SquirrelDatabase.Implementations;
public class CocktailStorageContract : ICocktailStorageContract
{
private readonly SquirrelDbContext _dbContext;
private readonly Mapper _mapper;
public CocktailStorageContract(SquirrelDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Cocktail, CocktailDataModel>();
cfg.CreateMap<CocktailDataModel, Cocktail>();
cfg.CreateMap<CocktailHistory, CocktailHistoryDataModel>();
});
_mapper = new Mapper(config);
}
public List<CocktailDataModel> GetList()
{
try
{
return [.. _dbContext.Cocktails.Select(x => _mapper.Map<CocktailDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public List<CocktailHistoryDataModel> GetHistoryByCocktailId(string cocktailId)
{
try
{
return [.. _dbContext.CocktailHistories.Include(x => x.Cocktail).Where(x => x.CocktailId == cocktailId).OrderByDescending(x => x.ChangeDate).Select(x => _mapper.Map<CocktailHistoryDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public CocktailDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<CocktailDataModel>(GetCocktailById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public CocktailDataModel? GetElementByName(string name)
{
try
{
return _mapper.Map<CocktailDataModel>(_dbContext.Cocktails.FirstOrDefault(x => x.CocktailName == name));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(CocktailDataModel cocktailDataModel)
{
try
{
_dbContext.Cocktails.Add(_mapper.Map<Cocktail>(cocktailDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", cocktailDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Cocktails_CocktailName" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("CocktailName", cocktailDataModel.CocktailName);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(CocktailDataModel cocktailDataModel)
{
try
{
var transaction = _dbContext.Database.BeginTransaction();
try
{
var element = GetCocktailById(cocktailDataModel.Id) ?? throw new ElementNotFoundException(cocktailDataModel.Id);
if (element.Price != cocktailDataModel.Price)
{
_dbContext.CocktailHistories.Add(new CocktailHistory() { CocktailId = element.Id, OldPrice = element.Price });
_dbContext.SaveChanges();
}
_dbContext.Cocktails.Update(_mapper.Map(cocktailDataModel, element));
_dbContext.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Cocktails_CocktailName" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("CocktailName", cocktailDataModel.CocktailName);
}
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 = GetCocktailById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Cocktails.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void ResElement(string id)
{
try
{
var element = GetCocktailById(id) ?? throw new ElementNotFoundException(id);
_dbContext.SaveChanges();
}
catch
{
_dbContext.ChangeTracker.Clear();
throw;
}
}
private Cocktail? GetCocktailById(string id) => _dbContext.Cocktails.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,163 @@
using AutoMapper;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
namespace SquirrelDatabase.Implementations;
public class EmployeeStorageContract : IEmployeeStorageContract
{
private readonly SquirrelDbContext _dbContext;
private readonly Mapper _mapper;
public EmployeeStorageContract(SquirrelDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Post, PostDataModel>()
.ForMember(x => x.Id, x => x.MapFrom(src => src.PostId));
cfg.CreateMap<Employee, EmployeeDataModel>();
cfg.CreateMap<EmployeeDataModel, Employee>();
});
_mapper = new Mapper(config);
}
public List<EmployeeDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null)
{
try
{
var query = _dbContext.Employees.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 >= DateTime.SpecifyKind(fromBirthDate ?? DateTime.UtcNow, DateTimeKind.Utc) && x.BirthDate <= DateTime.SpecifyKind(toBirthDate ?? DateTime.UtcNow, DateTimeKind.Utc));
}
if (fromEmploymentDate is not null && toEmploymentDate is not null)
{
query = query.Where(x => x.EmploymentDate >= DateTime.SpecifyKind(fromEmploymentDate ?? DateTime.UtcNow, DateTimeKind.Utc) && x.EmploymentDate <= DateTime.SpecifyKind(toEmploymentDate ?? DateTime.UtcNow, DateTimeKind.Utc));
}
return [.. JoinPost(query).Select(x => _mapper.Map<EmployeeDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public EmployeeDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<EmployeeDataModel>(GetEmployeeById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public EmployeeDataModel? GetElementByFIO(string fio)
{
try
{
return _mapper.Map<EmployeeDataModel>(AddPost(_dbContext.Employees.FirstOrDefault(x => x.FIO == fio && !x.IsDeleted)));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public EmployeeDataModel? GetElementByEmail(string email)
{
try
{
return _mapper.Map<EmployeeDataModel>(AddPost(_dbContext.Employees.FirstOrDefault(x => x.Email == email && !x.IsDeleted)));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(EmployeeDataModel employeeDataModel)
{
try
{
_dbContext.Employees.Add(_mapper.Map<Employee>(employeeDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", employeeDataModel.Id);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(EmployeeDataModel employeeDataModel)
{
try
{
var element = GetEmployeeById(employeeDataModel.Id) ?? throw new ElementNotFoundException(employeeDataModel.Id);
_dbContext.Employees.Update(_mapper.Map(employeeDataModel, 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 = GetEmployeeById(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 Employee? GetEmployeeById(string id) => AddPost(_dbContext.Employees.FirstOrDefault(x => x.Id == id && !x.IsDeleted));
private IQueryable<Employee> JoinPost(IQueryable<Employee> query)
=> query.GroupJoin(_dbContext.Posts.Where(x => x.IsActual), x => x.PostId, y => y.PostId, (x, y) => new { Employee = x, Post = y })
.SelectMany(xy => xy.Post.DefaultIfEmpty(), (x, y) => x.Employee.AddPost(y));
private Employee? AddPost(Employee? employee)
=> employee?.AddPost(_dbContext.Posts.FirstOrDefault(x => x.PostId == employee.PostId && x.IsActual));
}

View File

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

View File

@@ -0,0 +1,62 @@
using AutoMapper;
using BarBelochkaContract.DataModels;
using Microsoft.EntityFrameworkCore;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
namespace SquirrelDatabase.Implementations;
public class SalaryStorageContract : ISalaryStorageContract
{
private readonly SquirrelDbContext _dbContext;
private readonly Mapper _mapper;
public SalaryStorageContract(SquirrelDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Employee, EmployeeDataModel>();
cfg.CreateMap<Salary, SalaryDataModel>();
cfg.CreateMap<SalaryDataModel, Salary>()
.ForMember(dest => dest.EmployeeSalary, opt => opt.MapFrom(src => src.Salary));
});
_mapper = new Mapper(config);
}
public List<SalaryDataModel> GetList(DateTime? startDate, DateTime? endDate, string? employeeId = null)
{
try
{
var query = _dbContext.Salaries.Include(d => d.Employee).AsQueryable();
if (startDate.HasValue)
query = query.Where(x => x.SalaryDate >= DateTime.SpecifyKind(startDate ?? DateTime.UtcNow, DateTimeKind.Utc));
if (endDate.HasValue)
query = query.Where(x => x.SalaryDate <= DateTime.SpecifyKind(endDate ?? DateTime.UtcNow, DateTimeKind.Utc));
if (employeeId != null)
query = query.Where(x => x.EmployeeId == employeeId);
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,120 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
using System;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace SquirrelDatabase.Implementations;
public class SaleStorageContract : ISaleStorageContract
{
private readonly SquirrelDbContext _dbContext;
private readonly Mapper _mapper;
public SaleStorageContract(SquirrelDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Client, ClientDataModel>();
cfg.CreateMap<Cocktail, CocktailDataModel>();
cfg.CreateMap<Employee, EmployeeDataModel>();
cfg.CreateMap<SaleCocktail, SaleCocktailDataModel>();
cfg.CreateMap<SaleCocktailDataModel, SaleCocktail>()
.ForMember(x => x.Cocktail, x => x.Ignore());
cfg.CreateMap<Sale, SaleDataModel>();
cfg.CreateMap<SaleDataModel, Sale>()
.ForMember(x => x.IsCancel, x => x.MapFrom(src => false))
.ForMember(x => x.SaleCocktails, x => x.MapFrom(src => src.Cocktails))
.ForMember(x => x.Employee, x => x.Ignore())
.ForMember(x => x.Client, x => x.Ignore());
});
_mapper = new Mapper(config);
}
public List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? employeeId = null, string? clientId = null, string? cocktailId = null)
{
try
{
var query = _dbContext.Sales
.Include(r => r.Employee)
.Include(r => r.Client)
.Include(r => r.SaleCocktails)!
.ThenInclude(d => d.Cocktail)
.AsQueryable();
if (startDate.HasValue)
query = query.Where(x => x.SaleDate >= DateTime.SpecifyKind(startDate ?? DateTime.UtcNow, DateTimeKind.Utc));
if (endDate.HasValue)
query = query.Where(x => x.SaleDate <= DateTime.SpecifyKind(endDate ?? DateTime.UtcNow, DateTimeKind.Utc));
if (employeeId != null)
query = query.Where(x => x.EmployeeId == employeeId);
if (clientId != null)
query = query.Where(x => x.ClientId == clientId);
if (cocktailId != null)
query = query.Where(x => x.SaleCocktails!.Any(y => y.CocktailId == cocktailId));
var s = query.ToList();
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.Client).Include(x => x.Employee).Include(x => x.SaleCocktails)!.ThenInclude(x => x.Cocktail).FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,100 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
using System;
namespace SquirrelDatabase.Implementations;
public class SupplyStorageContract : ISupplyStorageContract
{
private readonly SquirrelDbContext _dbContext;
private readonly IMapper _mapper;
public SupplyStorageContract(SquirrelDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<SupplyCocktail, SupplyCocktailDataModel>();
cfg.CreateMap<SupplyCocktailDataModel, SupplyCocktail>();
cfg.CreateMap<Supply, SupplyDataModel>();
cfg.CreateMap<SupplyDataModel, Supply>()
.ForMember(x => x.Cocktails, x => x.MapFrom(src => src.Cocktails));
});
_mapper = new Mapper(config);
}
public List<SupplyDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? cocktailId = null)
{
try
{
var query = _dbContext.Supplies.Include(x => x.Cocktails).AsQueryable();
if (startDate.HasValue)
query = query.Where(x => x.SupplyDate >= DateTime.SpecifyKind(startDate ?? DateTime.UtcNow, DateTimeKind.Utc));
if (endDate.HasValue)
query = query.Where(x => x.SupplyDate <= DateTime.SpecifyKind(endDate ?? DateTime.UtcNow, DateTimeKind.Utc));
if (cocktailId is not null)
{
query = query.Where(x => x.Cocktails!.Any(y => y.CocktailId == cocktailId));
}
return [.. query.Select(x => _mapper.Map<SupplyDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public SupplyDataModel GetElementById(string id)
{
try
{
return _mapper.Map<SupplyDataModel>(GetSuppliesById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(SupplyDataModel suppliesDataModel)
{
try
{
_dbContext.Supplies.Add(_mapper.Map<Supply>(suppliesDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdateElement(SupplyDataModel suppliesDataModel)
{
try
{
var element = GetSuppliesById(suppliesDataModel.Id) ?? throw new ElementNotFoundException(suppliesDataModel.Id);
_dbContext.Supplies.Update(_mapper.Map(suppliesDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Supply? GetSuppliesById(string id) => _dbContext.Supplies.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,211 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
namespace SquirrelDatabase.Implementations;
public class WarehouseStorageContract : IWarehouseStorageContract
{
private readonly SquirrelDbContext _dbContext;
private readonly Mapper _mapper;
public WarehouseStorageContract(SquirrelDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<WarehouseCocktail, WarehouseCocktailDataModel>();
cfg.CreateMap<WarehouseCocktailDataModel, WarehouseCocktail>();
cfg.CreateMap<Warehouse, WarehouseDataModel>();
cfg.CreateMap<WarehouseDataModel, Warehouse>()
.ForMember(x => x.Cocktails, x => x.MapFrom(src => src.Cocktails));
});
_mapper = new Mapper(config);
}
public List<WarehouseDataModel> GetList()
{
try
{
return [.. _dbContext.Warehouses.Select(x => _mapper.Map<WarehouseDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public WarehouseDataModel GetElementById(string id)
{
try
{
return _mapper.Map<WarehouseDataModel>(GetWarehouseById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public WarehouseDataModel GetElementByName(string name)
{
try
{
return _mapper.Map<WarehouseDataModel>(_dbContext.Warehouses.FirstOrDefault(x => x.Name == name));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(WarehouseDataModel warehouseDataModel)
{
try
{
_dbContext.Warehouses.Add(_mapper.Map<Warehouse>(warehouseDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(WarehouseDataModel warehouseDataModel)
{
try
{
var element = GetWarehouseById(warehouseDataModel.Id) ?? throw new ElementNotFoundException(warehouseDataModel.Id);
_dbContext.Warehouses.Update(_mapper.Map(warehouseDataModel, 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 = GetWarehouseById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Warehouses.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdWarehouseOnSupply(string warehouseId, string cocktailId, int count)
{
using var transaction = _dbContext.Database.BeginTransaction();
try
{
var warehouse = _dbContext.Warehouses
.Include(w => w.Cocktails)
.FirstOrDefault(w => w.Id == warehouseId);
if (warehouse == null)
{
throw new ElementNotFoundException($"Warehouse with id {warehouseId} not found.");
}
var warehouseCocktail = warehouse.Cocktails.FirstOrDefault(c => c.CocktailId == cocktailId);
if (warehouseCocktail != null)
{
warehouseCocktail.Count += count;
}
else
{
warehouse.Cocktails.Add(new WarehouseCocktail
{
WarehouseId = warehouseId,
CocktailId = cocktailId,
Count = count
});
}
_dbContext.SaveChanges();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public bool CheckCocktails(SaleDataModel saleDataModel)
{
using var transaction = _dbContext.Database.BeginTransaction();
try
{
foreach (var saleCocktail in saleDataModel.Cocktails)
{
int requiredCount = saleCocktail.Count;
var warehousesWithCocktail = _dbContext.Warehouses.Include(w => w.Cocktails)
.Where(w => w.Cocktails.Any(c => c.CocktailId == saleCocktail.CocktailId && c.Count > 0))
.ToList();
foreach (var warehouse in warehousesWithCocktail)
{
var warehouseCocktail = warehouse.Cocktails
.FirstOrDefault(c => c.CocktailId == saleCocktail.CocktailId);
if (warehouseCocktail == null || warehouseCocktail.Count == 0)
continue;
int toWithdraw = Math.Min(warehouseCocktail.Count, requiredCount);
warehouseCocktail.Count -= toWithdraw;
requiredCount -= toWithdraw;
_dbContext.SaveChanges();
if (requiredCount == 0)
break;
}
if (requiredCount > 0)
{
transaction.Rollback();
return false;
}
}
_dbContext.SaveChanges();
transaction.Commit();
return true;
}
catch (Exception ex)
{
transaction.Rollback();
throw new StorageException(ex);
}
}
private Warehouse? GetWarehouseById(string id) => _dbContext.Warehouses.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,18 @@
using AutoMapper;
using SquirrelContract.DataModels;
using System.ComponentModel.DataAnnotations.Schema;
namespace SquirrelDatabase.Models;
[AutoMap(typeof(ClientDataModel), ReverseMap = true)]
public class Client
{
public required string Id { get; set; } = Guid.NewGuid().ToString();
public required string FIO { get; set; }
public required string PhoneNumber { get; set; }
public double DiscountSize { get; set; }
[ForeignKey("ClientId")]
public List<Sale>? Sales { get; set; }
}

View File

@@ -0,0 +1,18 @@
using SquirrelContract.Enums;
using System.ComponentModel.DataAnnotations.Schema;
namespace SquirrelDatabase.Models;
public class Cocktail
{
public required string Id { get; set; }
public required string CocktailName { get; set; }
public double Price { get; set; }
public required AlcoholType BaseAlcohol { get; set; }
[ForeignKey("CocktailId")]
public List<CocktailHistory>? CocktailHistories { get; set; }
[ForeignKey("CocktailId")]
public List<SaleCocktail>? SaleCocktails { get; set; }
}

View File

@@ -0,0 +1,14 @@
namespace SquirrelDatabase.Models;
public class CocktailHistory
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string CocktailId { get; set; }
public double OldPrice { get; set; }
public DateTime ChangeDate { get; set; }
public Cocktail? Cocktail { get; set; }
}

View File

@@ -0,0 +1,38 @@
using AutoMapper;
using SquirrelContract.DataModels;
using System.ComponentModel.DataAnnotations.Schema;
namespace SquirrelDatabase.Models;
[AutoMap(typeof(EmployeeDataModel), ReverseMap = true)]
public class Employee
{
public required string Id { get; set; }
public required string FIO { get; set; }
public string Email { 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("EmployeeId")]
public List<Salary>? Salaries { get; set; }
[ForeignKey("EmployeeId")]
public List<Sale>? Sales { get; set; }
public Employee AddPost(Post? post)
{
Post = post;
return this;
}
}

View File

@@ -0,0 +1,22 @@
using AutoMapper;
using SquirrelContract.DataModels;
using SquirrelContract.Enums;
namespace SquirrelDatabase.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,18 @@
using AutoMapper;
using BarBelochkaContract.DataModels;
namespace SquirrelDatabase.Models;
public class Salary
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string EmployeeId { get; set; }
public DateTime SalaryDate { get; set; }
public double EmployeeSalary { get; set; }
public Employee? Employee { get; set; }
}

View File

@@ -0,0 +1,33 @@
using AutoMapper;
using BarBelochkaContract.DataModels;
using SquirrelContract.DataModels;
using SquirrelContract.Enums;
using System.ComponentModel.DataAnnotations.Schema;
namespace SquirrelDatabase.Models;
public class Sale
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string EmployeeId { get; set; }
public string? ClientId { get; set; }
public DateTime SaleDate { get; set; }
public double Sum { get; set; }
public DiscountType DiscountType { get; set; }
public double Discount { get; set; }
public bool IsCancel { get; set; }
public Employee? Employee { get; set; }
public Client? Client { get; set; }
[ForeignKey("SaleId")]
public List<SaleCocktail>? SaleCocktails { get; set; }
}

View File

@@ -0,0 +1,16 @@
namespace SquirrelDatabase.Models;
public class SaleCocktail
{
public required string SaleId { get; set; }
public required string CocktailId { get; set; }
public int Count { get; set; }
public double Price { get; set; }
public Sale? Sale { get; set; }
public Cocktail? Cocktail { get; set; }
}

View File

@@ -0,0 +1,14 @@
using AutoMapper;
using SquirrelContract.DataModels;
using System.ComponentModel.DataAnnotations.Schema;
namespace SquirrelDatabase.Models;
public class Supply
{
public required string Id { get; set; }
public DateTime SupplyDate { get; set; }
[ForeignKey("SupplyId")]
public List<SupplyCocktail>? Cocktails { get; set; }
}

View File

@@ -0,0 +1,13 @@
using AutoMapper;
using SquirrelContract.DataModels;
namespace SquirrelDatabase.Models;
public class SupplyCocktail
{
public required string SupplyId { get; set; }
public required string CocktailId { get; set; }
public int Count { get; set; }
public Supply? Supply { get; set; }
public Cocktail? Cocktails { get; set; }
}

View File

@@ -0,0 +1,14 @@
using AutoMapper;
using SquirrelContract.DataModels;
using System.ComponentModel.DataAnnotations.Schema;
namespace SquirrelDatabase.Models;
public class Warehouse
{
public required string Id { get; set; }
public required string Name { get; set; }
[ForeignKey("WarehouseId")]
public List<WarehouseCocktail> Cocktails { get; set; }
}

View File

@@ -0,0 +1,10 @@
namespace SquirrelDatabase.Models;
public class WarehouseCocktail
{
public required string WarehouseId { get; set; }
public required string CocktailId { get; set; }
public int Count { get; set; }
public Warehouse? Warehouse { get; set; }
public Cocktail? Cocktails { get; set; }
}

View File

@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.2" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SquirrelContract\SquirrelContract.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,72 @@
using Microsoft.EntityFrameworkCore;
using SquirrelContract.Infastructure;
using SquirrelDatabase.Models;
namespace SquirrelDatabase;
public class SquirrelDbContext(IConfigurationDatabase configurationDatabase) : DbContext
{
private readonly IConfigurationDatabase? _configurationDatabase = configurationDatabase;
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<Client>().HasIndex(x => x.PhoneNumber).IsUnique();
modelBuilder.Entity<Sale>()
.HasOne(e => e.Client)
.WithMany(e => e.Sales)
.OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity<Cocktail>().HasIndex(x => x.CocktailName).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<Warehouse>().HasIndex(x => x.Name).IsUnique();
modelBuilder.Entity<SupplyCocktail>().HasKey(x => new { x.SupplyId, x.CocktailId });
modelBuilder.Entity<WarehouseCocktail>().HasKey(x => new { x.WarehouseId, x.CocktailId });
modelBuilder.Entity<SaleCocktail>().HasKey(x => new { x.SaleId, x.CocktailId });
}
public DbSet<Client> Clients { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<Cocktail> Cocktails { get; set; }
public DbSet<CocktailHistory> CocktailHistories { get; set; }
public DbSet<Salary> Salaries { get; set; }
public DbSet<Sale> Sales { get; set; }
public DbSet<SaleCocktail> SaleCocktails { get; set; }
public DbSet<Employee> Employees { get; set; }
public DbSet<Supply> Supplies { get; set; }
public DbSet<Warehouse> Warehouses { get; set; }
public DbSet<SupplyCocktail> SupplyCocktails { get; set; }
public DbSet<WarehouseCocktail> WarehouseCocktails { get; set; }
}

View File

@@ -33,61 +33,53 @@ internal class PostBusinessLogicContractTests
//Arrange
var listOriginal = new List<PostDataModel>()
{
new(Guid.NewGuid().ToString(),"name 1", PostType.Manager, 10, true, DateTime.UtcNow),
new(Guid.NewGuid().ToString(), "name 2", PostType.Manager, 10, false, DateTime.UtcNow),
new(Guid.NewGuid().ToString(), "name 3", PostType.Manager, 10, true, DateTime.UtcNow),
new(Guid.NewGuid().ToString(),"name 1", PostType.Manager, 10),
new(Guid.NewGuid().ToString(), "name 2", PostType.Manager, 10),
new(Guid.NewGuid().ToString(), "name 3", PostType.Manager, 10),
};
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Returns(listOriginal);
_postStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
//Act
var listOnlyActive = _postBusinessLogicContract.GetAllPosts(true);
var listAll = _postBusinessLogicContract.GetAllPosts(false);
var list = _postBusinessLogicContract.GetAllPosts();
//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));
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_postStorageContract.Verify(x => x.GetList(true), Times.Once);
_postStorageContract.Verify(x => x.GetList(false), Times.Once);
_postStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllPosts_ReturnEmptyList_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Returns([]);
_postStorageContract.Setup(x => x.GetList()).Returns([]);
//Act
var listOnlyActive = _postBusinessLogicContract.GetAllPosts(true);
var listAll = _postBusinessLogicContract.GetAllPosts(false);
var list = _postBusinessLogicContract.GetAllPosts();
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(listAll, Is.Not.Null);
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(listAll, Has.Count.EqualTo(0));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
});
_postStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Exactly(2));
}
[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);
Assert.That(() => _postBusinessLogicContract.GetAllPosts(), Throws.TypeOf<NullListException>());
_postStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllPosts_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.GetList()).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);
Assert.That(() => _postBusinessLogicContract.GetAllPosts(), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
@@ -97,8 +89,8 @@ internal class PostBusinessLogicContractTests
var postId = Guid.NewGuid().ToString();
var listOriginal = new List<PostDataModel>()
{
new(postId, "name 1", PostType.Manager, 10, true, DateTime.UtcNow),
new(postId, "name 2", PostType.Manager, 10, false, DateTime.UtcNow)
new(postId, "name 1", PostType.Manager, 10),
new(postId, "name 2", PostType.Manager, 10)
};
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns(listOriginal);
//Act
@@ -162,7 +154,7 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new PostDataModel(id, "name", PostType.Manager, 10, true, DateTime.UtcNow);
var record = new PostDataModel(id, "name", PostType.Manager, 10);
_postStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(id);
@@ -177,7 +169,7 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var postName = "name";
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.Manager, 10, true, DateTime.UtcNow);
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.Manager, 10);
_postStorageContract.Setup(x => x.GetElementByName(postName)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(postName);
@@ -233,12 +225,11 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Bartender, 10, true, DateTime.UtcNow.AddDays(-1));
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 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 &&
x.ChangeDate == record.ChangeDate;
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary;
});
//Act
_postBusinessLogicContract.InsertPost(record);
@@ -253,7 +244,7 @@ internal class PostBusinessLogicContractTests
//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.Bartender, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementExistsException>());
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Manager, 10)), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
}
@@ -269,7 +260,7 @@ internal class PostBusinessLogicContractTests
public void InsertPost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Bartender, 10, true, DateTime.UtcNow)), Throws.TypeOf<ValidationException>());
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Manager, 10)), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Never);
}
@@ -279,7 +270,7 @@ internal class PostBusinessLogicContractTests
//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.Bartender, 10, true, DateTime.UtcNow)), Throws.TypeOf<StorageException>());
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Manager, 10)), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
}
@@ -288,12 +279,11 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Bartender, 10, true, DateTime.UtcNow.AddDays(-1));
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 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 &&
x.ChangeDate == record.ChangeDate;
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary;
});
//Act
_postBusinessLogicContract.UpdatePost(record);
@@ -308,7 +298,7 @@ internal class PostBusinessLogicContractTests
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Bartender, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementNotFoundException>());
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Manager, 10)), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
@@ -318,7 +308,7 @@ internal class PostBusinessLogicContractTests
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.Bartender, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementExistsException>());
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.Manager, 10)), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
@@ -334,7 +324,7 @@ internal class PostBusinessLogicContractTests
public void UpdatePost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Bartender, 10, true, DateTime.UtcNow)), Throws.TypeOf<ValidationException>());
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Manager, 10)), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Never);
}
@@ -344,7 +334,7 @@ internal class PostBusinessLogicContractTests
//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.Bartender, 10, true, DateTime.UtcNow)), Throws.TypeOf<StorageException>());
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Manager, 10)), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}

View File

@@ -160,7 +160,7 @@ internal class SalaryBusinessLogicContractTests
public void GetAllSalariesByEmployee_EmployeeIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByEmployee(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), "workerId"), Throws.TypeOf<ValidationException>());
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByEmployee(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), "employeeId"), Throws.TypeOf<ValidationException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Never);
}
@@ -187,12 +187,12 @@ internal class SalaryBusinessLogicContractTests
{
//Arrange
var employeeId = Guid.NewGuid().ToString();
var saleSum = 200.0;
var saleSum = 1.2 * 5;
var postSalary = 2000.0;
_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(), employeeId, null, saleSum, DiscountType.None, 0, false, [])]);
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employeeId, null, DiscountType.None, false, [new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, postSalary, true, DateTime.UtcNow));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, postSalary));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new EmployeeDataModel(employeeId, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
var sum = 0.0;
@@ -209,7 +209,7 @@ internal class SalaryBusinessLogicContractTests
}
[Test]
public void CalculateSalaryByMounth_WithSeveralWorkers_Test()
public void CalculateSalaryByMounth_WithSeveralEmployees_Test()
{
//Arrange
var employee1Id = Guid.NewGuid().ToString();
@@ -221,13 +221,13 @@ internal class SalaryBusinessLogicContractTests
new(employee3Id, "Test", "123@gmail.com", 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(), employee1Id, null, 1, DiscountType.None, 0, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), employee1Id, null, 1, DiscountType.None, 0, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), employee2Id, null, 1, DiscountType.None, 0, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), employee3Id, null, 1, DiscountType.None, 0, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), employee3Id, null, 1, DiscountType.None, 0, false, [])]);
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employee1Id, null, DiscountType.None, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), employee1Id, null, DiscountType.None, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), employee2Id, null, DiscountType.None, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), employee3Id, null, DiscountType.None, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), employee3Id, null, DiscountType.None, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000, true, DateTime.UtcNow));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000));
_employeeStorageContract.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
@@ -237,7 +237,7 @@ internal class SalaryBusinessLogicContractTests
}
[Test]
public void CalculateSalaryByMounth_WithoutSalesByWorker_Test()
public void CalculateSalaryByMounth_WithoutSalesByEmployee_Test()
{
//Arrange
var postSalary = 2000.0;
@@ -245,7 +245,7 @@ internal class SalaryBusinessLogicContractTests
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, postSalary, true, DateTime.UtcNow));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, postSalary));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new EmployeeDataModel(employeeId, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
var sum = 0.0;
@@ -267,7 +267,7 @@ internal class SalaryBusinessLogicContractTests
//Arrange
var employeeId = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000, true, DateTime.UtcNow));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new EmployeeDataModel(employeeId, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
@@ -280,22 +280,22 @@ internal class SalaryBusinessLogicContractTests
//Arrange
var employeeId = 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(), employeeId, null, 200, DiscountType.None, 0, false, [])]);
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employeeId, null, DiscountType.None, false, [])]);
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new EmployeeDataModel(employeeId, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
.Returns([new EmployeeDataModel(employeeId, "Test", "abc@gmail.com", 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()
public void CalculateSalaryByMounth_EmployeeStorageReturnNull_ThrowException_Test()
{
//Arrange
var employeeId = 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(), employeeId, null, 200, DiscountType.None, 0, false, [])]);
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employeeId, null, DiscountType.None, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000, true, DateTime.UtcNow));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
@@ -308,7 +308,7 @@ internal class SalaryBusinessLogicContractTests
_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.Manager, 2000, true, DateTime.UtcNow));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new EmployeeDataModel(employeeId, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
@@ -321,7 +321,7 @@ internal class SalaryBusinessLogicContractTests
//Arrange
var employeeId = 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(), employeeId, null, 200, DiscountType.None, 0, false, [])]);
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employeeId, null, DiscountType.None, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
@@ -331,14 +331,14 @@ internal class SalaryBusinessLogicContractTests
}
[Test]
public void CalculateSalaryByMounth_WorkerStorageThrowException_ThrowException_Test()
public void CalculateSalaryByMounth_EmployeeStorageThrowException_ThrowException_Test()
{
//Arrange
var employeeId = 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(), employeeId, null, 200, DiscountType.None, 0, false, [])]);
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employeeId, null, DiscountType.None, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000, true, DateTime.UtcNow));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000));
_employeeStorageContract.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

View File

@@ -13,18 +13,21 @@ internal class SaleBusinessLogicContractTests
{
private SaleBusinessLogicContract _saleBusinessLogicContract;
private Mock<ISaleStorageContract> _saleStorageContract;
private Mock<IWarehouseStorageContract> _warehouseStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_saleStorageContract = new Mock<ISaleStorageContract>();
_saleBusinessLogicContract = new SaleBusinessLogicContract(_saleStorageContract.Object, new Mock<ILogger>().Object);
_warehouseStorageContract = new Mock<IWarehouseStorageContract>();
_saleBusinessLogicContract = new SaleBusinessLogicContract(_saleStorageContract.Object, _warehouseStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_saleStorageContract.Reset();
_warehouseStorageContract.Reset();
}
[Test]
@@ -34,10 +37,10 @@ internal class SaleBusinessLogicContractTests
var date = DateTime.UtcNow;
var listOriginal = new List<SaleDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
[new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false,
[new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
@@ -98,10 +101,10 @@ internal class SaleBusinessLogicContractTests
var employeeId = Guid.NewGuid().ToString();
var listOriginal = new List<SaleDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
[new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false,
[new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
@@ -179,10 +182,10 @@ internal class SaleBusinessLogicContractTests
var clientId = Guid.NewGuid().ToString();
var listOriginal = new List<SaleDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
[new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false,
[new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
@@ -260,10 +263,10 @@ internal class SaleBusinessLogicContractTests
var cocktailId = Guid.NewGuid().ToString();
var listOriginal = new List<SaleDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
[new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false,
[new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.None, false, []),
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
@@ -338,8 +341,8 @@ internal class SaleBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new SaleDataModel(id, Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
[new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
var record = new SaleDataModel(id, Guid.NewGuid().ToString(), null, DiscountType.None, false,
[new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]);
_saleStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _saleBusinessLogicContract.GetSaleByData(id);
@@ -389,8 +392,9 @@ internal class SaleBusinessLogicContractTests
{
//Arrange
var flag = false;
var record = new SaleDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.None, 10,
false, [new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
var record = new SaleDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.None,
false, [new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]);
_warehouseStorageContract.Setup(x => x.CheckCocktails(It.IsAny<SaleDataModel>())).Returns(true);
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>()))
.Callback((SaleDataModel x) =>
{
@@ -404,6 +408,7 @@ internal class SaleBusinessLogicContractTests
//Act
_saleBusinessLogicContract.InsertSale(record);
//Assert
_warehouseStorageContract.Verify(x => x.CheckCocktails(It.IsAny<SaleDataModel>()), Times.Once);
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
Assert.That(flag);
}
@@ -412,11 +417,13 @@ internal class SaleBusinessLogicContractTests
public void InsertSale_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.CheckCocktails(It.IsAny<SaleDataModel>())).Returns(true);
_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(), 10, DiscountType.None, 10, false, [new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
Guid.NewGuid().ToString(), DiscountType.None, false, [new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])), Throws.TypeOf<ElementExistsException>());
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
_warehouseStorageContract.Verify(x => x.CheckCocktails(It.IsAny<SaleDataModel>()), Times.Once);
}
[Test]
@@ -431,7 +438,7 @@ internal class SaleBusinessLogicContractTests
public void InsertSale_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertSale(new SaleDataModel("id", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false, [])), Throws.TypeOf<ValidationException>());
Assert.That(() => _saleBusinessLogicContract.InsertSale(new SaleDataModel("id", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.None, false, [])), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Never);
}
@@ -439,13 +446,26 @@ internal class SaleBusinessLogicContractTests
public void InsertSale_StorageThrowError_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.CheckCocktails(It.IsAny<SaleDataModel>())).Returns(true);
_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(), 10, DiscountType.None, 10, false, [new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
Guid.NewGuid().ToString(), DiscountType.None, false, [new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.CheckCocktails(It.IsAny<SaleDataModel>()), Times.Once);
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
}
[Test]
public void InsertSale_InsufficientError_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.CheckCocktails(It.IsAny<SaleDataModel>())).Returns(false);
Assert.That(() => _saleBusinessLogicContract.InsertSale(new SaleDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), DiscountType.None, false, [new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])), Throws.TypeOf<InsufficientStockException>());
//Act&Assert
_warehouseStorageContract.Verify(x => x.CheckCocktails(It.IsAny<SaleDataModel>()), Times.Once);
}
[Test]
public void CancelSale_CorrectRecord_Test()
{

View File

@@ -0,0 +1,284 @@
using Microsoft.Extensions.Logging;
using Moq;
using SquirrelBusinessLogic.Implementations;
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.DataModels;
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace SquirrelTests.BusinessLogicContractsTests;
[TestFixture]
internal class SupplyBusinessLogicContractTests
{
private SupplyBusinessLogicContract _supplyBusinessLogicContract;
private Mock<ISupplyStorageContract> _supplyStorageContract;
private Mock<IWarehouseStorageContract> _warehouseStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_supplyStorageContract = new Mock<ISupplyStorageContract>();
_warehouseStorageContract = new Mock<IWarehouseStorageContract>();
_supplyBusinessLogicContract = new SupplyBusinessLogicContract(_supplyStorageContract.Object, _warehouseStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_supplyStorageContract.Reset();
}
[Test]
public void GetAllSuppliesByPeriod_ReturnListOfRecords_Test()
{
var date = DateTime.UtcNow;
// Arrange
var listOriginal = new List<SupplyDataModel>()
{
new(Guid.NewGuid().ToString(), DateTime.Now, []),
new(Guid.NewGuid().ToString(), DateTime.Now, []),
new(Guid.NewGuid().ToString(), DateTime.Now, [])
};
_supplyStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>())).Returns(listOriginal);
// Act
var list = _supplyBusinessLogicContract.GetAllSuppliesByPeriod(date, date.AddDays(1));
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_supplyStorageContract.Verify(x => x.GetList(date, date.AddDays(1), null), Times.Once);
}
[Test]
public void GetAllSuppliesByPeriod_ReturnEmptyList_Test()
{
//Arrange
_supplyStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>())).Returns([]);
//Act
var list = _supplyBusinessLogicContract.GetAllSuppliesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_supplyStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSuppliesByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _supplyBusinessLogicContract.GetAllSuppliesByPeriod(date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _supplyBusinessLogicContract.GetAllSuppliesByPeriod(date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_supplyStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSuppliesByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _supplyBusinessLogicContract.GetAllSuppliesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_supplyStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSuppliesByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_supplyStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _supplyBusinessLogicContract.GetAllSuppliesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_supplyStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSuppliesByCocktailByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var cocktailId = Guid.NewGuid().ToString();
var listOriginal = new List<SupplyDataModel>()
{
new(Guid.NewGuid().ToString(), DateTime.Now,
[new SupplyCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
new(Guid.NewGuid().ToString(), DateTime.Now, []),
new(Guid.NewGuid().ToString(), DateTime.Now, []),
};
_supplyStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _supplyBusinessLogicContract.GetAllSuppliesByCocktailByPeriod(cocktailId, date, date.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_supplyStorageContract.Verify(x => x.GetList(date, date.AddDays(1), cocktailId), Times.Once);
}
[Test]
public void GetAllSuppliesByCocktailByPeriod_ReturnEmptyList_Test()
{
//Arrange
_supplyStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>())).Returns([]);
//Act
var list = _supplyBusinessLogicContract.GetAllSuppliesByCocktailByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_supplyStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSuppliesByCocktailByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _supplyBusinessLogicContract.GetAllSuppliesByCocktailByPeriod(Guid.NewGuid().ToString(), date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _supplyBusinessLogicContract.GetAllSuppliesByCocktailByPeriod(Guid.NewGuid().ToString(), date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_supplyStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSuppliesByCocktailByPeriod_CocktailIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _supplyBusinessLogicContract.GetAllSuppliesByCocktailByPeriod(null, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _supplyBusinessLogicContract.GetAllSuppliesByCocktailByPeriod(string.Empty, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
_supplyStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSuppliesByCocktailByPeriod_CocktailIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _supplyBusinessLogicContract.GetAllSuppliesByCocktailByPeriod("cocktailId", DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ValidationException>());
_supplyStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSuppliesByCocktailByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _supplyBusinessLogicContract.GetAllSuppliesByCocktailByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_supplyStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSuppliesByCocktailByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_supplyStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _supplyBusinessLogicContract.GetAllSuppliesByCocktailByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_supplyStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetSupplyByData_GetById_ReturnRecord_Test()
{
// Arrange
var id = Guid.NewGuid().ToString();
var record = new SupplyDataModel(id, DateTime.Now, []);
_supplyStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
// Act
var element = _supplyBusinessLogicContract.GetSupplyByData(id);
// Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_supplyStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetSupplyByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _supplyBusinessLogicContract.GetSupplyByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _supplyBusinessLogicContract.GetSupplyByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_supplyStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetSupplyByData_GetById_NotFoundRecord_ThrowException_Test()
{
// Arrange
_supplyStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new ElementNotFoundException(""));
// Act & Assert
Assert.That(() => _supplyBusinessLogicContract.GetSupplyByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_supplyStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetSuppliesByData_StorageThrowError_ThrowException_Test()
{
// Arrange
_supplyStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _supplyBusinessLogicContract.GetSupplyByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_supplyStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertSupply_CorrectRecord_Test()
{
// Arrange
var supplyId = Guid.NewGuid().ToString();
var cocktailId = Guid.NewGuid().ToString();
var warehouseId = Guid.NewGuid().ToString();
var record = new SupplyDataModel(supplyId, DateTime.Now,
[new SupplyCocktailDataModel(supplyId, cocktailId, 5)]);
var warehouse = new WarehouseDataModel(warehouseId, "Main Warehouse",
[new WarehouseCocktailDataModel(warehouseId, cocktailId, 10)]);
_supplyStorageContract.Setup(x => x.AddElement(It.IsAny<SupplyDataModel>()));
_warehouseStorageContract.Setup(x => x.GetList()).Returns([warehouse]);
_warehouseStorageContract.Setup(x => x.UpdWarehouseOnSupply(warehouseId, cocktailId, 5));
// Act
_supplyBusinessLogicContract.InsertSupply(record);
// Assert
_supplyStorageContract.Verify(x => x.AddElement(It.IsAny<SupplyDataModel>()), Times.Once);
_warehouseStorageContract.Verify(x => x.UpdWarehouseOnSupply(warehouseId, cocktailId, 5), Times.Once);
}
[Test]
public void InsertSupply_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_supplyStorageContract.Setup(x => x.AddElement(It.IsAny<SupplyDataModel>())).Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() => _supplyBusinessLogicContract.InsertSupply(new(Guid.NewGuid().ToString(), DateTime.Now,
[new SupplyCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_supplyStorageContract.Verify(x => x.AddElement(It.IsAny<SupplyDataModel>()), Times.Once);
}
[Test]
public void InsertSupply_NullRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _supplyBusinessLogicContract.InsertSupply(null), Throws.TypeOf<ArgumentNullException>());
_supplyStorageContract.Verify(x => x.AddElement(It.IsAny<SupplyDataModel>()), Times.Never);
}
[Test]
public void InsertSupply_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _supplyBusinessLogicContract.InsertSupply(new SupplyDataModel("id", DateTime.UtcNow, [])), Throws.TypeOf<ValidationException>());
_supplyStorageContract.Verify(x => x.AddElement(It.IsAny<SupplyDataModel>()), Times.Never);
}
[Test]
public void InsertSupply_StorageThrowError_ThrowException_Test()
{
// Arrange
_supplyStorageContract.Setup(x => x.AddElement(It.IsAny<SupplyDataModel>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _supplyBusinessLogicContract.InsertSupply(new(Guid.NewGuid().ToString(), DateTime.Now,
[new SupplyCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_supplyStorageContract.Verify(x => x.AddElement(It.IsAny<SupplyDataModel>()), Times.Once);
}
}

View File

@@ -0,0 +1,320 @@
using Microsoft.Extensions.Logging;
using Moq;
using SquirrelBusinessLogic.Implementations;
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.DataModels;
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
namespace SquirrelTests.BusinessLogicContractsTests;
[TestFixture]
internal class WarehouseBusinessLogicContractTests
{
private WarehouseBusinessLogicContract _warehouseBusinessLogicContract;
private Mock<IWarehouseStorageContract> _warehouseStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_warehouseStorageContract = new Mock<IWarehouseStorageContract>();
_warehouseBusinessLogicContract = new WarehouseBusinessLogicContract(_warehouseStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_warehouseStorageContract.Reset();
}
[Test]
public void GetAllWarehouses_ReturnListOfRecords_Test()
{
// Arrange
var listOriginal = new List<WarehouseDataModel>()
{
new(Guid.NewGuid().ToString(), "aba", []),
new(Guid.NewGuid().ToString(), "aaa", []),
new(Guid.NewGuid().ToString(), "aaa", []),
};
_warehouseStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
// Act
var list = _warehouseBusinessLogicContract.GetAllWarehouses();
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
}
[Test]
public void GetAllWarehouses_ReturnEmptyList_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetList()).Returns([]);
// Act
var list = _warehouseBusinessLogicContract.GetAllWarehouses();
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_warehouseStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllWarehouses_ReturnNull_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetList()).Returns((List<WarehouseDataModel>)null);
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.GetAllWarehouses(), Throws.TypeOf<NullListException>());
_warehouseStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllWarehouses_StorageThrowError_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.GetAllWarehouses(), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllWarehousesByData_GetById_ReturnRecord_Test()
{
// Arrange
var id = Guid.NewGuid().ToString();
var record = new WarehouseDataModel(id, "aba", []);
_warehouseStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
// Act
var element = _warehouseBusinessLogicContract.GetWarehouseByData(id);
// Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetCocktailByData_GetByName_ReturnRecord_Test()
{
//Arrange
var name = "name";
var record = new WarehouseDataModel(Guid.NewGuid().ToString(), name, []);
_warehouseStorageContract.Setup(x => x.GetElementByName(name)).Returns(record);
//Act
var element = _warehouseBusinessLogicContract.GetWarehouseByData(name);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Name, Is.EqualTo(name));
_warehouseStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetWarehouseByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.GetWarehouseByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _warehouseBusinessLogicContract.GetWarehouseByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
_warehouseStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetWarehouseByData_GetById_NotFoundRecord_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new ElementNotFoundException(""));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.GetWarehouseByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetWarehouseByData_GetByName_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.GetWarehouseByData("name"), Throws.TypeOf<ElementNotFoundException>());
_warehouseStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetWarehouseByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_warehouseStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.GetWarehouseByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _warehouseBusinessLogicContract.GetWarehouseByData("name"), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_warehouseStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertWarehouse_CorrectRecord_Test()
{
// Arrange
var record = new WarehouseDataModel(Guid.NewGuid().ToString(), "aba",
[new WarehouseCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_warehouseStorageContract.Setup(x => x.AddElement(It.IsAny<WarehouseDataModel>()));
// Act
_warehouseBusinessLogicContract.InsertWarehouse(record);
// Assert
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void InsertWarehouse_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.AddElement(It.IsAny<WarehouseDataModel>())).Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertWarehouse(new(Guid.NewGuid().ToString(), "aba",
[new WarehouseCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void InsertWarehouse_NullRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertWarehouse(null), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<WarehouseDataModel>()), Times.Never);
}
[Test]
public void InsertWarehouse_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertWarehouse(new WarehouseDataModel("id", "aba", [])), Throws.TypeOf<ValidationException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<WarehouseDataModel>()), Times.Never);
}
[Test]
public void InsertWarehouse_StorageThrowError_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.AddElement(It.IsAny<WarehouseDataModel>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertWarehouse(new(Guid.NewGuid().ToString(), "aba",
[new WarehouseCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void UpdateWarehouse_CorrectRecord_Test()
{
// Arrange
var record = new WarehouseDataModel(Guid.NewGuid().ToString(), "aba",
[new WarehouseCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<WarehouseDataModel>()));
// Act
_warehouseBusinessLogicContract.UpdateWarehouse(record);
// Assert
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void UpdateWarehouse_RecordWithIncorrectData_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<WarehouseDataModel>())).Throws(new ElementNotFoundException(""));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateWarehouse(new(Guid.NewGuid().ToString(), "aba",
[new WarehouseCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementNotFoundException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void UpdateWarehouse_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<WarehouseDataModel>())).Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateWarehouse(new(Guid.NewGuid().ToString(), "aba",
[new WarehouseCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void UpdateWarehouse_NullRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateWarehouse(null), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<WarehouseDataModel>()), Times.Never);
}
[Test]
public void UpdateWarehouse_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateWarehouse(new WarehouseDataModel(Guid.NewGuid().ToString(), "aba", [])), Throws.TypeOf<ValidationException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<WarehouseDataModel>()), Times.Never);
}
[Test]
public void UpdateWarehouse_StorageThrowError_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<WarehouseDataModel>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateWarehouse(new(Guid.NewGuid().ToString(), "aba",
[new WarehouseCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<WarehouseDataModel>()), Times.Once);
}
[Test]
public void DeleteWarehouse_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_warehouseStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_warehouseBusinessLogicContract.DeleteWarehouse(id);
//Assert
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once); Assert.That(flag);
}
[Test]
public void DeleteWarehouse_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_warehouseStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.DeleteWarehouse(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeleteWarehouse_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.DeleteWarehouse(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _warehouseBusinessLogicContract.DeleteWarehouse(string.Empty), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteWarehouse_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.DeleteWarehouse("id"),
Throws.TypeOf<ValidationException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteWarehouse_StorageThrowError_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.DeleteWarehouse(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -10,41 +10,41 @@ internal class PostDataModelTests
[Test]
public void IdIsNullOrEmptyTest()
{
var post = CreateDataModel(null, "name", PostType.Manager, 10, true, DateTime.UtcNow);
var post = CreateDataModel(null, "name", PostType.Manager, 10);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(string.Empty, "name", PostType.Manager, 10, true, DateTime.UtcNow);
post = CreateDataModel(string.Empty, "name", PostType.Manager, 10);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var post = CreateDataModel("id", "name", PostType.Manager, 10, true, DateTime.UtcNow);
var post = CreateDataModel("id", "name", PostType.Manager, 10);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostNameIsEmptyTest()
{
var manufacturer = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Manager, 10, true, DateTime.UtcNow);
var manufacturer = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Manager, 10);
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
manufacturer = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Manager, 10, true, DateTime.UtcNow);
manufacturer = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Manager, 10);
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostTypeIsNoneTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.None, 10, true, DateTime.UtcNow);
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.None, 10);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void SalaryIsLessOrZeroTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 0, true, DateTime.UtcNow);
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 0);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, -10, true, DateTime.UtcNow);
post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, -10);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
@@ -55,9 +55,7 @@ internal class PostDataModelTests
var postName = "name";
var postType = PostType.Manager;
var salary = 10;
var isActual = false;
var changeDate = DateTime.UtcNow.AddDays(-1);
var post = CreateDataModel(postId, postName, postType, salary, isActual, changeDate);
var post = CreateDataModel(postId, postName, postType, salary);
Assert.That(() => post.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
@@ -65,11 +63,9 @@ internal class PostDataModelTests
Assert.That(post.PostName, Is.EqualTo(postName));
Assert.That(post.PostType, Is.EqualTo(postType));
Assert.That(post.Salary, Is.EqualTo(salary));
Assert.That(post.IsActual, Is.EqualTo(isActual));
Assert.That(post.ChangeDate, Is.EqualTo(changeDate));
});
}
private static PostDataModel CreateDataModel(string? id, string? postName, PostType postType, double salary, bool isActual, DateTime changeDate) =>
new(id, postName, postType, salary, isActual, changeDate);
private static PostDataModel CreateDataModel(string? id, string? postName, PostType postType, double salary) =>
new(id, postName, postType, salary);
}

View File

@@ -9,41 +9,50 @@ internal class SaleCocktailDataModelTests
[Test]
public void SaleIdIsNullOrEmptyTest()
{
var saleCocktail = CreateDataModel(null, Guid.NewGuid().ToString(), 10);
var saleCocktail = CreateDataModel(null, Guid.NewGuid().ToString(), 10, 1.1);
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
saleCocktail = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10);
saleCocktail = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10, 1.1);
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void SaleIdIsNotGuidTest()
{
var saleProduct = CreateDataModel("saleId", Guid.NewGuid().ToString(), 10);
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
var saleCocktail = CreateDataModel("saleId", Guid.NewGuid().ToString(), 10, 1.1);
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CocktailIdIsNullOrEmptyTest()
{
var saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), null, 10);
var saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), null, 10, 1.1);
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
saleCocktail = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10);
saleCocktail = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10, 1.1);
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductIdIsNotGuidTest()
public void CocktailIdIsNotGuidTest()
{
var saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), "productId", 10);
var saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), "cocktailId", 10, 1.1);
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CountIsLessOrZeroTest()
{
var saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0);
var saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0, 1.1);
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -10);
saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -10, 1.1);
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PriceIsLessOrZeroTest()
{
var saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 0);
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, -10);
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
@@ -53,16 +62,18 @@ internal class SaleCocktailDataModelTests
var saleId = Guid.NewGuid().ToString();
var cocktailId = Guid.NewGuid().ToString();
var count = 10;
var saleCocktail = CreateDataModel(saleId, cocktailId, count);
var price = 1.2;
var saleCocktail = CreateDataModel(saleId, cocktailId, count, price);
Assert.That(() => saleCocktail.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(saleCocktail.SaleId, Is.EqualTo(saleId));
Assert.That(saleCocktail.CocktailId, Is.EqualTo(cocktailId));
Assert.That(saleCocktail.Count, Is.EqualTo(count));
Assert.That(saleCocktail.Price, Is.EqualTo(price));
});
}
private static SaleCocktailDataModel CreateDataModel(string? saleId, string? cocktailId, int count) =>
new(saleId, cocktailId, count);
private static SaleCocktailDataModel CreateDataModel(string? saleId, string? cocktailId, int count, double price) =>
new(saleId, cocktailId, count, price);
}

View File

@@ -10,88 +10,120 @@ internal class SaleDataModelTests
[Test]
public void IdIsNullOrEmptyTest()
{
var sale = CreateDataModel(null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, CreateSubDataModel());
var sale = CreateDataModel(null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
sale = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, CreateSubDataModel());
sale = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var sale = CreateDataModel("id", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, CreateSubDataModel());
var sale = CreateDataModel("id", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void EmployeeIdIsNullOrEmptyTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), null, Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, CreateSubDataModel());
var sale = CreateDataModel(Guid.NewGuid().ToString(), null, Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
sale = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, CreateSubDataModel());
sale = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void EmployeeIdIsNotGuidTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), "employeeId", Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, CreateSubDataModel());
var sale = CreateDataModel(Guid.NewGuid().ToString(), "employeeId", Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ClientIdIsNotGuidTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "clientId", 10, DiscountType.OnSale, 10, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void SumIsLessOrZeroTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0, DiscountType.OnSale, 10, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -10, DiscountType.OnSale, 10, false, CreateSubDataModel());
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "clientId", DiscountType.OnSale, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CocktailsIsNullOrEmptyTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, null);
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.OnSale, false, null);
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.OnSale, 10, false, []);
sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.OnSale, false, []);
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CalcSumAndDiscountTest()
{
var saleId = Guid.NewGuid().ToString();
var employeeId = Guid.NewGuid().ToString();
var clientId = Guid.NewGuid().ToString();
var cocktails = new List<SaleCocktailDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 2, 1.1),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 1.3)
};
var isCancel = false;
var totalSum = cocktails.Sum(x => x.Price * x.Count);
var saleNone = CreateDataModel(saleId, employeeId, clientId, DiscountType.None, isCancel, cocktails);
Assert.Multiple(() =>
{
Assert.That(saleNone.Sum, Is.EqualTo(totalSum));
Assert.That(saleNone.Discount, Is.EqualTo(0));
});
var saleOnSale = CreateDataModel(saleId, employeeId, clientId, DiscountType.OnSale, isCancel, cocktails);
Assert.Multiple(() =>
{
Assert.That(saleOnSale.Sum, Is.EqualTo(totalSum));
Assert.That(saleOnSale.Discount, Is.EqualTo(totalSum * 0.1));
});
var saleRegularCustomer = CreateDataModel(saleId, employeeId, clientId, DiscountType.RegularCustomer, isCancel, cocktails);
Assert.Multiple(() =>
{
Assert.That(saleRegularCustomer.Sum, Is.EqualTo(totalSum));
Assert.That(saleRegularCustomer.Discount, Is.EqualTo(totalSum * 0.5));
});
var saleCertificate = CreateDataModel(saleId, employeeId, clientId, DiscountType.Certificate, isCancel, cocktails);
Assert.Multiple(() =>
{
Assert.That(saleCertificate.Sum, Is.EqualTo(totalSum));
Assert.That(saleCertificate.Discount, Is.EqualTo(totalSum * 0.3));
});
var saleMulty = CreateDataModel(saleId, employeeId, clientId, DiscountType.Certificate | DiscountType.RegularCustomer, isCancel, cocktails);
Assert.Multiple(() =>
{
Assert.That(saleMulty.Sum, Is.EqualTo(totalSum));
Assert.That(saleMulty.Discount, Is.EqualTo(totalSum * 0.8));
});
}
[Test]
public void AllFieldsIsCorrectTest()
{
var saleId = Guid.NewGuid().ToString();
var employeeId = Guid.NewGuid().ToString();
var clientId = Guid.NewGuid().ToString();
var sum = 10;
var discountType = DiscountType.Certificate;
var discount = 1;
var isCancel = true;
var cocktails = CreateSubDataModel();
var sale = CreateDataModel(saleId, employeeId, clientId, sum, discountType, discount, isCancel, cocktails);
var sale = CreateDataModel(saleId, employeeId, clientId, discountType, isCancel, cocktails);
Assert.That(() => sale.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(sale.Id, Is.EqualTo(saleId));
Assert.That(sale.EmployeeId, Is.EqualTo(employeeId));
Assert.That(sale.ClientId, Is.EqualTo(clientId));
Assert.That(sale.Sum, Is.EqualTo(sum));
Assert.That(sale.DiscountType, Is.EqualTo(discountType));
Assert.That(sale.Discount, Is.EqualTo(discount));
Assert.That(sale.IsCancel, Is.EqualTo(isCancel));
Assert.That(sale.Cocktails, Is.EquivalentTo(cocktails));
});
}
private static SaleDataModel CreateDataModel(string? id, string? employeeId, string? clientId, double sum, DiscountType discountType, double discount, bool isCancel, List<SaleCocktailDataModel>? cocktails) =>
new(id, employeeId, clientId, sum, discountType, discount, isCancel, cocktails);
private static SaleDataModel CreateDataModel(string? id, string? employeeId, string? clientId, DiscountType discountType, bool isCancel, List<SaleCocktailDataModel>? cocktails) =>
new(id, employeeId, clientId, discountType, isCancel, cocktails);
private static List<SaleCocktailDataModel> CreateSubDataModel()
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)];
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 1.1)];
}

View File

@@ -0,0 +1,68 @@
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
namespace SquirrelTests.DataModelsTests;
[TestFixture]
internal class SupplyCocktailDataModelTests
{
[Test]
public void SupplyIdIsNullOrEmptyTest()
{
var supplyCocktail = CreateDataModel(null, Guid.NewGuid().ToString(), 10);
Assert.That(() => supplyCocktail.Validate(), Throws.TypeOf<ValidationException>());
supplyCocktail = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10);
Assert.That(() => supplyCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void SupplyIdIsNotGuidTest()
{
var supplyCocktail = CreateDataModel("SupplyId", Guid.NewGuid().ToString(), 10);
Assert.That(() => supplyCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CocktailIdIsNullOrEmptyTest()
{
var supplyCocktail = CreateDataModel(Guid.NewGuid().ToString(), null, 10);
Assert.That(() => supplyCocktail.Validate(), Throws.TypeOf<ValidationException>());
supplyCocktail = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, 10);
Assert.That(() => supplyCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CocktailIdIsNotGuidTest()
{
var supplyCocktail = CreateDataModel(Guid.NewGuid().ToString(), "ComponentId", 10);
Assert.That(() => supplyCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CountIsLessOrZeroTest()
{
var supplyCocktail = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0);
Assert.That(() => supplyCocktail.Validate(), Throws.TypeOf<ValidationException>());
supplyCocktail = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -10);
Assert.That(() => supplyCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var cocktailId = Guid.NewGuid().ToString();
var supplyId = Guid.NewGuid().ToString();
var count = 5;
var supplyCocktail = CreateDataModel(supplyId, cocktailId, count);
Assert.That(() => supplyCocktail.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(supplyCocktail.SupplyId, Is.EqualTo(supplyId));
Assert.That(supplyCocktail.CocktailId, Is.EqualTo(cocktailId));
Assert.That(supplyCocktail.Count, Is.EqualTo(count));
});
}
private static SupplyCocktailDataModel CreateDataModel(string? supplyId, string? cocktailId, int count) =>
new(supplyId, cocktailId, count);
}

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