Compare commits

..

33 Commits

Author SHA1 Message Date
a0e1b0d14d мелкие исправления 2025-04-20 11:49:18 +04:00
741fccb38a тесты и не только 2025-04-14 19:55:32 +04:00
59aaa5cb04 до тестов 2025-04-13 14:32:05 +04:00
47c8badaa0 корректировка 2025-04-09 14:53:23 +04:00
2cbfda6122 объединение 2025-04-09 14:49:29 +04:00
ac4aa4a146 правки 2025-04-08 14:27:46 +04:00
135619e512 исправлени, наконец то 4 работает, УРААААА 2025-04-08 14:09:53 +04:00
400faf460a правки 2025-04-05 15:06:24 +04:00
618bc7f639 исправлние в storage тестах 2025-04-05 14:07:48 +04:00
7a0fcca7b1 корректировка 2025-03-26 20:37:20 +04:00
ea790d5d17 контракты для agency и supplies 2025-03-26 18:02:17 +04:00
ce473a3725 корректировка моделей 2025-03-26 18:01:40 +04:00
1475434fef изменения в тестах 2025-03-26 18:01:32 +04:00
0df46ec709 перенос из 3 лабы 2025-03-26 16:01:32 +04:00
0a00160b2f предварительно 2025-03-26 15:56:11 +04:00
96b01aeedf правки 2025-03-26 10:27:16 +04:00
770bf77797 salary добавлено. тесты ну как бы позже 2025-03-25 23:02:13 +04:00
6658ada87a тесты контроллеров 2025-03-25 18:06:47 +04:00
6a14c33a91 web api 2025-03-25 18:06:26 +04:00
a9142a8b38 вью модели и изменения в моделях 2025-03-25 18:06:09 +04:00
42c509fa72 биндинг модели 2025-03-25 18:05:40 +04:00
eb4c1f037b измнения в моделяз и котрактах хранилищ 2025-03-25 18:05:09 +04:00
ed32c34921 контроллеры 2025-03-25 18:04:29 +04:00
3a9c533507 адаптеры 2025-03-25 18:04:21 +04:00
5097441b78 корректировка бизнес логики 2025-03-25 18:03:51 +04:00
39dada6bca изменение безнес логики при нехватке продукта 2025-03-17 18:56:45 +04:00
f7b2442b3e полная перестройка логики и тестов, зато работает 2025-03-12 16:37:27 +04:00
9e9cfe3adf правки правки.... 2025-03-12 10:49:38 +04:00
da93722d9f Добавление интерфейсов и логики для пополнения и агенства 2025-03-03 18:09:18 +04:00
43dc07e662 Merge branch 'lab02_BuisnessLogic' into lab02_BuisnessLogic_Hard 2025-03-03 17:24:49 +04:00
ddb84536c0 поправка 2025-02-26 17:18:05 +04:00
ec2eea3184 правки 2025-02-14 13:11:44 +04:00
b7cb388d19 Усложненная лабораторная 2025-02-10 16:29:49 +04:00
155 changed files with 9445 additions and 465 deletions

View File

@@ -0,0 +1,74 @@
using MagicCarpetContracts.BusinessLogicContracts;
using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Enums;
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.Extensions;
using MagicCarpetContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace MagicCarpetBusinessLogic.Implementations;
public class AgencyBusinessLogicContract(IAgencyStorageContract agencyStorageContract, ILogger logger) : IAgencyBusinessLogicContract
{
private readonly IAgencyStorageContract _agencyStorageContract = agencyStorageContract;
private readonly ILogger _logger = logger;
public List<AgencyDataModel> GetAllComponents()
{
_logger.LogInformation("GetAllComponents");
return _agencyStorageContract.GetList() ?? throw new NullListException();
return [];
}
public AgencyDataModel GetComponentByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (!data.IsGuid())
{
throw new ElementNotFoundException(data);
}
return _agencyStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return new("", TourType.None, 0, []);
}
public void InsertComponent(AgencyDataModel agencyDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(agencyDataModel));
ArgumentNullException.ThrowIfNull(agencyDataModel);
agencyDataModel.Validate();
_agencyStorageContract.AddElement(agencyDataModel);
}
public void UpdateComponent(AgencyDataModel agencyDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(agencyDataModel));
ArgumentNullException.ThrowIfNull(agencyDataModel);
agencyDataModel.Validate();
_agencyStorageContract.UpdElement(agencyDataModel);
}
public void DeleteComponent(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");
}
_agencyStorageContract.DelElement(id);
}
}

View File

@@ -14,7 +14,7 @@ using System.Threading.Tasks;
namespace MagicCarpetBusinessLogic.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

@@ -14,7 +14,7 @@ using System.Threading.Tasks;
namespace MagicCarpetBusinessLogic.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

@@ -12,14 +12,14 @@ using System.Text.Json;
using System.Threading.Tasks;
namespace MagicCarpetBusinessLogic.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

@@ -11,7 +11,7 @@ using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetBusinessLogic.Implementations;
internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract,ISaleStorageContract saleStorageContract,
public class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract,ISaleStorageContract saleStorageContract,
IPostStorageContract postStorageContract, IEmployeeStorageContract employeeStorageContract, ILogger logger) : ISalaryBusinessLogicContract
{
private readonly ILogger _logger = logger;
@@ -61,7 +61,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

@@ -13,10 +13,11 @@ using System.Threading.Tasks;
namespace MagicCarpetBusinessLogic.Implementations;
internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContract, ILogger logger) : ISaleBusinessLogicContract
public class SaleBusinessLogicContract(ISaleStorageContract saleStorageContract,IAgencyStorageContract agencyStorageContract, ILogger logger) : ISaleBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
private readonly IAgencyStorageContract _agencyStorageContract = agencyStorageContract;
public List<SaleDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate)
{
@@ -101,6 +102,10 @@ internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContrac
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(saleDataModel));
ArgumentNullException.ThrowIfNull(saleDataModel);
saleDataModel.Validate();
if (!_agencyStorageContract.CheckComponents(saleDataModel))
{
throw new InsufficientException("Dont have tour in agency");
}
_saleStorageContract.AddElement(saleDataModel);
}

View File

@@ -0,0 +1,61 @@
using MagicCarpetContracts.BusinessLogicContracts;
using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Enums;
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.Extensions;
using MagicCarpetContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace MagicCarpetBusinessLogic.Implementations;
public class SuppliesBusinessLogicContract(ISuppliesStorageContract suppliesStorageContract, ILogger logger) : ISuppliesBusinessLogicContract
{
private readonly ISuppliesStorageContract _suppliesStorageContract = suppliesStorageContract;
private readonly ILogger _logger = logger;
public List<SuppliesDataModel> GetAllComponents()
{
_logger.LogInformation("GetAllComponents");
return _suppliesStorageContract.GetList() ?? throw new NullListException();
return [];
}
public SuppliesDataModel GetComponentByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (!data.IsGuid())
{
throw new ElementNotFoundException(data);
}
return _suppliesStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return new("", TourType.None, DateTime.UtcNow, 0, []);
}
public void InsertComponent(SuppliesDataModel suppliesDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(suppliesDataModel));
ArgumentNullException.ThrowIfNull(suppliesDataModel);
suppliesDataModel.Validate();
_suppliesStorageContract.AddElement(suppliesDataModel);
}
public void UpdateComponent(SuppliesDataModel suppliesDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(suppliesDataModel));
ArgumentNullException.ThrowIfNull(suppliesDataModel);
suppliesDataModel.Validate();
_suppliesStorageContract.UpdElement(suppliesDataModel);
}
}

View File

@@ -13,7 +13,7 @@ using System.Threading.Tasks;
namespace MagicCarpetBusinessLogic.Implementations;
internal class TourBusinessLogicContract(ITourStorageContract tourStorageContract, ILogger logger) : ITourBusinessLogicContract
public class TourBusinessLogicContract(ITourStorageContract tourStorageContract, ILogger logger) : ITourBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ITourStorageContract _tourStorageContract = tourStorageContract;
@@ -56,7 +56,6 @@ internal class TourBusinessLogicContract(ITourStorageContract tourStorageContrac
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(tourDataModel));
ArgumentNullException.ThrowIfNull(tourDataModel);
tourDataModel.Validate();
_tourStorageContract.AddElement(tourDataModel);
}
public void UpdateTour(TourDataModel tourDataModel)
@@ -64,7 +63,6 @@ internal class TourBusinessLogicContract(ITourStorageContract tourStorageContrac
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(tourDataModel));
ArgumentNullException.ThrowIfNull(tourDataModel);
tourDataModel.Validate();
_tourStorageContract.UpdElement(tourDataModel);
}
public void DeleteTour(string id)

View File

@@ -7,6 +7,7 @@
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="MagicCarpetTests" />
<InternalsVisibleTo Include="MagicCarpetWebApi" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
<ItemGroup>

View File

@@ -0,0 +1,18 @@
using MagicCarpetContracts.AdapterContracts.OperationResponses;
using MagicCarpetContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.AdapterContracts;
public interface IAgencyAdapter
{
AgencyOperationResponse GetAllComponents();
AgencyOperationResponse GetComponentByData(string data);
AgencyOperationResponse InsertComponent(AgencyBindingModel warehouseDataModel);
AgencyOperationResponse UpdateComponent(AgencyBindingModel warehouseDataModel);
AgencyOperationResponse DeleteComponent(string id);
}

View File

@@ -0,0 +1,22 @@
using MagicCarpetContracts.AdapterContracts.OperationResponses;
using MagicCarpetContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.AdapterContracts;
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,28 @@
using MagicCarpetContracts.AdapterContracts.OperationResponses;
using MagicCarpetContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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,26 @@
using MagicCarpetContracts.AdapterContracts.OperationResponses;
using MagicCarpetContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.AdapterContracts;
public interface IPostAdapter
{
PostOperationResponse GetList();
PostOperationResponse GetHistory(string id);
PostOperationResponse GetElement(string data);
PostOperationResponse RegisterPost(PostBindingModel postModel);
PostOperationResponse ChangePostInfo(PostBindingModel postModel);
PostOperationResponse RemovePost(string id);
PostOperationResponse RestorePost(string id);
}

View File

@@ -0,0 +1,15 @@
using MagicCarpetContracts.AdapterContracts.OperationResponses;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.AdapterContracts;
public interface ISalaryAdapter
{
SalaryOperationResponse GetListByPeriod(DateTime fromDate, DateTime toDate);
SalaryOperationResponse GetListByPeriodByEmployee(DateTime fromDate, DateTime toDate, string employeeId);
SalaryOperationResponse CalculateSalary(DateTime date);
}

View File

@@ -0,0 +1,26 @@
using MagicCarpetContracts.AdapterContracts.OperationResponses;
using MagicCarpetContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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 GetTourList(string id, DateTime fromDate, DateTime toDate);
SaleOperationResponse GetElement(string id);
SaleOperationResponse MakeSale(SaleBindingModel saleModel);
SaleOperationResponse CancelSale(string id);
}

View File

@@ -0,0 +1,17 @@
using MagicCarpetContracts.AdapterContracts.OperationResponses;
using MagicCarpetContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.AdapterContracts;
public interface ISuppliesAdapter
{
SuppliesOperationResponse GetAllComponents();
SuppliesOperationResponse GetComponentByData(string data);
SuppliesOperationResponse InsertComponent(SuppliesBindingModel componentDataModel);
SuppliesOperationResponse UpdateComponent(SuppliesBindingModel componentDataModel);
}

View File

@@ -0,0 +1,24 @@
using MagicCarpetContracts.AdapterContracts.OperationResponses;
using MagicCarpetContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.AdapterContracts;
public interface ITourAdapter
{
TourOperationResponse GetList(bool includeDeleted);
TourOperationResponse GetHistory(string id);
TourOperationResponse GetElement(string data);
TourOperationResponse RegisterTour(TourBindingModel tourModel);
TourOperationResponse ChangeTourInfo(TourBindingModel tourModel);
TourOperationResponse RemoveTour(string id);
}

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,24 @@
using MagicCarpetContracts.Infrastructure;
using MagicCarpetContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.AdapterContracts.OperationResponses;
public class SuppliesOperationResponse : OperationResponse
{
public static SuppliesOperationResponse OK(List<SuppliesViewModel> data) => OK<SuppliesOperationResponse, List<SuppliesViewModel>>(data);
public static SuppliesOperationResponse OK(SuppliesViewModel data) => OK<SuppliesOperationResponse, SuppliesViewModel>(data);
public static SuppliesOperationResponse NoContent() => NoContent<SuppliesOperationResponse>();
public static SuppliesOperationResponse NotFound(string message) => NotFound<SuppliesOperationResponse>(message);
public static SuppliesOperationResponse BadRequest(string message) => BadRequest<SuppliesOperationResponse>(message);
public static SuppliesOperationResponse InternalServerError(string message) => InternalServerError<SuppliesOperationResponse>(message);
}

View File

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

View File

@@ -0,0 +1,16 @@
using MagicCarpetContracts.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.BindingModels;
public class AgencyBindingModel
{
public string? Id { get; set; }
public TourType? TourType { get; set; }
public int Count { get; set; }
public List<TourAgencyBindingModel>? Tours { get; set; }
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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<SaleTourBindingModel>? Tours { get; set; }
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.BindingModels;
public class SaleTourBindingModel
{
public string? SaleId { get; set; }
public string? TourId { get; set; }
public int Count { get; set; }
public double Price { get; set; }
}

View File

@@ -0,0 +1,17 @@
using MagicCarpetContracts.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.BindingModels;
public class SuppliesBindingModel
{
public string? Id { get; set; }
public TourType? TourType { get; set; }
public DateTime ProductuionDate { get; set; }
public int Count { get; set; }
public List<TourSuppliesBindingModel>? Tours { get; set; }
}

View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.BindingModels;
public class TourAgencyBindingModel
{
public string? AgencyId { get; set; }
public string? TourId { get; set; }
public int Count { get; set; }
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.BindingModels;
public class TourBindingModel
{
public string? Id { get; set; }
public string? TourName { get; set; }
public string? TourCountry { get; set; }
public double Price { get; set; }
public string? TourType { get; set; }
}

View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.BindingModels;
public class TourSuppliesBindingModel
{
public string? SuppliesId { get; set; }
public string? TourId { get; set; }
public int Count { get; set; }
}

View File

@@ -0,0 +1,17 @@
using MagicCarpetContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.BusinessLogicContracts;
public interface IAgencyBusinessLogicContract
{
List<AgencyDataModel> GetAllComponents();
AgencyDataModel GetComponentByData(string data);
void InsertComponent(AgencyDataModel agencyDataModel);
void UpdateComponent(AgencyDataModel agencyDataModel);
void DeleteComponent(string id);
}

View File

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

View File

@@ -0,0 +1,16 @@
using MagicCarpetContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.BusinessLogicContracts;
public interface ISuppliesBusinessLogicContract
{
List<SuppliesDataModel> GetAllComponents();
SuppliesDataModel GetComponentByData(string data);
void InsertComponent(SuppliesDataModel componentDataModel);
void UpdateComponent(SuppliesDataModel componentDataModel);
}

View File

@@ -0,0 +1,33 @@
using MagicCarpetContracts.Enums;
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.Extensions;
using MagicCarpetContracts.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.DataModels;
public class AgencyDataModel(string id, TourType tourType, int count, List<TourAgencyDataModel> tours) : IValidation
{
public string Id { get; private set; } = id;
public TourType TourType { get; private set; } = tourType;
public int Count { get; private set; } = count;
public List<TourAgencyDataModel> Tours { get; private set; } = tours;
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 (TourType == TourType.None)
throw new ValidationException("Field Type is empty");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
if ((Tours?.Count ?? 0) == 0)
throw new ValidationException("The sale must include tours");
}
}

View File

@@ -1,6 +1,7 @@
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.Extensions;
using MagicCarpetContracts.Infrastructure;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -12,6 +13,8 @@ namespace MagicCarpetContracts.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;
@@ -26,6 +29,17 @@ 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

@@ -10,14 +10,12 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.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;
public PostType PostType { get; private set; } = postType;
public double Salary { get; private set; } = salary;
public bool IsActual { get; private set; } = isActual;
public DateTime ChangeDate { get; private set; } = changeDate;
public void Validate()
{

View File

@@ -11,12 +11,20 @@ namespace MagicCarpetContracts.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

@@ -10,25 +10,78 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.DataModels;
public class SaleDataModel(string id, string employeeId, string? clientId, double sum, DiscountType discountType,
double discount, bool isCancel, List<SaleTourDataModel> saleTours) : 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 DiscountType DiscountType { get; private set; } = discountType;
public double Sum { get; private set; }
public double Discount { get; private set; } = discount;
public DiscountType DiscountType { get; private set; }
public bool IsCancel { get; private set; } = isCancel;
public double Discount { get; private set; }
public List<SaleTourDataModel> Tours { get; private set; } = saleTours;
public bool IsCancel { get; private set; }
public List<SaleTourDataModel>? Tours { 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<SaleTourDataModel> saleTours)
{
Id = id;
EmployeeId = employeeId;
ClientId = clientId;
DiscountType = discountType;
IsCancel = isCancel;
Tours = saleTours;
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 = Tours?.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<SaleTourDataModel> saleTours, EmployeeDataModel employee, ClientDataModel? client) : this(id, employeeId, clientId, discountType, isCancel, saleTours)
{
Sum = sum;
Discount = discount;
_employee = employee;
_client = client;
}
public SaleDataModel(string id, string employeeId, string? clientId, int discountType,
List<SaleTourDataModel> tours) : this(id, employeeId, clientId, (DiscountType)discountType, false, tours) { }
public void Validate()
{

View File

@@ -3,20 +3,32 @@ using MagicCarpetContracts.Extensions;
using MagicCarpetContracts.Infrastructure;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.DataModels;
public class SaleTourDataModel(string saleId, string tourId, int count) : IValidation
public class SaleTourDataModel(string saleId, string tourId, int count, double price) : IValidation
{
private readonly TourDataModel? _tour;
public string SaleId { get; private set; } = saleId;
public string TourId { get; private set; } = tourId;
public int Count { get; private set; } = count;
public double Price { get; private set; } = price;
public string TourName => _tour?.TourName ?? string.Empty;
public SaleTourDataModel(string saleId, string tourId, int count, double price, TourDataModel tour) : this(saleId, tourId, count, price)
{
_tour = tour;
}
public void Validate()
{
if (SaleId.IsEmpty())
@@ -33,5 +45,8 @@ public class SaleTourDataModel(string saleId, string tourId, int count) : IValid
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

@@ -0,0 +1,35 @@
using MagicCarpetContracts.Enums;
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.Extensions;
using MagicCarpetContracts.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace MagicCarpetContracts.DataModels;
public class SuppliesDataModel(string id, TourType tourType, DateTime productuionDate, int count, List<TourSuppliesDataModel> tours) : IValidation
{
public string Id { get; private set; } = id;
public TourType TourType { get; private set; } = tourType;
public DateTime ProductuionDate { get; private set; } = productuionDate;
public int Count { get; private set; } = count;
public List<TourSuppliesDataModel> Tours { get; private set; } = tours;
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 (TourType == TourType.None)
throw new ValidationException("Field Type is empty");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
if ((Tours?.Count ?? 0) == 0)
throw new ValidationException("The sale must include tours");
}
}

View File

@@ -0,0 +1,32 @@
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.Extensions;
using MagicCarpetContracts.Infrastructure;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.DataModels;
public class TourAgencyDataModel(string agencyId, string tourId, int count) : IValidation
{
public string AgencyId { get; private set; } = agencyId;
public string TourId { get; private set; } = tourId;
public int Count { get; private set; } = count;
public void Validate()
{
if (AgencyId.IsEmpty())
throw new ValidationException("Field AgencyId is empty");
if (!AgencyId.IsGuid())
throw new ValidationException("The value in the field AgencyId is not a unique identifier");
if (TourId.IsEmpty())
throw new ValidationException("Field TourId is empty");
if (!TourId.IsGuid())
throw new ValidationException("The value in the field TourId is not a unique identifier");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
}
}

View File

@@ -18,7 +18,7 @@ public class TourDataModel(string id, string tourName, string tourCountry, doubl
public string TourName { get; private set; } = tourName;
public string TourCountry { get; private set; } = tourCountry;
public double Price { get; private set; } = price;
public TourType Type { get; private set; } = tourType;
public TourType TourType { get; private set; } = tourType;
public void Validate()
{
@@ -32,7 +32,7 @@ public class TourDataModel(string id, string tourName, string tourCountry, doubl
throw new ValidationException("Field TourCountry is empty");
if (Price <= 0)
throw new ValidationException("Field Price is less than or equal to 0");
if (Type == TourType.None)
if (TourType == TourType.None)
throw new ValidationException("Field Type is empty");
}
}

View File

@@ -11,12 +11,22 @@ namespace MagicCarpetContracts.DataModels;
public class TourHistoryDataModel(string tourId, double oldPrice) : IValidation
{
private readonly TourDataModel? _tour;
public string TourId { get; private set; } = tourId;
public double OldPrice { get; private set; } = oldPrice;
public DateTime ChangeDate { get; private set; } = DateTime.UtcNow;
public string TourName => _tour?.TourName ?? string.Empty;
public TourHistoryDataModel(string tourId, double oldPrice, DateTime changeDate, TourDataModel tour) : this(tourId, oldPrice)
{
ChangeDate = changeDate;
_tour = tour;
}
public void Validate()
{
if (TourId.IsEmpty())

View File

@@ -0,0 +1,32 @@
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.Extensions;
using MagicCarpetContracts.Infrastructure;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.DataModels;
public class TourSuppliesDataModel(string suppliesId, string tourId, int count) : IValidation
{
public string SuppliesId { get; private set; } = suppliesId;
public string TourId { get; private set; } = tourId;
public int Count { get; private set; } = count;
public void Validate()
{
if (SuppliesId.IsEmpty())
throw new ValidationException("Field SuppliesId is empty");
if (!SuppliesId.IsGuid())
throw new ValidationException("The value in the field SuppliesId is not a unique identifier");
if (TourId.IsEmpty())
throw new ValidationException("Field TourId is empty");
if (!TourId.IsGuid())
throw new ValidationException("The value in the field BlandId 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,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.Exceptions;
public class InsufficientException(string message) : Exception(message)
{
}

View File

@@ -0,0 +1,47 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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,10 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.3.0" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,18 @@
using MagicCarpetContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.StoragesContracts;
public interface IAgencyStorageContract
{
List<AgencyDataModel> GetList();
AgencyDataModel GetElementById(string id);
void AddElement(AgencyDataModel agencyDataModel);
void UpdElement(AgencyDataModel agencyDataModel);
void DelElement(string id);
bool CheckComponents(SaleDataModel saleDataModel);
}

View File

@@ -9,7 +9,7 @@ namespace MagicCarpetContracts.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

@@ -9,7 +9,7 @@ namespace MagicCarpetContracts.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,16 @@
using MagicCarpetContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.StoragesContracts;
public interface ISuppliesStorageContract
{
List<SuppliesDataModel> GetList(DateTime? startDate = null);
SuppliesDataModel GetElementById(string id);
void AddElement(SuppliesDataModel suppliesDataModel);
void UpdElement(SuppliesDataModel suppliesDataModel);
}

View File

@@ -0,0 +1,16 @@
using MagicCarpetContracts.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.ViewModels;
public class AgencyViewModel
{
public required string Id { get; set; }
public required TourType TourType { get; set; }
public required int Count { get; set; }
public required List<TourAgencyViewModel> Tours { get; set; }
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.ViewModels;
public class PostViewModel
{
public required string Id { get; set; }
public required string PostName { get; set; }
public required string PostType { get; set; }
public double Salary { get; set; }
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.ViewModels;
public class SaleTourViewModel
{
public required string TourId { get; set; }
public required string TourName { get; set; }
public int Count { get; set; }
public double Price { get; set; }
}

View File

@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.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<SaleTourViewModel> Tours { get; set; }
}

View File

@@ -0,0 +1,17 @@
using MagicCarpetContracts.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.ViewModels;
public class SuppliesViewModel
{
public required string Id { get; set; }
public required TourType TourType { get; set; }
public DateTime ProductuionDate { get; set; }
public int Count { get; set; }
public required List<TourSuppliesViewModel> Tours { get; set; }
}

View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.ViewModels;
public class TourAgencyViewModel
{
public required string AgencyId { get; set; }
public required string TourId { get; set; }
public int Count { get; set; }
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.ViewModels;
public class TourHistoryViewModel
{
public required string TourName { get; set; }
public double OldPrice { get; set; }
public DateTime ChangeDate { get; set; }
}

View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.ViewModels;
public class TourSuppliesViewModel
{
public required string SuppliesId { get; set; }
public required string TourId { get; set; }
public int Count { get; set; }
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.ViewModels;
public class TourViewModel
{
public required string Id { get; set; }
public required string TourName { get; set; }
public required string TourType { get; set; }
public string? TourCountry { get; set; }
public double Price { get; set; }
}

View File

@@ -0,0 +1,140 @@
using AutoMapper;
using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.StoragesContracts;
using MagicCarpetDatabase.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetDatabase.Implementations;
public class AgencyStorageContract : IAgencyStorageContract
{
private readonly MagicCarpetDbContext _dbContext;
private readonly Mapper _mapper;
public AgencyStorageContract(MagicCarpetDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(TourAgency));
cfg.AddMaps(typeof(Agency));
});
_mapper = new Mapper(config);
}
public List<AgencyDataModel> GetList()
{
try
{
return [.. _dbContext.Agencies.Select(x => _mapper.Map<AgencyDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public AgencyDataModel GetElementById(string id)
{
try
{
return _mapper.Map<AgencyDataModel>(GetAgencyById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(AgencyDataModel agencyDataModel)
{
try
{
_dbContext.Agencies.Add(_mapper.Map<Agency>(agencyDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(AgencyDataModel agencyDataModel)
{
try
{
var element = GetAgencyById(agencyDataModel.Id) ?? throw new ElementNotFoundException(agencyDataModel.Id);
_dbContext.Agencies.Update(_mapper.Map(agencyDataModel, 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 = GetAgencyById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Agencies.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public bool CheckComponents(SaleDataModel saleDataModel)
{
using (var transaction = _dbContext.Database.BeginTransaction())
{
foreach (SaleTourDataModel sale_tour in saleDataModel.Tours)
{
var tour = _dbContext.Tours.FirstOrDefault(x => x.Id == sale_tour.TourId);
var agency = _dbContext.Agencies.FirstOrDefault(x => x.TourType == tour.TourType && x.Count >= sale_tour.Count);
if (agency == null)
{
transaction.Rollback();
return false;
}
if (agency.Count - sale_tour.Count == 0)
{
DelElement(agency.Id);
}
else
{
agency.Count -= sale_tour.Count;
}
}
transaction.Commit();
_dbContext.SaveChanges();
return true;
}
}
private Agency? GetAgencyById(string id) => _dbContext.Agencies.FirstOrDefault(x => x.Id == id);
}

View File

@@ -13,11 +13,11 @@ using System.Threading.Tasks;
namespace MagicCarpetDatabase.Implementations;
internal class ClientStorageContarct : IClientStorageContract
public class ClientStorageContract : IClientStorageContract
{
private readonly MagicCarpetDbContext _dbContext;
private readonly Mapper _mapper;
public ClientStorageContarct(MagicCarpetDbContext magicCarpetDbContext)
public ClientStorageContract(MagicCarpetDbContext magicCarpetDbContext)
{
_dbContext = magicCarpetDbContext;
var config = new MapperConfiguration(cfg =>

View File

@@ -11,7 +11,7 @@ using System.Threading.Tasks;
namespace MagicCarpetDatabase.Implementations;
internal class EmployeeStorageContract : IEmployeeStorageContract
public class EmployeeStorageContract : IEmployeeStorageContract
{
private readonly MagicCarpetDbContext _dbContext;
private readonly Mapper _mapper;
@@ -21,10 +21,14 @@ internal class EmployeeStorageContract : IEmployeeStorageContract
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(MagicCarpetDbContext).Assembly);
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
@@ -40,13 +44,13 @@ internal class EmployeeStorageContract : IEmployeeStorageContract
}
if (fromBirthDate is not null && toBirthDate is not null)
{
query = query.Where(x => x.BirthDate >= fromBirthDate && x.BirthDate <= toBirthDate);
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 >= fromEmploymentDate && x.EmploymentDate <= toEmploymentDate);
query = query.Where(x => x.EmploymentDate >= DateTime.SpecifyKind(fromEmploymentDate ?? DateTime.UtcNow, DateTimeKind.Utc) && x.EmploymentDate <= DateTime.SpecifyKind(toEmploymentDate ?? DateTime.UtcNow, DateTimeKind.Utc));
}
return [.. query.Select(x => _mapper.Map<EmployeeDataModel>(x))];
return [.. JoinPost(query).Select(x => _mapper.Map<EmployeeDataModel>(x))];
}
catch (Exception ex)
{
@@ -72,7 +76,7 @@ internal class EmployeeStorageContract : IEmployeeStorageContract
{
try
{
return _mapper.Map<EmployeeDataModel>(_dbContext.Employees.FirstOrDefault(x => x.FIO == fio));
return _mapper.Map<EmployeeDataModel>(AddPost(_dbContext.Employees.FirstOrDefault(x => x.FIO == fio && !x.IsDeleted)));
}
catch (Exception ex)
{
@@ -80,11 +84,12 @@ internal class EmployeeStorageContract : IEmployeeStorageContract
throw new StorageException(ex);
}
}
public EmployeeDataModel? GetElementByEmail(string email)
{
try
{
return _mapper.Map<EmployeeDataModel>(_dbContext.Employees.FirstOrDefault(x => x.Email == email));
return _mapper.Map<EmployeeDataModel>(AddPost(_dbContext.Employees.FirstOrDefault(x => x.Email == email && !x.IsDeleted)));
}
catch (Exception ex)
{
@@ -152,5 +157,12 @@ internal class EmployeeStorageContract : IEmployeeStorageContract
}
}
private Employee? GetEmployeeById(string id) => _dbContext.Employees.FirstOrDefault(x => x.Id == id && !x.IsDeleted);
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

@@ -13,7 +13,7 @@ using System.Threading.Tasks;
namespace MagicCarpetDatabase.Implementations;
internal class PostStorageContract : IPostStorageContract
public class PostStorageContract : IPostStorageContract
{
private readonly MagicCarpetDbContext _dbContext;
private readonly Mapper _mapper;
@@ -34,16 +34,11 @@ internal class PostStorageContract : IPostStorageContract
_mapper = new Mapper(config);
}
public List<PostDataModel> GetList(bool onlyActual = true)
public List<PostDataModel> GetList()
{
try
{
var query = _dbContext.Posts.AsQueryable();
if (onlyActual)
{
query = query.Where(x => x.IsActual);
}
return [.. query.Select(x => _mapper.Map<PostDataModel>(x))];
return [.. _dbContext.Posts.Select(x => _mapper.Map<PostDataModel>(x))];
}
catch (Exception ex)
{

View File

@@ -3,6 +3,7 @@ using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.StoragesContracts;
using MagicCarpetDatabase.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -11,7 +12,7 @@ using System.Threading.Tasks;
namespace MagicCarpetDatabase.Implementations;
internal class SalaryStorageContract : ISalaryStorageContract
public class SalaryStorageContract : ISalaryStorageContract
{
private readonly MagicCarpetDbContext _dbContext;
private readonly Mapper _mapper;
@@ -21,6 +22,7 @@ internal class SalaryStorageContract : ISalaryStorageContract
_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));
@@ -28,15 +30,17 @@ internal class SalaryStorageContract : ISalaryStorageContract
_mapper = new Mapper(config);
}
public List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? employeeId = null)
public List<SalaryDataModel> GetList(DateTime? startDate, DateTime? endDate, string? employeeId = null)
{
try
{
var query = _dbContext.Salaries.Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate);
if (employeeId is not null)
{
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)

View File

@@ -12,7 +12,7 @@ using System.Threading.Tasks;
namespace MagicCarpetDatabase.Implementations;
internal class SaleStorageContract : ISaleStorageContract
public class SaleStorageContract : ISaleStorageContract
{
private readonly MagicCarpetDbContext _dbContext;
private readonly Mapper _mapper;
@@ -22,12 +22,18 @@ internal class SaleStorageContract : ISaleStorageContract
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Client, ClientDataModel>();
cfg.CreateMap<Tour, TourDataModel>();
cfg.CreateMap<Employee, EmployeeDataModel>();
cfg.CreateMap<SaleTour, SaleTourDataModel>();
cfg.CreateMap<SaleTourDataModel, SaleTour>();
cfg.CreateMap<SaleTourDataModel, SaleTour>()
.ForMember(x => x.Tour, x => x.Ignore());
cfg.CreateMap<Sale, SaleDataModel>();
cfg.CreateMap<SaleDataModel, Sale>()
.ForMember(x => x.IsCancel, x => x.MapFrom(src => false))
.ForMember(x => x.SaleTours, x => x.MapFrom(src => src.Tours));
.ForMember(x => x.SaleTours, x => x.MapFrom(src => src.Tours))
.ForMember(x => x.Employee, x => x.Ignore())
.ForMember(x => x.Client, x => x.Ignore());
});
_mapper = new Mapper(config);
}
@@ -36,23 +42,23 @@ internal class SaleStorageContract : ISaleStorageContract
{
try
{
var query = _dbContext.Sales.Include(x => x.SaleTours).AsQueryable();
if (startDate is not null && endDate is not null)
{
query = query.Where(x => x.SaleDate >= startDate && x.SaleDate < endDate);
}
if (employeeId is not null)
{
var query = _dbContext.Sales
.Include(r => r.Employee)
.Include(r => r.Client)
.Include(r => r.SaleTours)!
.ThenInclude(d => d.Tour)
.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 is not null)
{
if (clientId != null)
query = query.Where(x => x.ClientId == clientId);
}
if (tourId is not null)
{
if (tourId != null)
query = query.Where(x => x.SaleTours!.Any(y => y.TourId == tourId));
}
var s = query.ToList();
return [.. query.Select(x => _mapper.Map<SaleDataModel>(x))];
}
catch (Exception ex)
@@ -113,5 +119,5 @@ internal class SaleStorageContract : ISaleStorageContract
}
}
private Sale? GetSaleById(string id) => _dbContext.Sales.FirstOrDefault(x => x.Id == id);
private Sale? GetSaleById(string id) => _dbContext.Sales.Include(x => x.Client).Include(x => x.Employee).Include(x => x.SaleTours)!.ThenInclude(x => x.Tour).FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,100 @@
using AutoMapper;
using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.StoragesContracts;
using MagicCarpetDatabase.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetDatabase.Implementations;
public class SuppliesStorageContract : ISuppliesStorageContract
{
private readonly MagicCarpetDbContext _dbContext;
private readonly Mapper _mapper;
public SuppliesStorageContract(MagicCarpetDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Supplies, SuppliesDataModel>()
.ConstructUsing(src => new SuppliesDataModel(
src.Id,
src.Type,
src.ProductuionDate,
src.Count,
_mapper.Map<List<TourSuppliesDataModel>>(src.Tours)
));
cfg.CreateMap<SuppliesDataModel, Supplies>();
cfg.CreateMap<TourSuppliesDataModel, TourSupplies>().ReverseMap();
});
_mapper = new Mapper(config);
}
public List<SuppliesDataModel> GetList(DateTime? startDate = null)
{
try
{
return [.. _dbContext.Supplieses.Select(x => _mapper.Map<SuppliesDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public SuppliesDataModel GetElementById(string id)
{
try
{
return _mapper.Map<SuppliesDataModel>(GetSuppliesById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(SuppliesDataModel suppliesDataModel)
{
try
{
_dbContext.Supplieses.Add(_mapper.Map<Supplies>(suppliesDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(SuppliesDataModel suppliesDataModel)
{
try
{
var element = GetSuppliesById(suppliesDataModel.Id) ?? throw new ElementNotFoundException(suppliesDataModel.Id);
_dbContext.Supplieses.Update(_mapper.Map(suppliesDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Supplies? GetSuppliesById(string id) => _dbContext.Supplieses.FirstOrDefault(x => x.Id == id);
}

View File

@@ -7,13 +7,14 @@ using Microsoft.EntityFrameworkCore;
using Npgsql;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetDatabase.Implementations;
internal class TourStorageContract : ITourStorageContract
public class TourStorageContract : ITourStorageContract
{
private readonly MagicCarpetDbContext _dbContext;
private readonly Mapper _mapper;
@@ -23,13 +24,13 @@ internal class TourStorageContract : ITourStorageContract
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Tour, TourDataModel>()
.ConstructUsing(src => new TourDataModel(src.Id, src.TourName, src.TourCountry, src.Price, src.Type));
cfg.CreateMap<Tour, TourDataModel>();
cfg.CreateMap<TourDataModel, Tour>();
cfg.CreateMap<TourHistory, TourHistoryDataModel>();
cfg.CreateMap<TourHistory, TourHistoryDataModel>(); ;
});
_mapper = new Mapper(config);
}
public List<TourDataModel> GetList()
{
try
@@ -47,7 +48,7 @@ internal class TourStorageContract : ITourStorageContract
{
try
{
return [.. _dbContext.TourHistories.Where(x => x.TourId == tourId).OrderByDescending(x => x.ChangeDate).Select(x => _mapper.Map<TourHistoryDataModel>(x))];
return [.. _dbContext.TourHistories.Include(x => x.Tour).Where(x => x.TourId == tourId).OrderByDescending(x => x.ChangeDate).Select(x => _mapper.Map<TourHistoryDataModel>(x))];
}
catch (Exception ex)
{
@@ -110,20 +111,35 @@ internal class TourStorageContract : ITourStorageContract
{
try
{
var element = GetTourById(tourDataModel.Id) ?? throw new ElementNotFoundException(tourDataModel.Id);
_dbContext.Tours.Update(_mapper.Map(tourDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
var transaction = _dbContext.Database.BeginTransaction();
try
{
var element = GetTourById(tourDataModel.Id) ?? throw new ElementNotFoundException(tourDataModel.Id);
if (element.Price != tourDataModel.Price)
{
_dbContext.TourHistories.Add(new TourHistory() { TourId = element.Id, OldPrice = element.Price });
_dbContext.SaveChanges();
}
_dbContext.Tours.Update(_mapper.Map(tourDataModel, element));
_dbContext.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Tours_TourName" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("TourName", tourDataModel.TourName);
}
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();

View File

@@ -15,9 +15,6 @@
<ItemGroup>
<ProjectReference Include="..\MagicCarpetContracts\MagicCarpetContracts.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="MagicCarpetTests" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
</Project>

View File

@@ -9,7 +9,7 @@ using System.Threading.Tasks;
namespace MagicCarpetDatabase;
internal class MagicCarpetDbContext(IConfigurationDatabase configurationDatabase) : DbContext
public class MagicCarpetDbContext(IConfigurationDatabase configurationDatabase) : DbContext
{
private readonly IConfigurationDatabase? _configurationDatabase = configurationDatabase;
@@ -25,6 +25,11 @@ internal class MagicCarpetDbContext(IConfigurationDatabase configurationDatabase
modelBuilder.Entity<Client>().HasIndex(x => x.PhoneNumber).IsUnique();
modelBuilder.Entity<Sale>()
.HasOne(e => e.Client)
.WithMany(e => e.Sales)
.OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity<Tour>().HasIndex(x => x.TourName).IsUnique();
modelBuilder.Entity<Post>()
@@ -38,6 +43,10 @@ internal class MagicCarpetDbContext(IConfigurationDatabase configurationDatabase
.HasFilter($"\"{nameof(Post.IsActual)}\" = TRUE");
modelBuilder.Entity<SaleTour>().HasKey(x => new { x.SaleId, x.TourId });
modelBuilder.Entity<TourSupplies>().HasKey(x => new { x.SuppliesId, x.TourId });
modelBuilder.Entity<TourAgency>().HasKey(x => new { x.AgencyId, x.TourId });
}
public DbSet<Client> Clients { get; set; }
@@ -55,4 +64,8 @@ internal class MagicCarpetDbContext(IConfigurationDatabase configurationDatabase
public DbSet<SaleTour> SaleTours { get; set; }
public DbSet<Employee> Employees { get; set; }
public DbSet<Supplies> Supplieses { get; set; }
public DbSet<Agency> Agencies { get; set; }
public DbSet<TourSupplies> TourSupplieses { get; set; }
public DbSet<TourAgency> TourAgensies { get; set; }
}

View File

@@ -0,0 +1,22 @@
using AutoMapper;
using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetDatabase.Models;
[AutoMap(typeof(AgencyDataModel), ReverseMap = true)]
public class Agency
{
public required string Id { get; set; }
public required TourType TourType { get; set; }
public required int Count { get; set; }
[ForeignKey("AgencyId")]
public List<TourAgency>? Tours { get; set; }
}

View File

@@ -10,7 +10,7 @@ using System.Threading.Tasks;
namespace MagicCarpetDatabase.Models;
[AutoMap(typeof(ClientDataModel), ReverseMap = true)]
internal class Client
public class Client
{
public required string Id { get; set; }

View File

@@ -10,7 +10,7 @@ using System.Threading.Tasks;
namespace MagicCarpetDatabase.Models;
[AutoMap(typeof(EmployeeDataModel), ReverseMap = true)]
internal class Employee
public class Employee
{
public required string Id { get; set; }
@@ -24,9 +24,16 @@ internal class Employee
public DateTime EmploymentDate { get; set; }
public bool IsDeleted { 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

@@ -8,7 +8,7 @@ using System.Threading.Tasks;
namespace MagicCarpetDatabase.Models;
internal class Post
public class Post
{
public required string Id { get; set; } = Guid.NewGuid().ToString();
public required string PostId { get; set; }

View File

@@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace MagicCarpetDatabase.Models;
internal class Salary
public class Salary
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string EmployeeId { get; set; }

View File

@@ -9,7 +9,7 @@ using System.Threading.Tasks;
namespace MagicCarpetDatabase.Models;
internal class Sale
public class Sale
{
public string Id { get; set; } = Guid.NewGuid().ToString();

View File

@@ -6,11 +6,17 @@ using System.Threading.Tasks;
namespace MagicCarpetDatabase.Models;
internal class SaleTour
public class SaleTour
{
public required string SaleId { get; set; }
public required string TourId { get; set; }
public int Count { get; set; }
public double Price { get; set; }
public Sale? Sale { get; set; }
public Tour? Tour { get; set; }
}

View File

@@ -0,0 +1,22 @@
using AutoMapper;
using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetDatabase.Models;
public class Supplies
{
public required string Id { get; set; }
public required TourType Type { get; set; }
public DateTime ProductuionDate { get; set; }
public required int Count { get; set; }
[ForeignKey("SuppliesId")]
public List<TourSupplies>? Tours { get; set; }
}

View File

@@ -1,4 +1,6 @@
using MagicCarpetContracts.Enums;
using AutoMapper;
using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
@@ -9,15 +11,20 @@ using System.Threading.Tasks;
namespace MagicCarpetDatabase.Models;
internal class Tour
[AutoMap(typeof(TourDataModel), ReverseMap = true)]
public class Tour
{
public required string Id { get; set; }
public required string TourName { get; set; }
public string? TourCountry { get; set; }
public double Price { get; set; }
public required TourType Type { get; set; }
public required TourType TourType { get; set; }
[ForeignKey("TourId")]
public List<SaleTour>? SaleTours { get; set; }
[ForeignKey("TourId")]
public List<TourHistory>? TourHistories { get; set; }
[ForeignKey("SuppliesesId")]
public List<TourSupplies>? TourSupplies { get; set; }
[ForeignKey("AgenciesId")]
public List<TourAgency>? TourAgency { get; set; }
}

View File

@@ -0,0 +1,19 @@
using AutoMapper;
using MagicCarpetContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetDatabase.Models;
[AutoMap(typeof(TourAgencyDataModel), ReverseMap = true)]
public class TourAgency
{
public required string AgencyId { get; set; }
public required string TourId { get; set; }
public int Count { get; set; }
public Agency? Agencies { get; set; }
public Tour? Tours { get; set; }
}

View File

@@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace MagicCarpetDatabase.Models;
internal class TourHistory
public class TourHistory
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string TourId { get; set; }

View File

@@ -0,0 +1,19 @@
using AutoMapper;
using MagicCarpetContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetDatabase.Models;
[AutoMap(typeof(TourSuppliesDataModel), ReverseMap = true)]
public class TourSupplies
{
public required string SuppliesId { get; set; }
public required string TourId { get; set; }
public int Count { get; set; }
public Supplies? Supplies { get; set; }
public Tour? Tours { get; set; }
}

View File

@@ -11,6 +11,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MagicCarpetBusinessLogic",
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MagicCarpetDatabase", "MagicCarpetDatabase\MagicCarpetDatabase.csproj", "{C69B43B2-8680-42D7-A111-306E2E8225FE}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MagicCarpetWebApi", "MagicCarpetWebApi\MagicCarpetWebApi.csproj", "{EB1F990E-6604-4DE4-81A9-2D1D15E0240F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -33,6 +35,10 @@ Global
{C69B43B2-8680-42D7-A111-306E2E8225FE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C69B43B2-8680-42D7-A111-306E2E8225FE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C69B43B2-8680-42D7-A111-306E2E8225FE}.Release|Any CPU.Build.0 = Release|Any CPU
{EB1F990E-6604-4DE4-81A9-2D1D15E0240F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EB1F990E-6604-4DE4-81A9-2D1D15E0240F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EB1F990E-6604-4DE4-81A9-2D1D15E0240F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EB1F990E-6604-4DE4-81A9-2D1D15E0240F}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@@ -0,0 +1,296 @@
using MagicCarpetBusinessLogic.Implementations;
using MagicCarpetContracts.BusinessLogicContracts;
using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Enums;
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetTests.BusinessLogicContractsTests;
[TestFixture]
internal class AgencyBusinessLogicContractTests
{
private IAgencyBusinessLogicContract _warehouseBusinessLogicContract;
private Mock<IAgencyStorageContract> _warehouseStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_warehouseStorageContract = new Mock<IAgencyStorageContract>();
_warehouseBusinessLogicContract = new AgencyBusinessLogicContract(_warehouseStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_warehouseStorageContract.Reset();
}
public void GetAllSupplies_ReturnListOfRecords_Test()
{
// Arrange
var listOriginal = new List<AgencyDataModel>()
{
new(Guid.NewGuid().ToString(), TourType.Beach, 1, []),
new(Guid.NewGuid().ToString(), TourType.Beach, 1, []),
new(Guid.NewGuid().ToString(), TourType.Beach, 1, []),
};
_warehouseStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
// Act
var list = _warehouseBusinessLogicContract.GetAllComponents();
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
}
[Test]
public void GetAllSupplies_ReturnEmptyList_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetList()).Returns([]);
// Act
var list = _warehouseBusinessLogicContract.GetAllComponents();
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_warehouseStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllSupplies_ReturnNull_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetList()).Returns((List<AgencyDataModel>)null);
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.GetAllComponents(), Throws.TypeOf<NullListException>());
_warehouseStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllSupplies_StorageThrowError_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.GetAllComponents(), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetSuppliesByData_GetById_ReturnRecord_Test()
{
// Arrange
var id = Guid.NewGuid().ToString();
var record = new AgencyDataModel(id, TourType.Beach, 1, []);
_warehouseStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
// Act
var element = _warehouseBusinessLogicContract.GetComponentByData(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 GetComponentsByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.GetComponentByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _warehouseBusinessLogicContract.GetComponentByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetSuppliesByData_GetById_NotFoundRecord_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new ElementNotFoundException(""));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.GetComponentByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetSuppliesByData_StorageThrowError_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.GetComponentByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertSupplies_CorrectRecord_Test()
{
// Arrange
var record = new AgencyDataModel(Guid.NewGuid().ToString(), TourType.Beach, 1,
[new TourAgencyDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_warehouseStorageContract.Setup(x => x.AddElement(It.IsAny<AgencyDataModel>()));
// Act
_warehouseBusinessLogicContract.InsertComponent(record);
// Assert
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<AgencyDataModel>()), Times.Once);
}
[Test]
public void InsertSupplies_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.AddElement(It.IsAny<AgencyDataModel>())).Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertComponent(new(Guid.NewGuid().ToString(), TourType.Beach, 1,
[new TourAgencyDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<AgencyDataModel>()), Times.Once);
}
[Test]
public void InsertSupplies_NullRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertComponent(null), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<AgencyDataModel>()), Times.Never);
}
[Test]
public void InsertComponents_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertComponent(new AgencyDataModel("id", TourType.Beach, 1, [])), Throws.TypeOf<ValidationException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<AgencyDataModel>()), Times.Never);
}
[Test]
public void InsertSupplies_StorageThrowError_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.AddElement(It.IsAny<AgencyDataModel>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertComponent(new(Guid.NewGuid().ToString(), TourType.Beach, 1,
[new TourAgencyDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<AgencyDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_CorrectRecord_Test()
{
// Arrange
var record = new AgencyDataModel(Guid.NewGuid().ToString(), TourType.Beach, 1,
[new TourAgencyDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<AgencyDataModel>()));
// Act
_warehouseBusinessLogicContract.UpdateComponent(record);
// Assert
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<AgencyDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_RecordWithIncorrectData_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<AgencyDataModel>())).Throws(new ElementNotFoundException(""));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), TourType.Beach, 1,
[new TourAgencyDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementNotFoundException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<AgencyDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<AgencyDataModel>())).Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), TourType.Beach, 1,
[new TourAgencyDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<AgencyDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_NullRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(null), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<AgencyDataModel>()), Times.Never);
}
[Test]
public void UpdateComponents_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(new AgencyDataModel(Guid.NewGuid().ToString(), TourType.Beach, 1, [])), Throws.TypeOf<ValidationException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<AgencyDataModel>()), Times.Never);
}
[Test]
public void UpdateSupplies_StorageThrowError_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<AgencyDataModel>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), TourType.Beach, 1,
[new TourAgencyDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<AgencyDataModel>()), Times.Once);
}
[Test]
public void DeleteComponents_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.DeleteComponent(id);
//Assert
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once); Assert.That(flag);
}
[Test]
public void DeleteComponents_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.DeleteComponent(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeleteComponents_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent(string.Empty), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteComponents_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent("id"),
Throws.TypeOf<ValidationException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteComponents_StorageThrowError_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -38,61 +38,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]
@@ -102,8 +94,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
@@ -167,7 +159,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);
@@ -182,7 +174,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);
@@ -238,12 +230,11 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 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);
@@ -258,7 +249,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.Manager, 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);
}
@@ -274,7 +265,7 @@ internal class PostBusinessLogicContractTests
public void InsertPost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Manager, 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);
}
@@ -284,7 +275,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.Manager, 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);
}
@@ -293,12 +284,11 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 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);
@@ -313,7 +303,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.Manager, 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);
}
@@ -323,7 +313,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.Manager, 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);
}
@@ -339,7 +329,7 @@ internal class PostBusinessLogicContractTests
public void UpdatePost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Manager, 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);
}
@@ -349,7 +339,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.Manager, 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

@@ -164,7 +164,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);
}
@@ -191,12 +191,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 SaleTourDataModel(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;
@@ -213,7 +213,7 @@ internal class SalaryBusinessLogicContractTests
}
[Test]
public void CalculateSalaryByMounth_WithSeveralWorkers_Test()
public void CalculateSalaryByMounth_WithSeveralEmployees_Test()
{
//Arrange
var employee1Id = Guid.NewGuid().ToString();
@@ -225,13 +225,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
@@ -241,7 +241,7 @@ internal class SalaryBusinessLogicContractTests
}
[Test]
public void CalculateSalaryByMounth_WithoutSalesByWorker_Test()
public void CalculateSalaryByMounth_WithoutSalesByEmployee_Test()
{
//Arrange
var postSalary = 2000.0;
@@ -249,7 +249,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;
@@ -271,7 +271,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
@@ -284,22 +284,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>());
}
@@ -312,7 +312,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
@@ -325,7 +325,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?>()))
@@ -335,14 +335,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

@@ -18,18 +18,22 @@ internal class SaleBusinessLogicContractTests
{
private SaleBusinessLogicContract _saleBusinessLogicContract;
private Mock<ISaleStorageContract> _saleStorageContract;
private Mock<IAgencyStorageContract> _agencyStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_saleStorageContract = new Mock<ISaleStorageContract>();
_saleBusinessLogicContract = new SaleBusinessLogicContract(_saleStorageContract.Object, new Mock<ILogger>().Object);
_agencyStorageContract = new Mock<IAgencyStorageContract>();
_saleBusinessLogicContract = new SaleBusinessLogicContract(_saleStorageContract.Object,
_agencyStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_saleStorageContract.Reset();
_agencyStorageContract.Reset();
}
[Test]
@@ -39,10 +43,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 SaleTourDataModel(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 SaleTourDataModel(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
@@ -103,10 +107,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 SaleTourDataModel(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 SaleTourDataModel(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
@@ -184,10 +188,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 SaleTourDataModel(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 SaleTourDataModel(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
@@ -265,10 +269,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 SaleTourDataModel(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 SaleTourDataModel(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
@@ -343,8 +347,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 SaleTourDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
var record = new SaleDataModel(id, Guid.NewGuid().ToString(), null, DiscountType.None, false,
[new SaleTourDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]);
_saleStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _saleBusinessLogicContract.GetSaleByData(id);
@@ -394,8 +398,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 SaleTourDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
var record = new SaleDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.None,
false, [new SaleTourDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]);
_agencyStorageContract.Setup(x => x.CheckComponents(It.IsAny<SaleDataModel>())).Returns(true);
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>()))
.Callback((SaleDataModel x) =>
{
@@ -409,6 +414,7 @@ internal class SaleBusinessLogicContractTests
//Act
_saleBusinessLogicContract.InsertSale(record);
//Assert
_agencyStorageContract.Verify(x => x.CheckComponents(It.IsAny<SaleDataModel>()), Times.Once);
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
Assert.That(flag);
}
@@ -417,11 +423,13 @@ internal class SaleBusinessLogicContractTests
public void InsertSale_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_agencyStorageContract.Setup(x => x.CheckComponents(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 SaleTourDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
Guid.NewGuid().ToString(), DiscountType.None, false, [new SaleTourDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])), Throws.TypeOf<ElementExistsException>());
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
_agencyStorageContract.Verify(x => x.CheckComponents(It.IsAny<SaleDataModel>()), Times.Once);
}
[Test]
@@ -436,7 +444,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);
}
@@ -444,13 +452,26 @@ internal class SaleBusinessLogicContractTests
public void InsertSale_StorageThrowError_ThrowException_Test()
{
//Arrange
_agencyStorageContract.Setup(x => x.CheckComponents(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 SaleTourDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
Guid.NewGuid().ToString(), DiscountType.None, false, [new SaleTourDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])), Throws.TypeOf<StorageException>());
_agencyStorageContract.Verify(x => x.CheckComponents(It.IsAny<SaleDataModel>()), Times.Once);
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
}
[Test]
public void InsertSale_InsufficientError_ThrowException_Test()
{
//Arrange
_agencyStorageContract.Setup(x => x.CheckComponents(It.IsAny<SaleDataModel>())).Returns(false);
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), DiscountType.None, false, [new SaleTourDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])), Throws.TypeOf<InsufficientException>());
//Act&Assert
_agencyStorageContract.Verify(x => x.CheckComponents(It.IsAny<SaleDataModel>()), Times.Once);
}
[Test]
public void CancelSale_CorrectRecord_Test()
{

View File

@@ -0,0 +1,242 @@
using MagicCarpetBusinessLogic.Implementations;
using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Enums;
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetTests.BusinessLogicContractsTests;
[TestFixture]
internal class SuppliesBusinessLogicContractTests
{
private SuppliesBusinessLogicContract _suppliesBusinessLogicContract;
private Mock<ISuppliesStorageContract> _suppliesStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_suppliesStorageContract = new Mock<ISuppliesStorageContract>();
_suppliesBusinessLogicContract = new SuppliesBusinessLogicContract(_suppliesStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_suppliesStorageContract.Reset();
}
[Test]
public void GetAllSupplies_ReturnListOfRecords_Test()
{
// Arrange
var listOriginal = new List<SuppliesDataModel>()
{
new(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1, []),
new(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1, []),
new(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1, []),
};
_suppliesStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>())).Returns(listOriginal);
// Act
var list = _suppliesBusinessLogicContract.GetAllComponents();
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
}
[Test]
public void GetAllSupplies_ReturnEmptyList_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>())).Returns([]);
// Act
var list = _suppliesBusinessLogicContract.GetAllComponents();
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_suppliesStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllSupplies_ReturnNull_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>())).Returns((List<SuppliesDataModel>)null);
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.GetAllComponents(), Throws.TypeOf<NullListException>());
_suppliesStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllSupplies_StorageThrowError_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.GetAllComponents(), Throws.TypeOf<StorageException>());
_suppliesStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetSuppliesByData_GetById_ReturnRecord_Test()
{
// Arrange
var id = Guid.NewGuid().ToString();
var record = new SuppliesDataModel(id,TourType.Beach, DateTime.Now, 1, []);
_suppliesStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
// Act
var element = _suppliesBusinessLogicContract.GetComponentByData(id);
// Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_suppliesStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetComponentsByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _suppliesBusinessLogicContract.GetComponentByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _suppliesBusinessLogicContract.GetComponentByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_suppliesStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetSuppliesByData_GetById_NotFoundRecord_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new ElementNotFoundException(""));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.GetComponentByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_suppliesStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetSuppliesByData_StorageThrowError_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.GetComponentByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_suppliesStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertSupplies_CorrectRecord_Test()
{
// Arrange
var record = new SuppliesDataModel(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1,
[new TourSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_suppliesStorageContract.Setup(x => x.AddElement(It.IsAny<SuppliesDataModel>()));
// Act
_suppliesBusinessLogicContract.InsertComponent(record);
// Assert
_suppliesStorageContract.Verify(x => x.AddElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
[Test]
public void InsertSupplies_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.AddElement(It.IsAny<SuppliesDataModel>())).Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.InsertComponent(new(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1,
[new TourSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_suppliesStorageContract.Verify(x => x.AddElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
[Test]
public void InsertSupplies_NullRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.InsertComponent(null), Throws.TypeOf<ArgumentNullException>());
_suppliesStorageContract.Verify(x => x.AddElement(It.IsAny<SuppliesDataModel>()), Times.Never);
}
[Test]
public void InsertComponents_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _suppliesBusinessLogicContract.InsertComponent(new SuppliesDataModel("id", TourType.Beach, DateTime.UtcNow, 1, [])), Throws.TypeOf<ValidationException>());
_suppliesStorageContract.Verify(x => x.AddElement(It.IsAny<SuppliesDataModel>()), Times.Never);
}
[Test]
public void InsertSupplies_StorageThrowError_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.AddElement(It.IsAny<SuppliesDataModel>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.InsertComponent(new(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1,
[new TourSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_suppliesStorageContract.Verify(x => x.AddElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_CorrectRecord_Test()
{
// Arrange
var record = new SuppliesDataModel(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1,
[new TourSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_suppliesStorageContract.Setup(x => x.UpdElement(It.IsAny<SuppliesDataModel>()));
// Act
_suppliesBusinessLogicContract.UpdateComponent(record);
// Assert
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_RecordWithIncorrectData_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.UpdElement(It.IsAny<SuppliesDataModel>())).Throws(new ElementNotFoundException(""));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1,
[new TourSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementNotFoundException>());
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.UpdElement(It.IsAny<SuppliesDataModel>())).Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1,
[new TourSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_NullRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.UpdateComponent(null), Throws.TypeOf<ArgumentNullException>());
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Never);
}
[Test]
public void UpdateComponents_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _suppliesBusinessLogicContract.UpdateComponent(new SuppliesDataModel(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1, [])), Throws.TypeOf<ValidationException>());
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Never);
}
[Test]
public void UpdateSupplies_StorageThrowError_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.UpdElement(It.IsAny<SuppliesDataModel>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1,
[new TourSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
}

View File

@@ -3,6 +3,7 @@ using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Enums;
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.StoragesContracts;
using MagicCarpetTests.DataModelTests;
using Microsoft.Extensions.Logging;
using Moq;
using System;
@@ -154,7 +155,7 @@ internal class TourBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new TourDataModel(id, "name","country", 10, TourType.Ski);
var record = new TourDataModel(id, "name", "country", 10, TourType.Ski);
_tourStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _tourBusinessLogicContract.GetTourByData(id);
@@ -249,7 +250,7 @@ internal class TourBusinessLogicContractTests
.Callback((TourDataModel x) =>
{
flag = x.Id == record.Id && x.TourName == record.TourName && x.TourCountry == record.TourCountry
&& x.Price == record.Price && x.Type == record.Type;
&& x.Price == record.Price && x.TourType == record.TourType;
});
//Act
_tourBusinessLogicContract.InsertTour(record);
@@ -288,10 +289,18 @@ internal class TourBusinessLogicContractTests
public void InsertTour_StorageThrowError_ThrowException_Test()
{
//Arrange
_tourStorageContract.Setup(x => x.AddElement(It.IsAny<TourDataModel>())).Throws(new StorageException(new InvalidOperationException()));
Assert.That(() => _tourBusinessLogicContract.InsertTour(new TourDataModel(Guid.NewGuid().ToString(), "name","country", 10, TourType.Ski)), Throws.TypeOf<InsufficientException>());
//Act&Assert
Assert.That(() => _tourBusinessLogicContract.InsertTour(new(Guid.NewGuid().ToString(), "name", "country", 10, TourType.Ski)), Throws.TypeOf<StorageException>());
_tourStorageContract.Verify(x => x.AddElement(It.IsAny<TourDataModel>()), Times.Once);
_tourStorageContract.Verify(x => x.UpdElement(It.IsAny<TourDataModel>()), Times.Never);
}
[Test]
public void InsertTour_InsufficientError_ThrowException_Test()
{
//Arrange
Assert.That(() => _tourBusinessLogicContract.InsertTour(new TourDataModel(Guid.NewGuid().ToString(), "name", "country", 10, TourType.Ski)),Throws.TypeOf<InsufficientException>());
//Act&Assert
_tourStorageContract.Verify(x => x.UpdElement(It.IsAny<TourDataModel>()), Times.Never);
}
[Test]
@@ -304,7 +313,7 @@ internal class TourBusinessLogicContractTests
.Callback((TourDataModel x) =>
{
flag = x.Id == record.Id && x.TourName == record.TourName && x.TourCountry == record.TourCountry
&& x.Price == record.Price && x.Type == record.Type;
&& x.Price == record.Price && x.TourType == record.TourType;
});
//Act
_tourBusinessLogicContract.UpdateTour(record);
@@ -329,7 +338,7 @@ internal class TourBusinessLogicContractTests
//Arrange
_tourStorageContract.Setup(x => x.UpdElement(It.IsAny<TourDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _tourBusinessLogicContract.UpdateTour(new(Guid.NewGuid().ToString(), "name", "country", 10, TourType.Ski)), Throws.TypeOf<ElementExistsException>());
Assert.That(() => _tourBusinessLogicContract.UpdateTour(new(Guid.NewGuid().ToString(), "name", "country", 10, TourType.Ski)), Throws.TypeOf <ElementExistsException>());
_tourStorageContract.Verify(x => x.UpdElement(It.IsAny<TourDataModel>()), Times.Once);
}

View File

@@ -0,0 +1,79 @@
using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Enums;
using MagicCarpetContracts.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetTests.DataModelTests;
[TestFixture]
internal class AgencyDataModelTests
{
[Test]
public void IdIsNullOrEmptyTest()
{
var model = CreateDataModel(null, TourType.Beach, 1, CreateSubDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(string.Empty, TourType.Beach, 1, CreateSubDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var model = CreateDataModel("id", TourType.Beach, 1, CreateSubDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void TypeIsNoneTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), TourType.None, 1, CreateSubDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CountIsLessOrZeroTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), TourType.None, 0, CreateSubDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), TourType.None, -1, CreateSubDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ToursIsNullOrEmptyTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), TourType.Beach, 1, null);
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
sale = CreateDataModel(Guid.NewGuid().ToString(), TourType.Beach, 1, []);
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var id = Guid.NewGuid().ToString();
var type = TourType.Beach;
var count = 1;
var tours = CreateSubDataModel();
var model = CreateDataModel(id, type, count, tours);
Assert.DoesNotThrow(() => model.Validate());
Assert.Multiple(() =>
{
Assert.That(model.Id, Is.EqualTo(id));
Assert.That(model.TourType, Is.EqualTo(type));
Assert.That(model.Count, Is.EqualTo(count));
Assert.That(model.Tours, Is.EqualTo(tours));
});
}
private static AgencyDataModel CreateDataModel(string? id, TourType type, int count, List<TourAgencyDataModel> tours)
=> new AgencyDataModel(id, type, count, tours);
private static List<TourAgencyDataModel> CreateSubDataModel()
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)];
}

View File

@@ -14,41 +14,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>());
}
@@ -56,13 +56,10 @@ internal class PostDataModelTests
public void AllFieldsIsCorrectTest()
{
var postId = Guid.NewGuid().ToString();
var postPostId = Guid.NewGuid().ToString();
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(() =>
{
@@ -70,11 +67,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

@@ -15,89 +15,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 ToursIsNullOrEmptyTest()
{
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 tours = new List<SaleTourDataModel>()
{
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 = tours.Sum(x => x.Price * x.Count);
var saleNone = CreateDataModel(saleId, employeeId, clientId, DiscountType.None, isCancel, tours);
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, tours);
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, tours);
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, tours);
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, tours);
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 tours = CreateSubDataModel();
var sale = CreateDataModel(saleId, employeeId, clientId, sum, discountType, discount, isCancel, tours);
var sale = CreateDataModel(saleId, employeeId, clientId, discountType, isCancel, tours);
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.Tours, Is.EquivalentTo(tours));
});
}
private static SaleDataModel CreateDataModel(string? id, string? employeeId, string? clientId, double sum, DiscountType discountType,
double discount, bool isCancel, List<SaleTourDataModel>? tours) =>
new(id, employeeId, clientId, sum, discountType, discount, isCancel, tours);
private static SaleDataModel CreateDataModel(string? id, string? employeeId, string? clientId, DiscountType discountType, bool isCancel, List<SaleTourDataModel>? tours) =>
new(id, employeeId, clientId, discountType, isCancel, tours);
private static List<SaleTourDataModel> CreateSubDataModel()
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)];
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 1.1)];
}

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