1 Commits
lab_6 ... lab_7

Author SHA1 Message Date
23db4d2f8d Лабораторная 7 2025-05-27 16:20:42 +04:00
101 changed files with 5006 additions and 2454 deletions

View File

@@ -5,19 +5,22 @@ using DaisiesContracts.BindingModels;
using DaisiesContracts.BuisnessLogicContracts;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.Resources;
using DaisiesContracts.ViewModels;
using Microsoft.Extensions.Localization;
using System.Text.Json;
namespace DaisiesWebApi.Adapters;
public class BuyerAdapter : IBuyerAdapter
internal class BuyerAdapter : IBuyerAdapter
{
private readonly IBuyerBuisnessLogicContract _buyerBusinessLogicContract;
private readonly ILogger _logger;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
private readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNameCaseInsensitive = true };
public BuyerAdapter(IBuyerBuisnessLogicContract buyerBusinessLogicContract,
ILogger<BuyerAdapter> logger)
ILogger<BuyerAdapter> logger, IStringLocalizer<Messages> localizer)
{
_buyerBusinessLogicContract = buyerBusinessLogicContract;
_logger = logger;
@@ -28,22 +31,20 @@ public class BuyerAdapter : IBuyerAdapter
.ForMember(x => x.Configuration, x => x.MapFrom(src => JsonSerializer.Serialize(src.ConfigurationModel, JsonSerializerOptions)));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public BuyerOperationResponse GetList()
{
try
{
return BuyerOperationResponse.OK([.._buyerBusinessLogicContract.GetAllBuyers().Select(x =>_mapper.Map<BuyerViewModel>(x))]);
}
catch (NullListException)
{
_logger.LogError("NullListException");
return BuyerOperationResponse.NotFound("The list is not initialized");
return BuyerOperationResponse.OK([..
_buyerBusinessLogicContract.GetAllBuyers().Select(x =>
_mapper.Map<BuyerViewModel>(x))]);
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return BuyerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message} ");
return BuyerOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -62,17 +63,17 @@ public class BuyerAdapter : IBuyerAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return BuyerOperationResponse.BadRequest("Data is empty");
return BuyerOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return BuyerOperationResponse.NotFound($"Not found element by data {data} ");
return BuyerOperationResponse.NotFound(string.Format(_localizer["AdapterMessageElementNotFoundException"], data));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return BuyerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return BuyerOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -90,12 +91,12 @@ public class BuyerAdapter : IBuyerAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return BuyerOperationResponse.BadRequest("Data is empty");
return BuyerOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return BuyerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return BuyerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementExistsException ex)
{
@@ -105,7 +106,7 @@ public class BuyerAdapter : IBuyerAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return BuyerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return BuyerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -123,17 +124,17 @@ public class BuyerAdapter : IBuyerAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return BuyerOperationResponse.BadRequest("Data is empty");
return BuyerOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return BuyerOperationResponse.BadRequest($"Incorrect datatransmitted: {ex.Message}");
return BuyerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return BuyerOperationResponse.BadRequest($"Not found element by Id {buyerModel.Id}");
return BuyerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], buyerModel));
}
catch (ElementExistsException ex)
{
@@ -143,7 +144,7 @@ public class BuyerAdapter : IBuyerAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return BuyerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return BuyerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -161,22 +162,22 @@ public class BuyerAdapter : IBuyerAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return BuyerOperationResponse.BadRequest("Id is empty");
return BuyerOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return BuyerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return BuyerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return BuyerOperationResponse.BadRequest($"Not found element by id: {id}");
return BuyerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], id));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return BuyerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message} ");
return BuyerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{

View File

@@ -6,18 +6,23 @@ using DaisiesContracts.BindingModels;
using DaisiesContracts.BuisnessLogicContracts;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.Resources;
using DaisiesContracts.ViewModels;
using Microsoft.Extensions.Localization;
namespace DaisiesWebApi.Adapters;
public class ClientDiscountAdapter : IClientDiscountAdapter
internal class ClientDiscountAdapter : IClientDiscountAdapter
{
private readonly IClientDiscountBuisnessLogicContract _clientDiscountBusinessLogicContract;
private readonly ILogger _logger;
private readonly Mapper _mapper;
public ClientDiscountAdapter(IClientDiscountBuisnessLogicContract clientDiscountBusinessLogicContrac, ILogger<ClientDiscountAdapter> logger)
private readonly IStringLocalizer<Messages> _localizer;
public ClientDiscountAdapter(IClientDiscountBuisnessLogicContract clientDiscountBusinessLogicContrac, ILogger<ClientDiscountAdapter> logger, IStringLocalizer<Messages> localizer)
{
_clientDiscountBusinessLogicContract = clientDiscountBusinessLogicContrac;
_logger = logger;
@@ -27,6 +32,7 @@ public class ClientDiscountAdapter : IClientDiscountAdapter
cfg.CreateMap<ClientDiscountDataModel, ClientDiscountViewModel>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public ClientDiscountOperationResponse RegisterClientDiscount(ClientDiscountBindingModel
@@ -40,22 +46,22 @@ public class ClientDiscountAdapter : IClientDiscountAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return ClientDiscountOperationResponse.BadRequest("Data is empty");
return ClientDiscountOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return ClientDiscountOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return ClientDiscountOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementExistsException ex)
{
_logger.LogError(ex, "ElementExistsException");
return ClientDiscountOperationResponse.BadRequest(ex.Message);
return ClientDiscountOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ClientDiscountOperationResponse.BadRequest($"Error whileworking with data storage: {ex.InnerException!.Message}");
return ClientDiscountOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -75,22 +81,22 @@ public class ClientDiscountAdapter : IClientDiscountAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return ClientDiscountOperationResponse.BadRequest("Data is empty");
return ClientDiscountOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return ClientDiscountOperationResponse.NotFound($"Not found element by data {data} ");
return ClientDiscountOperationResponse.NotFound(string.Format(_localizer["AdapterMessageElementNotFoundException"], data));
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return ClientDiscountOperationResponse.BadRequest($"Element by data: {data} was deleted");
return ClientDiscountOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], data));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ClientDiscountOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return ClientDiscountOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message)); ;
}
catch (Exception ex)
{
@@ -104,19 +110,12 @@ public class ClientDiscountAdapter : IClientDiscountAdapter
{
try
{
return ClientDiscountOperationResponse.OK([..
_clientDiscountBusinessLogicContract.GetAllClientDiscounts().Select(x =>
_mapper.Map<ClientDiscountViewModel>(x))]);
}
catch (NullListException)
{
_logger.LogError("NullListException");
return ClientDiscountOperationResponse.NotFound("The list is not initialized");
return ClientDiscountOperationResponse.OK([.._clientDiscountBusinessLogicContract.GetAllClientDiscounts().Select(x =>_mapper.Map<ClientDiscountViewModel>(x))]);
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ClientDiscountOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message} ");
return ClientDiscountOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -125,7 +124,8 @@ _mapper.Map<ClientDiscountViewModel>(x))]);
}
}
public ClientDiscountOperationResponse ChangeClientDiscountInfo(ClientDiscountBindingModel clientDiscountModel)
public ClientDiscountOperationResponse ChangeClientDiscountInfo(ClientDiscountBindingModel
clientDiscountModel)
{
try
{
@@ -135,17 +135,17 @@ _mapper.Map<ClientDiscountViewModel>(x))]);
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return ClientDiscountOperationResponse.BadRequest("Data is empty");
return ClientDiscountOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return ClientDiscountOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message} ");
return ClientDiscountOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return ClientDiscountOperationResponse.BadRequest($"Not found element by BuyerId {clientDiscountModel.BuyerId} ");
return ClientDiscountOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], clientDiscountModel.BuyerId));
}
catch (ElementExistsException ex)
{
@@ -155,12 +155,12 @@ _mapper.Map<ClientDiscountViewModel>(x))]);
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return ClientDiscountOperationResponse.BadRequest($"Element by id: {clientDiscountModel.BuyerId} was deleted");
return ClientDiscountOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], clientDiscountModel.BuyerId));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ClientDiscountOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return ClientDiscountOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -174,32 +174,34 @@ _mapper.Map<ClientDiscountViewModel>(x))]);
{
try
{
return ClientDiscountOperationResponse.OK(_mapper.Map<ClientDiscountViewModel>(_clientDiscountBusinessLogicContract.GetClientDiscountByBuyerId(data)));
return
ClientDiscountOperationResponse.OK(_mapper.Map<ClientDiscountViewModel>(_clientDiscountBusinessLogicContract.GetClientDiscountByBuyerId(data)));
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return ClientDiscountOperationResponse.BadRequest("Data is empty");
return ClientDiscountOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return ClientDiscountOperationResponse.NotFound($"Not found element by data {data} ");
return ClientDiscountOperationResponse.NotFound(string.Format(_localizer["AdapterMessageElementNotFoundException"], data));
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return ClientDiscountOperationResponse.BadRequest($"Element by data: {data} was deleted");
return ClientDiscountOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], data));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ClientDiscountOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return ClientDiscountOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return ClientDiscountOperationResponse.InternalServerError(ex.Message);
return
ClientDiscountOperationResponse.InternalServerError(ex.Message);
}
}
}

View File

@@ -5,11 +5,13 @@ using DaisiesContracts.BindingModels;
using DaisiesContracts.BuisnessLogicContracts;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.Resources;
using DaisiesContracts.ViewModels;
using Microsoft.Extensions.Localization;
namespace DaisiesWebApi.Adapters;
public class PostAdapter : IPostAdapter
internal class PostAdapter : IPostAdapter
{
private readonly IPostBuisnessLogicContract _postBusinessLogicContract;
@@ -17,7 +19,9 @@ public class PostAdapter : IPostAdapter
private readonly Mapper _mapper;
public PostAdapter(IPostBuisnessLogicContract postBusinessLogicContract, ILogger<PostAdapter> logger)
private readonly IStringLocalizer<Messages> _localizer;
public PostAdapter(IPostBuisnessLogicContract postBusinessLogicContract, ILogger<PostAdapter> logger, IStringLocalizer<Messages> localizer)
{
_postBusinessLogicContract = postBusinessLogicContract;
_logger = logger;
@@ -27,6 +31,7 @@ public class PostAdapter : IPostAdapter
cfg.CreateMap<PostDataModel, PostViewModel>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public PostOperationResponse GetList()
@@ -35,15 +40,10 @@ public class PostAdapter : IPostAdapter
{
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllPosts().Select(x => _mapper.Map<PostViewModel>(x))]);
}
catch (NullListException)
{
_logger.LogError("NullListException");
return PostOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -61,17 +61,17 @@ public class PostAdapter : IPostAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest("Data is empty");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -89,22 +89,22 @@ public class PostAdapter : IPostAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest("Data is empty");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return PostOperationResponse.NotFound($"Not found element by data {data}");
return PostOperationResponse.NotFound(string.Format(_localizer["AdapterMessageElementNotFoundException"], data));
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return PostOperationResponse.BadRequest($"Element by data: {data} was deleted");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], data));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -123,12 +123,12 @@ public class PostAdapter : IPostAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest("Data is empty");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementExistsException ex)
{
@@ -138,7 +138,7 @@ public class PostAdapter : IPostAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -157,17 +157,17 @@ public class PostAdapter : IPostAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest("Data is empty");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return PostOperationResponse.BadRequest($"Not found element by Id {postModel.Id}");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], postModel));
}
catch (ElementExistsException ex)
{
@@ -177,12 +177,12 @@ public class PostAdapter : IPostAdapter
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return PostOperationResponse.BadRequest($"Element by id: {postModel.Id} was deleted");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], postModel));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -201,27 +201,27 @@ public class PostAdapter : IPostAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest("Id is empty");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return PostOperationResponse.BadRequest($"Not found element by id: {id}");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], id));
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return PostOperationResponse.BadRequest($"Element by id: {id} was deleted");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], id));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -240,22 +240,22 @@ public class PostAdapter : IPostAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest("Id is empty");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return PostOperationResponse.BadRequest($"Not found element by id: {id}");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], id));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -263,4 +263,4 @@ public class PostAdapter : IPostAdapter
return PostOperationResponse.InternalServerError(ex.Message);
}
}
}
}

View File

@@ -5,18 +5,21 @@ using DaisiesContracts.BindingModels;
using DaisiesContracts.BuisnessLogicContracts;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.Resources;
using DaisiesContracts.ViewModels;
using Microsoft.Extensions.Localization;
namespace DaisiesWebApi.Adapters;
public class ProductAdapter : IProductAdapter
internal class ProductAdapter : IProductAdapter
{
private readonly IProductBuisnessLogicContract
_productBusinessLogicContract;
private readonly ILogger _logger;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public ProductAdapter(IProductBuisnessLogicContract
productBusinessLogicContract, ILogger<ProductAdapter> logger)
productBusinessLogicContract, ILogger<ProductAdapter> logger, IStringLocalizer<Messages> localizer)
{
_productBusinessLogicContract = productBusinessLogicContract;
_logger = logger;
@@ -27,22 +30,18 @@ public class ProductAdapter : IProductAdapter
cfg.CreateMap<ProductHistoryDataModel, ProductHistoryViewModel>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public ProductOperationResponse GetList(bool includeDeleted)
{
try
{
return ProductOperationResponse.OK([.. _productBusinessLogicContract.GetAllProducts(!includeDeleted).Select(x =>_mapper.Map<ProductViewModel>(x))]);
}
catch (NullListException)
{
_logger.LogError("NullListException");
return ProductOperationResponse.NotFound("The list is not initialized");
return ProductOperationResponse.OK([.._productBusinessLogicContract.GetAllProducts(!includeDeleted).Select(x =>_mapper.Map<ProductViewModel>(x))]);
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ProductOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return ProductOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -51,26 +50,24 @@ public class ProductAdapter : IProductAdapter
ProductOperationResponse.InternalServerError(ex.Message);
}
}
public ProductOperationResponse GetSupplierList(string id, bool includeDeleted)
public ProductOperationResponse GetSupplierList(string id, bool
includeDeleted)
{
try
{
return ProductOperationResponse.OK([.. _productBusinessLogicContract.GetAllProductsBySupplier(id,!includeDeleted).Select(x => _mapper.Map<ProductViewModel>(x))]);
return ProductOperationResponse.OK([..
_productBusinessLogicContract.GetAllProductsBySupplier(id,
!includeDeleted).Select(x => _mapper.Map<ProductViewModel>(x))]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return ProductOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return ProductOperationResponse.NotFound("The list is not initialized");
return ProductOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ProductOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return ProductOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -84,27 +81,25 @@ public class ProductAdapter : IProductAdapter
{
try
{
return ProductOperationResponse.OK([.. _productBusinessLogicContract.GetProductHistoryByProduct(id).Select(x => _mapper.Map<ProductHistoryViewModel>(x))]);
return ProductOperationResponse.OK([..
_productBusinessLogicContract.GetProductHistoryByProduct(id).Select(x =>
_mapper.Map<ProductHistoryViewModel>(x))]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return ProductOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return ProductOperationResponse.NotFound("The list is not initialized");
return ProductOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ProductOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return ProductOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return ProductOperationResponse.InternalServerError(ex.Message);
return
ProductOperationResponse.InternalServerError(ex.Message);
}
}
public ProductOperationResponse GetElement(string data)
@@ -117,22 +112,22 @@ public class ProductAdapter : IProductAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return ProductOperationResponse.BadRequest("Data is empty");
return ProductOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return ProductOperationResponse.NotFound($"Not found element by data {data} ");
return ProductOperationResponse.NotFound(string.Format(_localizer["AdapterMessageElementNotFoundException"], data));
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return ProductOperationResponse.BadRequest($"Element by data: {data} was deleted");
return ProductOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], data));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ProductOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return ProductOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -152,12 +147,12 @@ public class ProductAdapter : IProductAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return ProductOperationResponse.BadRequest("Data is empty");
return ProductOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return ProductOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return ProductOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementExistsException ex)
{
@@ -167,7 +162,7 @@ public class ProductAdapter : IProductAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ProductOperationResponse.BadRequest($"Error whileworking with data storage: {ex.InnerException!.Message}");
return ProductOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -187,17 +182,17 @@ public class ProductAdapter : IProductAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return ProductOperationResponse.BadRequest("Data is empty");
return ProductOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return ProductOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message} ");
return ProductOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return ProductOperationResponse.BadRequest($"Not found element by Id {productModel.Id} ");
return ProductOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], productModel.Id));
}
catch (ElementExistsException ex)
{
@@ -207,12 +202,12 @@ public class ProductAdapter : IProductAdapter
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return ProductOperationResponse.BadRequest($"Element by id: {productModel.Id} was deleted");
return ProductOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], productModel.Id));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ProductOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return ProductOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -231,27 +226,27 @@ public class ProductAdapter : IProductAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return ProductOperationResponse.BadRequest("Id is empty");
return ProductOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return ProductOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message} ");
return ProductOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return ProductOperationResponse.BadRequest($"Not found element by id: {id} ");
return ProductOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], id));
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return ProductOperationResponse.BadRequest($"Element by id: {id} was deleted");
return ProductOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], id));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ProductOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return ProductOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{

View File

@@ -8,7 +8,7 @@ using DaisiesContracts.ViewModels;
namespace DaisiesWebApi.Adapters;
public class ReportAdapter : IReportAdapter
internal class ReportAdapter : IReportAdapter
{
private readonly IReportContract _reportContract;

View File

@@ -6,19 +6,22 @@ using DaisiesContracts.BindingModels;
using DaisiesContracts.BuisnessLogicContracts;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.Resources;
using DaisiesContracts.ViewModels;
using Microsoft.Extensions.Localization;
namespace DaisiesWebApi.Adapters;
public class SaleAdapter : ISaleAdapter
internal class SaleAdapter : ISaleAdapter
{
private readonly ISaleBuisnessLogicContract _saleBusinessLogicContract;
private readonly ILogger _logger;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public SaleAdapter(ISaleBuisnessLogicContract saleBusinessLogicContract, ILogger<SaleAdapter> logger)
public SaleAdapter(ISaleBuisnessLogicContract saleBusinessLogicContract, ILogger<SaleAdapter> logger, IStringLocalizer<Messages> localizer)
{
_saleBusinessLogicContract = saleBusinessLogicContract;
_logger = logger;
@@ -30,28 +33,25 @@ public class SaleAdapter : ISaleAdapter
cfg.CreateMap<SaleProductDataModel, SaleProductViewModel>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public SaleOperationResponse GetList(DateTime fromDate, DateTime toDate)
{
try
{
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByPeriod(fromDate, toDate).Select(x => _mapper.Map<SaleViewModel>(x))]);
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByPeriod(fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => _mapper.Map<SaleViewModel>(x))]);
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return SaleOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return SaleOperationResponse.NotFound("The list is not initialized");
return SaleOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageIncorrectDatesException"], ex.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return SaleOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -64,27 +64,22 @@ public class SaleAdapter : ISaleAdapter
{
try
{
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(id, fromDate, toDate).Select(x => _mapper.Map<SaleViewModel>(x))]);
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(id, fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => _mapper.Map<SaleViewModel>(x))]);
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return SaleOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
return SaleOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageIncorrectDatesException"], ex.Message));
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return SaleOperationResponse.NotFound("The list is not initialized");
return SaleOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return SaleOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -97,27 +92,24 @@ public class SaleAdapter : ISaleAdapter
{
try
{
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(id, fromDate, toDate).Select(x => _mapper.Map<SaleViewModel>(x))]);
var utcFromDate = fromDate.ToUniversalTime();
var utcToDate = toDate.ToUniversalTime();
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(id, utcFromDate, utcToDate).Select(x => _mapper.Map<SaleViewModel>(x))]);
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return SaleOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
return SaleOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return SaleOperationResponse.NotFound("The list is not initialized");
return SaleOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return SaleOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -130,27 +122,22 @@ public class SaleAdapter : ISaleAdapter
{
try
{
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByProductByPeriod(id, fromDate, toDate).Select(x => _mapper.Map<SaleViewModel>(x))]);
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByProductByPeriod(id, fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => _mapper.Map<SaleViewModel>(x))]);
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return SaleOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
return SaleOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return SaleOperationResponse.NotFound("The list is not initialized");
return SaleOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return SaleOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -168,22 +155,22 @@ public class SaleAdapter : ISaleAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return SaleOperationResponse.BadRequest("Data is empty");
return SaleOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return SaleOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return SaleOperationResponse.NotFound($"Not found element by data {id}");
return SaleOperationResponse.NotFound(string.Format(_localizer["AdapterMessageElementNotFoundException"], id));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return SaleOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -203,17 +190,17 @@ public class SaleAdapter : ISaleAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return SaleOperationResponse.BadRequest("Data is empty");
return SaleOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return SaleOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message)); ;
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return SaleOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return SaleOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -232,27 +219,27 @@ public class SaleAdapter : ISaleAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return SaleOperationResponse.BadRequest("Id is empty");
return SaleOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
return SaleOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return SaleOperationResponse.BadRequest($"Not found element by id: {id}");
return SaleOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], id));
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return SaleOperationResponse.BadRequest($"Element by id: {id} was deleted");
return SaleOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], id));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return SaleOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return SaleOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{

View File

@@ -6,17 +6,20 @@ using DaisiesContracts.BindingModels;
using DaisiesContracts.BuisnessLogicContracts;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.Resources;
using DaisiesContracts.ViewModels;
using Microsoft.Extensions.Localization;
namespace DaisiesWebApi.Adapters;
public class WorkerAdapter : IWorkerAdapter
internal class WorkerAdapter : IWorkerAdapter
{
private readonly IWorkerBuisnessLogicContract _buyerBusinessLogicContract;
private readonly ILogger _logger;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public WorkerAdapter(IWorkerBuisnessLogicContract
workerBusinessLogicContract, ILogger<WorkerAdapter> logger)
workerBusinessLogicContract, ILogger<WorkerAdapter> logger, IStringLocalizer<Messages> localizer)
{
_buyerBusinessLogicContract = workerBusinessLogicContract;
_logger = logger;
@@ -26,22 +29,20 @@ public class WorkerAdapter : IWorkerAdapter
cfg.CreateMap<WorkerDataModel, WorkerViewModel>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public WorkerOperationResponse GetList(bool includeDeleted)
{
try
{
return WorkerOperationResponse.OK([.._buyerBusinessLogicContract.GetAllWorkers(!includeDeleted).Select(x =>_mapper.Map<WorkerViewModel>(x))]);
}
catch (NullListException)
{
_logger.LogError("NullListException");
return WorkerOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return WorkerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message} ");
return WorkerOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -59,17 +60,12 @@ public class WorkerAdapter : IWorkerAdapter
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return WorkerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message} ");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return WorkerOperationResponse.NotFound("The list is not initialized");
return WorkerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return WorkerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message} ");
return WorkerOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -83,22 +79,19 @@ public class WorkerAdapter : IWorkerAdapter
{
try
{
return WorkerOperationResponse.OK([.._buyerBusinessLogicContract.GetAllWorkersByBirthDate(fromDate, toDate,!includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
var utcFromDate = fromDate.ToUniversalTime();
var utcToDate = toDate.ToUniversalTime();
return WorkerOperationResponse.OK([.._buyerBusinessLogicContract.GetAllWorkersByBirthDate(utcFromDate, utcToDate,!includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return WorkerOperationResponse.BadRequest($"Incorrect dates: {ex.Message} ");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return WorkerOperationResponse.NotFound("The list is not initialized");
return WorkerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageIncorrectDatesException"], ex.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return WorkerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message} ");
return WorkerOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -112,22 +105,19 @@ public class WorkerAdapter : IWorkerAdapter
{
try
{
return WorkerOperationResponse.OK([.._buyerBusinessLogicContract.GetAllWorkersByEmploymentDate(fromDate, toDate,!includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
var utcFromDate = fromDate.ToUniversalTime();
var utcToDate = toDate.ToUniversalTime();
return WorkerOperationResponse.OK([.._buyerBusinessLogicContract.GetAllWorkersByEmploymentDate(utcFromDate, utcToDate,!includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return WorkerOperationResponse.BadRequest($"Incorrect dates: {ex.Message} ");
}
catch (NullListException)
{
_logger.LogError("NullListException");
return WorkerOperationResponse.NotFound("The list is not initialized");
return WorkerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageIncorrectDatesException"], ex.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return WorkerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message} ");
return WorkerOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -146,22 +136,22 @@ public class WorkerAdapter : IWorkerAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return WorkerOperationResponse.BadRequest("Data is empty");
return WorkerOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return WorkerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message} ");
return WorkerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return WorkerOperationResponse.NotFound($"Not found element by data {data} ");
return WorkerOperationResponse.NotFound(string.Format(_localizer["AdapterMessageElementNotFoundException"], data));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return WorkerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message} ");
return WorkerOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -180,12 +170,12 @@ public class WorkerAdapter : IWorkerAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return WorkerOperationResponse.BadRequest("Data is empty");
return WorkerOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return WorkerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message} ");
return WorkerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementExistsException ex)
{
@@ -195,7 +185,7 @@ public class WorkerAdapter : IWorkerAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return WorkerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message} ");
return WorkerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -214,17 +204,17 @@ public class WorkerAdapter : IWorkerAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return WorkerOperationResponse.BadRequest("Data is empty");
return WorkerOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return WorkerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message} ");
return WorkerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return WorkerOperationResponse.BadRequest($"Not found element by Id {workerModel.Id} ");
return WorkerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], workerModel.Id));
}
catch (ElementExistsException ex)
{
@@ -234,7 +224,7 @@ public class WorkerAdapter : IWorkerAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return WorkerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message} ");
return WorkerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -253,22 +243,22 @@ public class WorkerAdapter : IWorkerAdapter
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return WorkerOperationResponse.BadRequest("Id is empty");
return WorkerOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return WorkerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message} ");
return WorkerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return WorkerOperationResponse.BadRequest($"Not found element by id: {id} ");
return WorkerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], id));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return WorkerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message} ");
return WorkerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{

View File

@@ -25,7 +25,7 @@ public class WeatherForecastController : ControllerBase
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Date = DateOnly.FromDateTime(DateTime.UtcNow.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})

View File

@@ -3,16 +3,19 @@ using DaisiesBuisnessLogic.OfficePackage;
using DaisiesContracts.AdapterContracts;
using DaisiesContracts.BuisnessLogicContracts;
using DaisiesContracts.Infrastructure;
using DaisiesContracts.StoragesContracts;
using DaisiesContracts.Resources.StoragesContracts;
using DaisiesDatabase;
using DaisiesDatabase.Implementations;
using DaisiesWebApi;
using DaisiesWebApi.Adapters;
using DaisiesWebApi.Infrastructure;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Localization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Serilog;
using System.Globalization;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
@@ -28,6 +31,27 @@ builder.Services.AddSingleton<IConfigurationDatabase, ConfigurationDatabase>();
builder.Services.AddSingleton<IConfigurationDatabase, ConfigurationDatabase>();
builder.Services.AddSingleton<IConfigurationDiscount, ConfigurationDiscount>();
builder.Services.AddLocalization();
builder.Services.Configure<RequestLocalizationOptions>(
options =>
{
var supportedCultures = new List<CultureInfo>
{
new("en-US"),
new("ru-RU"),
new("fr-FR")
};
options.DefaultRequestCulture = new RequestCulture(culture: "ru-RU", uiCulture: "ru-RU");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});
builder.Services.AddSingleton<IConfigurationDatabase, ConfigurationDatabase>();
builder.Services.AddSingleton<IConfigurationDiscount, ConfigurationDiscount>();
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>-<2D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
builder.Services.AddTransient<IBuyerBuisnessLogicContract, BuyerBuisnessLogicContract>();
builder.Services.AddTransient<IClientDiscountBuisnessLogicContract, ClientDiscountBuisnessLogicContract>();
@@ -127,5 +151,12 @@ app.Map("/login/{username}", (string username) =>
app.MapControllers();
var localizeOptions =
app.Services.GetService<IOptions<RequestLocalizationOptions>>();
if (localizeOptions is not null)
{
app.UseRequestLocalization(localizeOptions.Value);
}
app.Run();

View File

@@ -15,6 +15,7 @@
<ItemGroup>
<InternalsVisibleTo Include="DaisiesTests" />
<InternalsVisibleTo Include="DaisiesApi" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>

View File

@@ -1,26 +1,25 @@
using System.Text.Json;
using System.Text.RegularExpressions;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using DaisiesContracts.BuisnessLogicContracts;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.Extensions;
using DaisiesContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using DaisiesContracts.Resources;
using DaisiesContracts.Resources.StoragesContracts;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace DaisiesBuisnessLogic.Implementations;
public class BuyerBuisnessLogicContract(IBuyerStorageContract buyerStorageContract, ILogger logger) : IBuyerBuisnessLogicContract
internal class BuyerBuisnessLogicContract(IBuyerStorageContract buyerStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : IBuyerBuisnessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IBuyerStorageContract _buyerStorageContract =
buyerStorageContract;
private readonly IBuyerStorageContract _buyerStorageContract = buyerStorageContract;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<BuyerDataModel> GetAllBuyers()
{
_logger.LogInformation("GetAllBuyers");
return _buyerStorageContract.GetList() ?? throw new
NullListException();
return [];
return _buyerStorageContract.GetList();
}
public BuyerDataModel GetBuyerByData(string data)
@@ -33,22 +32,22 @@ public class BuyerBuisnessLogicContract(IBuyerStorageContract buyerStorageContra
if (data.IsGuid())
{
return _buyerStorageContract.GetElementById(data) ?? throw new
ElementNotFoundException(data);
ElementNotFoundException(data, _localizer);
}
if (Regex.IsMatch(data, @"^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\-]{7,10}$"))
{
return _buyerStorageContract.GetElementByPhoneNumber(data) ??
throw new ElementNotFoundException(data);
throw new ElementNotFoundException(data, _localizer);
}
return _buyerStorageContract.GetElementByFIO(data) ?? throw new
ElementNotFoundException(data);
ElementNotFoundException(data, _localizer);
}
public void InsertBuyer(BuyerDataModel buyerDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(buyerDataModel));
ArgumentNullException.ThrowIfNull(buyerDataModel);
buyerDataModel.Validate();
buyerDataModel.Validate(_localizer);
_buyerStorageContract.AddElement(buyerDataModel);
}
@@ -56,7 +55,7 @@ public class BuyerBuisnessLogicContract(IBuyerStorageContract buyerStorageContra
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(buyerDataModel));
ArgumentNullException.ThrowIfNull(buyerDataModel);
buyerDataModel.Validate();
buyerDataModel.Validate(_localizer);
_buyerStorageContract.UpdElement(buyerDataModel);
}
public void DeleteBuyer(string id)
@@ -68,7 +67,7 @@ public class BuyerBuisnessLogicContract(IBuyerStorageContract buyerStorageContra
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
}
_buyerStorageContract.DelElement(id);
}

View File

@@ -4,13 +4,16 @@ using DaisiesContracts.Exceptions;
using DaisiesContracts.Extensions;
using DaisiesContracts.Infrastructure;
using DaisiesContracts.Infrastructure.BuyerConfigurations;
using DaisiesContracts.StoragesContracts;
using DaisiesContracts.Resources;
using DaisiesContracts.Resources.StoragesContracts;
using DaisiesDatabase.Implementations;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace DaisiesBuisnessLogic.Implementations;
public class ClientDiscountBuisnessLogicContract(IClientDiscountStorageContract clientDiscountStorageContract, IBuyerStorageContract buyerStorageContract, ISaleStorageContract saleStorageContract, IConfigurationDiscount configuration, ILogger logger) : IClientDiscountBuisnessLogicContract
internal class ClientDiscountBuisnessLogicContract(IClientDiscountStorageContract clientDiscountStorageContract, IBuyerStorageContract buyerStorageContract, ISaleStorageContract saleStorageContract, IConfigurationDiscount configuration, ILogger logger, IStringLocalizer<Messages> localizer) : IClientDiscountBuisnessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IClientDiscountStorageContract _clientDiscountStorageContract = clientDiscountStorageContract;
@@ -18,37 +21,35 @@ public class ClientDiscountBuisnessLogicContract(IClientDiscountStorageContract
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
private readonly IConfigurationDiscount _discountConfiguration = configuration;
private readonly Lock _lockObject = new();
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<ClientDiscountDataModel> GetAllClientDiscounts()
{
logger.LogInformation("GetAllClientDiscount");
return _clientDiscountStorageContract.GetList() ?? throw new
NullListException();
return [];
return _clientDiscountStorageContract.GetList();
}
public ClientDiscountDataModel GetClientDiscountByBuyerId(string buyerId)
public ClientDiscountDataModel GetClientDiscountByBuyerId(string data)
{
_logger.LogInformation("get element by data: {data}", buyerId);
if (buyerId.IsEmpty())
_logger.LogInformation("get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(buyerId));
throw new ArgumentNullException(nameof(data));
}
if (buyerId.IsGuid())
if (data.IsGuid())
{
return _clientDiscountStorageContract.GetElementByBuyerId(buyerId) ?? throw new
ElementNotFoundException(buyerId);
return _clientDiscountStorageContract.GetElementByBuyerId(data) ?? throw new
ElementNotFoundException(data, _localizer);
}
return _clientDiscountStorageContract.GetElementByBuyerFIO(buyerId) ?? throw new
ElementNotFoundException(buyerId);
return _clientDiscountStorageContract.GetElementByBuyerFIO(data) ?? throw new
ElementNotFoundException(data, _localizer);
}
public void InsertClientDiscount(ClientDiscountDataModel clientDiscountDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(clientDiscountDataModel));
ArgumentNullException.ThrowIfNull(clientDiscountDataModel);
clientDiscountDataModel.Validate();
clientDiscountDataModel.Validate(_localizer);
_clientDiscountStorageContract.AddElement(clientDiscountDataModel);
}
@@ -56,7 +57,7 @@ public class ClientDiscountBuisnessLogicContract(IClientDiscountStorageContract
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(clientDiscountDataModel));
ArgumentNullException.ThrowIfNull(clientDiscountDataModel);
clientDiscountDataModel.Validate();
clientDiscountDataModel.Validate(_localizer);
_clientDiscountStorageContract.UpdElement(clientDiscountDataModel);
}
public void DeleteClientDiscount(string id)
@@ -68,43 +69,40 @@ public class ClientDiscountBuisnessLogicContract(IClientDiscountStorageContract
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
}
_clientDiscountStorageContract.DelElement(id);
}
public void CalculateBonusByMounth(DateTime date)
public void CalculateDiscountByMounth(DateTime date)
{
_logger.LogInformation("CalculateBonusesForCustomers: {date}", date);
_logger.LogInformation("CalculateDiscountsForBuyers: {date}", date);
var startDate = new DateTime(date.Year, date.Month, 1);
var finishDate = new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month));
// Получаем список всех покупателей
var buyers = _buyerStorageContract.GetList() ?? throw new NullListException();
var buyers = _buyerStorageContract.GetList();
foreach (var buyer in buyers)
{
// Получаем сумму покупок покупателя за месяц
var buyerOrders = _saleStorageContract.GetList(startDate, finishDate, buyerId: buyer.Id);
var ordersSum = _saleStorageContract.GetList(startDate, finishDate, buyerId: buyer.Id).Sum(x => x.Sum);
var buyerSales = _saleStorageContract.GetList(startDate, finishDate, buyerId: buyer.Id);
var salesSum = _saleStorageContract.GetList(startDate, finishDate, buyerId: buyer.Id).Sum(x => x.Sum);
var discount = buyer.ConfigurationModel switch
{
null => 0,
ConstantBuyerConfiguration cpc => CalculateBonusForConstBuyer(buyerOrders, cpc),
VipBuyerConfiguration spc => CalculateBonusForVipBuyer(buyerOrders, startDate, finishDate, spc),
BuyerConfiguration pc => (double)(ordersSum * 0.001)
ConstantBuyerConfiguration cpc => CalculateDiscountForConstBuyer(buyerSales, cpc),
VipBuyerConfiguration spc => CalculateDiscountForVipBuyer(buyerSales, startDate, finishDate, spc),
BuyerConfiguration pc => (double)(salesSum * 0.001)
};
_logger.LogDebug("Customer {customerId} received a bonus of {bonus} for the month", buyer.Id, discount);
_clientDiscountStorageContract.AddElement(new ClientDiscountDataModel(buyer.Id, ordersSum, discount));
_logger.LogDebug("Buyer {buyerId} received a discount of {discount} for the month", buyer.Id, discount);
_clientDiscountStorageContract.AddElement(new ClientDiscountDataModel(buyer.Id, salesSum, discount));
}
}
private double CalculateBonusForVipBuyer(List<SaleDataModel> sales, DateTime startDate, DateTime finishDate, VipBuyerConfiguration config)
private double CalculateDiscountForVipBuyer(List<SaleDataModel> sales, DateTime startDate, DateTime finishDate, VipBuyerConfiguration config)
{
var calcBonuses = 0.0;
var calcDiscounts = 0.0;
var options = new ParallelOptions
{
MaxDegreeOfParallelism = _discountConfiguration.MaxConcurrentThreads
@@ -112,24 +110,24 @@ public class ClientDiscountBuisnessLogicContract(IClientDiscountStorageContract
Parallel.ForEach(Enumerable.Range(0, (finishDate - startDate).Days), options, i =>
{
var dateInTask = startDate.AddDays(i);
var ordersInDay = sales.Where(x => x.SaleDate >= dateInTask && x.SaleDate < dateInTask.AddDays(1)).ToArray();
var salesInDay = sales.Where(x => x.SaleDate >= dateInTask && x.SaleDate < dateInTask.AddDays(1)).ToArray();
if (ordersInDay.Length > 0)
if (salesInDay.Length > 0)
{
lock (_lockObject)
{
foreach (var order in ordersInDay)
calcBonuses += (double)(order.Sum * 0.001) * (config.ExtraDiscountMultiplyer + config.DiscountMultiplier);
foreach (var sale in salesInDay)
calcDiscounts += (double)(sale.Sum * 0.001) * (config.ExtraDiscountMultiplyer + config.ConstantDiscountMultiplier);
}
}
});
var calcBonusTask = Task.Run(() =>
var calcDiscountTask = Task.Run(() =>
{
return (double)(sales.Where(x => x.Sum > _discountConfiguration.ExtraDiscountSum).Sum(x => x.Sum) * 0.001) * config.ExtraDiscountMultiplyer;
});
try
{
calcBonusTask.Wait();
calcDiscountTask.Wait();
}
catch (AggregateException agEx)
{
@@ -139,25 +137,25 @@ public class ClientDiscountBuisnessLogicContract(IClientDiscountStorageContract
}
return 0;
}
return calcBonuses + (double)calcBonusTask.Result;
return calcDiscounts + (double)calcDiscountTask.Result;
}
private double CalculateBonusForConstBuyer(List<SaleDataModel> sales, ConstantBuyerConfiguration config)
private double CalculateDiscountForConstBuyer(List<SaleDataModel> sales, ConstantBuyerConfiguration config)
{
try
{
var totalDiscount = 0.0;
foreach (var order in sales)
foreach (var sale in sales)
{
totalDiscount += (double)(order.Sum * 0.001) * config.RegularDiscountMultiplyer;
totalDiscount += (double)(sale.Sum * 0.001) * config.RegularDiscountMultiplyer;
}
return totalDiscount;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error in constant customer discount calculation");
_logger.LogError(ex, "Error in constant buyer discount calculation");
return 0;
}
}
}
}

View File

@@ -3,21 +3,18 @@ using DaisiesContracts.BuisnessLogicContracts;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.Extensions;
using DaisiesContracts.StoragesContracts;
using DaisiesContracts.Resources;
using DaisiesContracts.Resources.StoragesContracts;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
namespace DaisiesBuisnessLogic.Implementations;
public class PostBuisnessLogicContract(IPostStorageContract postStorageContract, ILogger logger) : IPostBuisnessLogicContract
internal class PostBuisnessLogicContract(IPostStorageContract postStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : IPostBuisnessLogicContract
{
IPostStorageContract _postStorageContract = postStorageContract;
private readonly ILogger _logger = logger;
private readonly IPostStorageContract _postStorageContract = postStorageContract;
public List<PostDataModel> GetAllPosts()
{
_logger.LogInformation("GetAllPosts params: {onlyActive}");
return _postStorageContract.GetList() ?? throw new NullListException();
}
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<PostDataModel> GetAllDataOfPost(string postId)
{
@@ -28,10 +25,15 @@ public class PostBuisnessLogicContract(IPostStorageContract postStorageContract,
}
if (!postId.IsGuid())
{
throw new ValidationException("The value in the field postId is not a unique identifier.");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "PostId"));
}
return _postStorageContract.GetPostWithHistory(postId) ?? throw new NullListException();
return _postStorageContract.GetPostWithHistory(postId);
}
public List<PostDataModel> GetAllPosts()
{
_logger.LogInformation("GetAllPosts");
return _postStorageContract.GetList();
}
public PostDataModel GetPostByData(string data)
@@ -43,17 +45,16 @@ public class PostBuisnessLogicContract(IPostStorageContract postStorageContract,
}
if (data.IsGuid())
{
return _postStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return _postStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data, _localizer);
}
return _postStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data);
return _postStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data, _localizer);
}
public void InsertPost(PostDataModel postDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(postDataModel));
logger.LogInformation("New data: {json}", JsonSerializer.Serialize(postDataModel));
ArgumentNullException.ThrowIfNull(postDataModel);
postDataModel.Validate();
postDataModel.Validate(_localizer);
_postStorageContract.AddElement(postDataModel);
}
@@ -61,7 +62,7 @@ public class PostBuisnessLogicContract(IPostStorageContract postStorageContract,
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(postDataModel));
ArgumentNullException.ThrowIfNull(postDataModel);
postDataModel.Validate();
postDataModel.Validate(_localizer);
_postStorageContract.UpdElement(postDataModel);
}
@@ -74,7 +75,7 @@ public class PostBuisnessLogicContract(IPostStorageContract postStorageContract,
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "PostId"));
}
_postStorageContract.DelElement(id);
}
@@ -88,7 +89,7 @@ public class PostBuisnessLogicContract(IPostStorageContract postStorageContract,
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "PostId"));
}
_postStorageContract.ResElement(id);
}

View File

@@ -3,20 +3,24 @@ using DaisiesContracts.DataModels;
using DaisiesContracts.Enum;
using DaisiesContracts.Exceptions;
using DaisiesContracts.Extensions;
using DaisiesContracts.StoragesContracts;
using System.Text.Json;
using Microsoft.Extensions.Logging;
using DaisiesContracts.Resources.StoragesContracts;
using Microsoft.Extensions.Localization;
using DaisiesContracts.Resources;
namespace DaisiesBuisnessLogic.Implementations;
public class ProductBuisnessLogicContract(IProductStorageContract productStorageContract, ILogger logger) : IProductBuisnessLogicContract
internal class ProductBuisnessLogicContract(IProductStorageContract productStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : IProductBuisnessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IProductStorageContract _productStorageContract = productStorageContract;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<ProductDataModel> GetAllProducts(bool onlyActive)
{
_logger.LogInformation("GetAllProducts params: {onlyActive}", onlyActive);
return _productStorageContract.GetList(onlyActive) ?? throw new NullListException();
return _productStorageContract.GetList(onlyActive);
}
public List<ProductHistoryDataModel> GetProductHistoryByProduct(string productId)
@@ -28,9 +32,9 @@ public class ProductBuisnessLogicContract(IProductStorageContract productStorage
}
if (!productId.IsGuid())
{
throw new ValidationException("The value in the field productId is not a unique identifier.");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
}
return _productStorageContract.GetHistoryByProductId(productId) ?? throw new NullListException();
return _productStorageContract.GetHistoryByProductId(productId);
}
public List<ProductDataModel> GetAllProductsBySupplier(string
@@ -45,10 +49,7 @@ public class ProductBuisnessLogicContract(IProductStorageContract productStorage
throw new ValidationException("The value in the field supplierId is not a unique identifier.");
}
_logger.LogInformation("GetAllProducts params: {supplierId}, { onlyActive} ", supplierId, onlyActive);
return _productStorageContract.GetList(onlyActive, supplierId) ??
throw new NullListException();
return [];
return _productStorageContract.GetList(onlyActive, supplierId);
}
public ProductDataModel GetProductByData(string data)
@@ -60,16 +61,16 @@ public class ProductBuisnessLogicContract(IProductStorageContract productStorage
}
if (data.IsGuid())
{
return _productStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return _productStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data, _localizer);
}
return _productStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data);
return _productStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data, _localizer);
}
public void InsertProduct(ProductDataModel productDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(productDataModel));
ArgumentNullException.ThrowIfNull(productDataModel);
productDataModel.Validate();
productDataModel.Validate(_localizer);
_productStorageContract.AddElement(productDataModel);
}
@@ -77,7 +78,7 @@ public class ProductBuisnessLogicContract(IProductStorageContract productStorage
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(productDataModel));
ArgumentNullException.ThrowIfNull(productDataModel);
productDataModel.Validate();
productDataModel.Validate(_localizer);
_productStorageContract.UpdElement(productDataModel);
}
@@ -90,7 +91,7 @@ public class ProductBuisnessLogicContract(IProductStorageContract productStorage
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
}
_productStorageContract.DelElement(id);
}

View File

@@ -2,43 +2,58 @@
using DaisiesContracts.BuisnessLogicContracts;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using DaisiesContracts.Resources;
using DaisiesContracts.Resources.StoragesContracts;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
namespace DaisiesBuisnessLogic.Implementations;
public class ReportContract(IProductStorageContract productStorageContract, ILogger logger, BaseWordBuilder baseWordBuilder, ISaleStorageContract saleStorageContract,
IClientDiscountStorageContract discountStorageContract, BaseExcelBuilder baseExcelBuilder, BasePdfBuilder basePdfBuilder) : IReportContract
internal class ReportContract : IReportContract
{
private readonly ILogger _logger = logger;
private readonly IProductStorageContract _productStorageContract = productStorageContract;
private readonly BaseWordBuilder _baseWordBuilder = baseWordBuilder;
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
private readonly IClientDiscountStorageContract _discountStorageContract = discountStorageContract;
private readonly BaseExcelBuilder _baseExcelBuilder = baseExcelBuilder;
private readonly BasePdfBuilder _basePdfBuilder = basePdfBuilder;
private readonly ILogger _logger;
private readonly IProductStorageContract _productStorageContract;
private readonly BaseWordBuilder _baseWordBuilder;
private readonly ISaleStorageContract _saleStorageContract;
private readonly IClientDiscountStorageContract _discountStorageContract;
private readonly BaseExcelBuilder _baseExcelBuilder;
private readonly BasePdfBuilder _basePdfBuilder;
private readonly IStringLocalizer<Messages> _localizer;
internal static readonly string[] tableHeader = ["Дата", "Сумма", "Скидка", "Продукт", "Кол-во"];
internal static readonly string[] documentHeader = ["Название продукта", "Цены", "Дата"];
private readonly string[] _tableHeader;
private readonly string[] _documentHeader;
public ReportContract(IProductStorageContract productStorageContract, ILogger logger, BaseWordBuilder baseWordBuilder, ISaleStorageContract saleStorageContract,
IClientDiscountStorageContract discountStorageContract, BaseExcelBuilder baseExcelBuilder, BasePdfBuilder basePdfBuilder, IStringLocalizer<Messages> localizer)
{
_productStorageContract = productStorageContract;
_saleStorageContract = saleStorageContract;
_discountStorageContract = discountStorageContract;
_baseWordBuilder = baseWordBuilder;
_baseExcelBuilder = baseExcelBuilder;
_basePdfBuilder = basePdfBuilder;
_logger = logger;
_localizer = localizer;
_documentHeader = [_localizer["DocumentDocCaptionName"], _localizer["DocumentDocCaptionPreviousPrices"], _localizer["DocumentExcelCaptionDate"]];
_tableHeader = [_localizer["DocumentExcelCaptionDate"], _localizer["DocumentExcelCaptionFIO"], _localizer["DocumentExcelCaptionSum"], _localizer["DocumentExcelCaptionProduct"], _localizer["DocumentExcelCaptionAmount"]];
}
public Task<List<ProductProductHistoryDataModel>> GetDataProductPricesByProductAsync(CancellationToken ct)
{
_logger.LogInformation("Get data ProductPricesByProduct");
return GetDataByHistoriesAsync(ct);
}
private async Task<List<ProductProductHistoryDataModel>> GetDataByHistoriesAsync(CancellationToken ct)
{
return [.. (await _productStorageContract.GetListAsync(ct)).GroupBy(x => x.ProductName).Select(x => new ProductProductHistoryDataModel {
private async Task<List<ProductProductHistoryDataModel>> GetDataByHistoriesAsync(CancellationToken ct) =>
[.. (await _productStorageContract.GetListAsync(ct)).GroupBy(x => x.ProductName).Select(x => new ProductProductHistoryDataModel {
ProductName = x.Key, HistoryPriceProducts = [.. x.Select(y => y.OldPrice.ToString())], Data = [.. x.Select(y => y.ChangeDate.ToString())] })];
}
public async Task<Stream> CreateDocumentProductPricesByProductAsync(CancellationToken ct)
{
_logger.LogInformation("Create report ProductPricesByProduct");
var data = await GetDataByHistoriesAsync(ct) ?? throw new InvalidOperationException("No found data");
var data = await GetDataByHistoriesAsync(ct) ?? throw new InvalidOperationException(_localizer["NotFoundDataMessage"]);
var tableData = new List<string[]>
{
documentHeader
_documentHeader
};
foreach (var product in data)
{
@@ -50,11 +65,11 @@ public class ReportContract(IProductStorageContract productStorageContract, ILog
tableData.AddRange(pairs);
}
return _baseWordBuilder
.AddHeader("Истории продукта по продуктам")
.AddParagraph($"Сформировано на дату {DateTime.Now}")
.AddHeader(_localizer["DocumentDocHeaderProducts"])
.AddParagraph(string.Format(_localizer["DocumentDocSubHeader"], DateTime.UtcNow))
.AddTable(
widths: new[] { 3000, 3000, 3000 },
data: tableData
data: [.. tableData]
)
.Build();
}
@@ -69,28 +84,26 @@ public class ReportContract(IProductStorageContract productStorageContract, ILog
{
if (dateStart.IsDateNotOlder(dateFinish))
{
throw new IncorrectDatesException(dateStart, dateFinish);
throw new IncorrectDatesException(dateStart, dateFinish, _localizer);
}
return [.. (await _saleStorageContract.GetListAsync(dateStart, dateFinish, ct)).OrderBy(x => x.SaleDate)];
}
public async Task<Stream> CreateDocumentSalesByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
logger.LogInformation("Create report SalesByPeriod from {dateStart} to {dateFinish}", dateStart, dateFinish);
var data = await GetDataBySalesAsync(dateStart, dateFinish, ct) ?? throw new InvalidOperationException("No found data");
var tableHeader = new string[] { "Дата", "ФИО", "Сумма", "Продукт", "Количество" };
_logger.LogInformation("Create report SalesByPeriod from {dateStart} to {dateFinish}", dateStart, dateFinish);
var data = await GetDataBySalesAsync(dateStart, dateFinish, ct) ?? throw new InvalidOperationException(_localizer["NotFoundDataMessage"]);
return _baseExcelBuilder
.AddHeader("Заказы за период", 0, 5)
.AddParagraph($"c {dateStart.ToShortDateString()} по {dateFinish.ToShortDateString()}", 2)
.AddHeader(_localizer["DocumentExcelHeader"], 0, 5)
.AddParagraph(string.Format(_localizer["DocumentExcelSubHeader"], dateStart.ToLocalTime().ToShortDateString(), dateFinish.ToLocalTime().ToShortDateString()), 2)
.AddTable(
[10, 10, 10, 10, 10],
[.. new List<string[]>() { tableHeader }
[.. new List<string[]>() { _tableHeader }
.Union(data.SelectMany(x =>
(new List<string[]>() {
new string[] {
x.SaleDate.ToShortDateString(),
x.SaleDate.ToLocalTime().ToShortDateString(),
x.BuyerFIO,
x.Sum.ToString("N2"),
"",
@@ -107,7 +120,7 @@ public class ReportContract(IProductStorageContract productStorageContract, ILog
.ToArray()
)
.Union([[
"Всего",
_localizer["DocumentExcelCaptionTotal"],
"",
data.Sum(x => x.Sum).ToString("N2"),
"",
@@ -119,7 +132,7 @@ public class ReportContract(IProductStorageContract productStorageContract, ILog
public Task<List<ClientDiscountByPeriodDataModel>> GetDataDiscountByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
logger.LogInformation("Get data DiscountByPeriod from {dateStart} to { dateFinish}", dateStart, dateFinish);
_logger.LogInformation("Get data DiscountByPeriod from {dateStart} to { dateFinish}", dateStart, dateFinish);
return GetDataByDiscountAsync(dateStart, dateFinish, ct);
}
@@ -127,7 +140,7 @@ public class ReportContract(IProductStorageContract productStorageContract, ILog
{
if (dateStart.IsDateNotOlder(dateFinish))
{
throw new IncorrectDatesException(dateStart, dateFinish);
throw new IncorrectDatesException(dateStart, dateFinish, _localizer);
}
return [.. (await _discountStorageContract.GetListAsync(dateStart, dateFinish, ct)).GroupBy(x => x.BuyerFIO).Select(x => new ClientDiscountByPeriodDataModel
@@ -142,7 +155,10 @@ public class ReportContract(IProductStorageContract productStorageContract, ILog
{
_logger.LogInformation("Create report DiscountByPeriod from {dateStart} to { dateFinish} ", dateStart, dateFinish);
var data = await GetDataByDiscountAsync(dateStart, dateFinish, ct) ?? throw new InvalidOperationException("No found data");
return _basePdfBuilder.AddHeader("Bедомость Скидок").AddParagraph($"за период с {dateStart.ToShortDateString()} по {dateFinish.ToShortDateString()}")
.AddPieChart("Начисления", [.. data.Select(x => (x.BuyerFIO, x.TotalDiscount))]).Build();
return _basePdfBuilder
.AddHeader(_localizer["DocumentPdfHeader"])
.AddParagraph(string.Format(_localizer["DocumentPdfSubHeader"], dateStart.ToLocalTime().ToShortDateString(), dateFinish.ToLocalTime().ToShortDateString()))
.AddPieChart(_localizer["DocumentPdfDiagramCaption"], [.. data.Select(x => (x.BuyerFIO, x.TotalDiscount))]).Build();
}
}

View File

@@ -2,34 +2,38 @@
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.Extensions;
using DaisiesContracts.StoragesContracts;
using DaisiesContracts.Resources;
using DaisiesContracts.Resources.StoragesContracts;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace DaisiesBuisnessLogic.Implementations;
public class SaleBusinessLogicContract(ISaleStorageContract saleStorageContract, ILogger logger) : ISaleBuisnessLogicContract
internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : ISaleBuisnessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
public List<SaleDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate)
private readonly ISaleStorageContract _saleStorageContract =
saleStorageContract;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<SaleDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime
toDate)
{
_logger.LogInformation("GetAllSales params: {fromDate}, {toDate}", fromDate, toDate);
_logger.LogInformation("GetAllSales params: {fromDate}, {toDate}",
fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
throw new IncorrectDatesException(fromDate, toDate, _localizer);
}
return _saleStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
return _saleStorageContract.GetList(fromDate, toDate);
}
public List<SaleDataModel> GetAllSalesByWorkerByPeriod(string workerId, DateTime fromDate, DateTime toDate)
public List<SaleDataModel> GetAllSalesByWorkerByPeriod(string workerId,
DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {workerId}, {fromDate}, {toDate}", workerId, fromDate, toDate);
_logger.LogInformation("GetAllSales params: {workerId}, {fromDate},{ toDate} ", workerId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
throw new IncorrectDatesException(fromDate, toDate, _localizer);
}
if (workerId.IsEmpty())
{
@@ -37,17 +41,18 @@ public class SaleBusinessLogicContract(ISaleStorageContract saleStorageContract,
}
if (!workerId.IsGuid())
{
throw new ValidationException("The value in the field workerId is not a unique identifier.");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "workerId"));
}
return _saleStorageContract.GetList(fromDate, toDate, workerId: workerId) ?? throw new NullListException();
return _saleStorageContract.GetList(fromDate, toDate, workerId:
workerId);
}
public List<SaleDataModel> GetAllSalesByBuyerByPeriod(string buyerId, DateTime fromDate, DateTime toDate)
public List<SaleDataModel> GetAllSalesByBuyerByPeriod(string buyerId,
DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {buyerId}, {fromDate}, {toDate}", buyerId, fromDate, toDate);
_logger.LogInformation("GetAllSales params: {buyerId}, {fromDate}, { toDate} ", buyerId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
throw new IncorrectDatesException(fromDate, toDate, _localizer);
}
if (buyerId.IsEmpty())
{
@@ -55,17 +60,18 @@ public class SaleBusinessLogicContract(ISaleStorageContract saleStorageContract,
}
if (!buyerId.IsGuid())
{
throw new ValidationException("The value in the field buyerId is not a unique identifier.");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "buyerId"));
}
return _saleStorageContract.GetList(fromDate, toDate, buyerId: buyerId) ?? throw new NullListException();
return _saleStorageContract.GetList(fromDate, toDate, buyerId:
buyerId);
}
public List<SaleDataModel> GetAllSalesByProductByPeriod(string productId, DateTime fromDate, DateTime toDate)
public List<SaleDataModel> GetAllSalesByProductByPeriod(string productId,
DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {productId}, {fromDate}, {toDate}", productId, fromDate, toDate);
_logger.LogInformation("GetAllSales params: {productId}, {fromDate}, { toDate} ", productId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
throw new IncorrectDatesException(fromDate, toDate, _localizer);
}
if (productId.IsEmpty())
{
@@ -73,11 +79,11 @@ public class SaleBusinessLogicContract(ISaleStorageContract saleStorageContract,
}
if (!productId.IsGuid())
{
throw new ValidationException("The value in the field productId is not a unique identifier.");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "productId"));
}
return _saleStorageContract.GetList(fromDate, toDate, productId: productId) ?? throw new NullListException();
return _saleStorageContract.GetList(fromDate, toDate, productId:
productId);
}
public SaleDataModel GetSaleByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
@@ -87,19 +93,19 @@ public class SaleBusinessLogicContract(ISaleStorageContract saleStorageContract,
}
if (!data.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
}
return _saleStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return _saleStorageContract.GetElementById(data) ?? throw new
ElementNotFoundException(data, _localizer);
}
public void InsertSale(SaleDataModel saleDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(saleDataModel));
_logger.LogInformation("New data: {json}",
JsonSerializer.Serialize(saleDataModel));
ArgumentNullException.ThrowIfNull(saleDataModel);
saleDataModel.Validate();
saleDataModel.Validate(_localizer);
_saleStorageContract.AddElement(saleDataModel);
}
public void CancelSale(string id)
{
_logger.LogInformation("Cancel by id: {id}", id);
@@ -109,7 +115,7 @@ public class SaleBusinessLogicContract(ISaleStorageContract saleStorageContract,
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
}
_saleStorageContract.DelElement(id);
}

View File

@@ -1,58 +1,64 @@
using DaisiesContracts.BuisnessLogicContracts;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using DaisiesContracts.BuisnessLogicContracts;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using DaisiesContracts.Extensions;
using DaisiesContracts.Resources;
using DaisiesContracts.Resources.StoragesContracts;
using System.Text.Json;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace DaisiesBuisnessLogic.Implementations;
public class WorkerBuisnessLogicContract(IWorkerStorageContract workerStorageContract, ILogger logger) : IWorkerBuisnessLogicContract
internal class WorkerBuisnessLogicContract(IWorkerStorageContract workerStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : IWorkerBuisnessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IWorkerStorageContract _workerStorageContract = workerStorageContract;
private readonly IWorkerStorageContract _workerStorageContract =
workerStorageContract;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<WorkerDataModel> GetAllWorkers(bool onlyActive = true)
{
_logger.LogInformation("GetAllWorkers params: {onlyActive}", onlyActive);
return _workerStorageContract.GetList(onlyActive) ?? throw new NullListException();
_logger.LogInformation("GetAllWorkers params: {onlyActive}",
onlyActive);
return _workerStorageContract.GetList(onlyActive);
}
public List<WorkerDataModel> GetAllWorkersByPost(string postId, bool onlyActive = true)
public List<WorkerDataModel> GetAllWorkersByPost(string postId, bool
onlyActive = true)
{
_logger.LogInformation("GetAllWorkers params: {postId}, {onlyActive},", postId, onlyActive);
_logger.LogInformation("GetAllWorkers params: {postId}, { onlyActive},", postId, onlyActive);
if (postId.IsEmpty())
{
throw new ArgumentNullException(nameof(postId));
}
if (!postId.IsGuid())
{
throw new ValidationException("The value in the field postId is not a unique identifier.");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "PostId"));
}
return _workerStorageContract.GetList(onlyActive, postId) ?? throw new NullListException();
return _workerStorageContract.GetList(onlyActive, postId);
}
public List<WorkerDataModel> GetAllWorkersByBirthDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
public List<WorkerDataModel> GetAllWorkersByBirthDate(DateTime fromDate,
DateTime toDate, bool onlyActive = true)
{
_logger.LogInformation("GetAllWorkers params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
_logger.LogInformation("GetAllWorkers params: {onlyActive}, { fromDate}, { toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
throw new IncorrectDatesException(fromDate, toDate, _localizer);
}
return _workerStorageContract.GetList(onlyActive, fromBirthDate: fromDate, toBirthDate: toDate) ?? throw new NullListException();
return _workerStorageContract.GetList(onlyActive, fromBirthDate:
fromDate, toBirthDate: toDate);
}
public List<WorkerDataModel> GetAllWorkersByEmploymentDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
{
_logger.LogInformation("GetAllWorkers params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
_logger.LogInformation("getallworkers params: {onlyactive}, { fromdate}, { todate} ", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
throw new IncorrectDatesException(fromDate, toDate, _localizer);
}
return _workerStorageContract.GetList(onlyActive, fromEmploymentDate: fromDate, toEmploymentDate: toDate) ?? throw new NullListException();
return _workerStorageContract.GetList(onlyActive, fromEmploymentDate:
fromDate, toEmploymentDate: toDate);
}
public WorkerDataModel GetWorkerByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
@@ -62,28 +68,28 @@ public class WorkerBuisnessLogicContract(IWorkerStorageContract workerStorageCon
}
if (data.IsGuid())
{
return _workerStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return _workerStorageContract.GetElementById(data) ?? throw
new ElementNotFoundException(data, _localizer);
}
return _workerStorageContract.GetElementByFIO(data) ?? throw new ElementNotFoundException(data);
return _workerStorageContract.GetElementByFIO(data) ?? throw new
ElementNotFoundException(data, _localizer);
}
public void InsertWorker(WorkerDataModel workerDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(workerDataModel));
_logger.LogInformation("New data: {json}",
JsonSerializer.Serialize(workerDataModel));
ArgumentNullException.ThrowIfNull(workerDataModel);
workerDataModel.Validate();
workerDataModel.Validate(_localizer);
_workerStorageContract.AddElement(workerDataModel);
}
public void UpdateWorker(WorkerDataModel workerDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(workerDataModel));
_logger.LogInformation("Update data: {json}",
JsonSerializer.Serialize(workerDataModel));
ArgumentNullException.ThrowIfNull(workerDataModel);
workerDataModel.Validate();
workerDataModel.Validate(_localizer);
_workerStorageContract.UpdElement(workerDataModel);
}
public void DeleteWorker(string id)
{
_logger.LogInformation("Delete by id: {id}", id);
@@ -93,7 +99,7 @@ public class WorkerBuisnessLogicContract(IWorkerStorageContract workerStorageCon
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
}
_workerStorageContract.DelElement(id);
}

View File

@@ -2,7 +2,7 @@
namespace DaisiesContracts.BuisnessLogicContracts;
public interface IBuyerBuisnessLogicContract
internal interface IBuyerBuisnessLogicContract
{
List<BuyerDataModel> GetAllBuyers();

View File

@@ -2,7 +2,7 @@
namespace DaisiesContracts.BuisnessLogicContracts;
public interface IClientDiscountBuisnessLogicContract
internal interface IClientDiscountBuisnessLogicContract
{
List<ClientDiscountDataModel> GetAllClientDiscounts();

View File

@@ -2,7 +2,7 @@
namespace DaisiesContracts.BuisnessLogicContracts;
public interface IPostBuisnessLogicContract
internal interface IPostBuisnessLogicContract
{
List<PostDataModel> GetAllPosts();

View File

@@ -2,7 +2,7 @@
namespace DaisiesContracts.BuisnessLogicContracts;
public interface IProductBuisnessLogicContract
internal interface IProductBuisnessLogicContract
{
List<ProductDataModel> GetAllProducts(bool onlyActive = true);
List<ProductDataModel> GetAllProductsBySupplier(string supplierId, bool onlyActive = true);

View File

@@ -2,7 +2,7 @@
namespace DaisiesContracts.BuisnessLogicContracts;
public interface IReportContract
internal interface IReportContract
{
Task<List<ProductProductHistoryDataModel>> GetDataProductPricesByProductAsync(CancellationToken ct);

View File

@@ -2,7 +2,7 @@
namespace DaisiesContracts.BuisnessLogicContracts;
public interface ISaleBuisnessLogicContract
internal interface ISaleBuisnessLogicContract
{
List<SaleDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate);

View File

@@ -2,7 +2,7 @@
namespace DaisiesContracts.BuisnessLogicContracts;
public interface IWorkerBuisnessLogicContract
internal interface IWorkerBuisnessLogicContract
{
List<WorkerDataModel> GetAllWorkers(bool onlyActive = true);
List<WorkerDataModel> GetAllWorkersByPost(string postId, bool onlyActive = true);

View File

@@ -8,7 +8,39 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.3.0" />
<PackageReference Include="Microsoft.Extensions.Localization" Version="9.0.5" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.5" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="DaisiesBusinessLogic" />
<InternalsVisibleTo Include="DaisiesDatabase" />
<InternalsVisibleTo Include="DaisiesApi" />
<InternalsVisibleTo Include="DaisiesTests" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
<ItemGroup>
<Compile Update="Resources\Messages.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Messages.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Resources\Messages.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Messages.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="Resources\Messages.en-US">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Messages.Designer.cs</LastGenOutput>
</None>
</ItemGroup>
</Project>

View File

@@ -5,10 +5,12 @@ using DaisiesContracts.Exceptions;
using DaisiesContracts.Infrastructure.BuyerConfigurations;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Microsoft.Extensions.Localization;
using DaisiesContracts.Resources;
namespace DaisiesContracts.DataModels;
public class BuyerDataModel : IValidation
internal class BuyerDataModel : IValidation
{
public string Id { get; private set; }
@@ -41,24 +43,24 @@ public class BuyerDataModel : IValidation
}
}
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
if (FIO.IsEmpty())
throw new ValidationException("Field FIO is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "FIO"));
if (!Regex.IsMatch(FIO, @"^([А-ЯЁ][а-яё]*(-[А-ЯЁ][а-яё]*)?)\s([А-ЯЁ]\.?\s?([А-ЯЁ]\.?\s?)?)?$"))
throw new ValidationException("Field FIO is not a fio");
if (PhoneNumber.IsEmpty()) throw new ValidationException("Field PhoneNumber is empty");
if (!Regex.IsMatch(PhoneNumber, @"^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\-]?)?[\d\- ]{7,10}$")) throw new ValidationException("Field PhoneNumber is not a phone number");
throw new ValidationException(localizer["ValidationExceptionMessageIncorrectFIO"]);
if (PhoneNumber.IsEmpty()) throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "PhoneNumber"));
if (!Regex.IsMatch(PhoneNumber, @"^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\-]?)?[\d\- ]{7,10}$")) throw new ValidationException(localizer["ValidationExceptionMessageIncorrectPhoneNumber"]);
if (ConfigurationModel is null)
throw new ValidationException("Field ConfigurationModel is not initialized");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotInitialized"], "ConfigurationModel"));
if (ConfigurationModel!.DiscountMultiplier < 0)
throw new ValidationException("Field DiscountRate is less zero");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessZero"], "DiscountRate"));
if (ConfigurationModel!.DiscountMultiplier > 1)
throw new ValidationException("Field DiscountRate is more one");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageMoreOne"], "DiscountRate"));
}
public BuyerDataModel()
{

View File

@@ -1,5 +1,5 @@
namespace DaisiesContracts.DataModels;
public class ClientDiscountByPeriodDataModel
internal class ClientDiscountByPeriodDataModel
{
public required string BuyerFIO { get; set; }
public double TotalDiscount { get; set; }

View File

@@ -1,10 +1,12 @@
using DaisiesContracts.Exceptions;
using DaisiesContracts.Extensions;
using DaisiesContracts.Infrastructure;
using DaisiesContracts.Resources;
using Microsoft.Extensions.Localization;
namespace DaisiesContracts.DataModels;
public class ClientDiscountDataModel(string buyerId, double totalSum, double personalDiscount, DateTime? discountDate = null) : IValidation
internal class ClientDiscountDataModel(string buyerId, double totalSum, double personalDiscount, DateTime? discountDate = null) : IValidation
{
private readonly BuyerDataModel? _buyer;
@@ -28,27 +30,27 @@ public class ClientDiscountDataModel(string buyerId, double totalSum, double per
_buyer = buyer;
}
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (BuyerId.IsEmpty())
{
throw new ValidationException("Field Id is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
}
if (!BuyerId.IsGuid())
{
throw new ValidationException("The value in the field Id is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
}
if (TotalSum < 0)
{
throw new ValidationException("TotalSum cannot be less than zero");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessZero"], "TotalSum"));
}
if (PersonalDiscount < 0)
{
throw new ValidationException("PersonalDiscount cannot be less than zero");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessZero"], "PersonalDiscount"));
}
}
}

View File

@@ -2,10 +2,12 @@
using DaisiesContracts.Exceptions;
using DaisiesContracts.Extensions;
using DaisiesContracts.Infrastructure;
using DaisiesContracts.Resources;
using Microsoft.Extensions.Localization;
namespace DaisiesContracts.DataModels;
public class PostDataModel(string postId, string postName, PostType postType, double salary) : IValidation
internal class PostDataModel(string postId, string postName, PostType postType, double salary) : IValidation
{
public string Id { get; private set; } = postId;
@@ -15,21 +17,21 @@ public class PostDataModel(string postId, string postName, PostType postType, do
public double Salary { get; private set; } = salary;
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
if (PostName.IsEmpty())
throw new ValidationException("Field PostName is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "PostName"));
if (PostType == PostType.None)
throw new ValidationException("Field PostType is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "PostType"));
if (Salary <= 0)
throw new ValidationException("Field Salary is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessZero"], "Salary"));
}
}

View File

@@ -2,10 +2,12 @@
using DaisiesContracts.Exceptions;
using DaisiesContracts.Extensions;
using DaisiesContracts.Infrastructure;
using DaisiesContracts.Resources;
using Microsoft.Extensions.Localization;
namespace DaisiesContracts.DataModels;
public class ProductDataModel : IValidation
internal class ProductDataModel : IValidation
{
public string Id { get; private set; }
public string ProductName { get; private set; }
@@ -28,20 +30,20 @@ public class ProductDataModel : IValidation
IsDeleted = isDeleted;
}
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty()) { throw new ValidationException("Field Id is empty"); }
if (Id.IsEmpty()) { throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id")); }
if (!Id.IsGuid()) { throw new ValidationException("The value in the field Id is a unique identifier"); }
if (!Id.IsGuid()) { throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id")); }
if (ProductName.IsEmpty()) { throw new ValidationException("Field Id is empty"); }
if (ProductName.IsEmpty()) { throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "ProductName")); }
if (ProductType == ProductType.None) { throw new ValidationException("Field ProductType is empty"); }
if (ProductType == ProductType.None) { throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "ProductType")); }
if (SupplierId.IsEmpty()) { throw new ValidationException("Field SupplierId is empty"); }
if (SupplierId.IsEmpty()) { throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "SupplierId")); }
if (!SupplierId.IsGuid()) { throw new ValidationException("The value in the field SupplierId is not a unique identifier"); }
if (!SupplierId.IsGuid()) { throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "SupplierId")); }
if (Price <= 0) { throw new ValidationException("Field Prise is less than or equal to 0"); }
if (Price <= 0) { throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessZero"], "Price")); }
}
}

View File

@@ -1,17 +1,19 @@
using DaisiesContracts.Exceptions;
using DaisiesContracts.Extensions;
using DaisiesContracts.Infrastructure;
using DaisiesContracts.Resources;
using Microsoft.Extensions.Localization;
namespace DaisiesContracts.DataModels;
public class ProductHistoryDataModel(string productId, double oldPrice) : IValidation
internal class ProductHistoryDataModel(string productId, double oldPrice) : IValidation
{
public ProductHistoryDataModel() : this(string.Empty, 0) { }
private readonly ProductDataModel? _product;
public string ProductId { get; private set; } = productId;
public double OldPrice { get; private set; } = oldPrice;
public DateTime ChangeDate { get; private set; } = DateTime.UtcNow;
public DateTime ChangeDate { get; private set; } = DateTime.UtcNow.ToUniversalTime();
public string ProductName => _product?.ProductName ?? string.Empty;
public ProductHistoryDataModel(
@@ -20,16 +22,16 @@ public class ProductHistoryDataModel(string productId, double oldPrice) : IValid
DateTime changeDate,
ProductDataModel product) : this(productId, oldPrice)
{
ChangeDate = changeDate;
ChangeDate = changeDate.ToUniversalTime();
_product = product;
}
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (ProductId.IsEmpty()) { throw new ValidationException("Field ProductId is empty"); }
if (ProductId.IsEmpty()) { throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "ProductId")); }
if (!ProductId.IsGuid()) { throw new ValidationException("The value in the field ProductId is a unique identifier"); }
if (!ProductId.IsGuid()) { throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "ProductId")); }
if (OldPrice <= 0) { throw new ValidationException("Field OldPrice is less than or equal to 0"); }
if (OldPrice <= 0) { throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessZero"], "OldPrice")); }
}
}

View File

@@ -1,6 +1,6 @@
namespace DaisiesContracts.DataModels;
public class ProductProductHistoryDataModel
internal class ProductProductHistoryDataModel
{
public required string ProductName { get; set; }
public required List<string> HistoryPriceProducts { get; set; }

View File

@@ -2,8 +2,10 @@
using DaisiesContracts.Exceptions;
using DaisiesContracts.Extensions;
using DaisiesContracts.Infrastructure;
using DaisiesContracts.Resources;
using Microsoft.Extensions.Localization;
public class SaleDataModel: IValidation
internal class SaleDataModel: IValidation
{
public string Id { get; private set; }
@@ -28,7 +30,7 @@ public class SaleDataModel: IValidation
public string WorkerFIO => _worker?.FIO ?? string.Empty;
public SaleDataModel(string id, string workerId, string? buyerId, DateTime saleDate, double sum, bool isCancel, List<SaleProductDataModel> saleProducts, WorkerDataModel worker, BuyerDataModel? buyer) : this(id, workerId, buyerId, sum, isCancel, saleProducts)
{
SaleDate = saleDate;
SaleDate = saleDate.ToUniversalTime();
_worker = worker;
_buyer = buyer;
}
@@ -47,27 +49,28 @@ public class SaleDataModel: IValidation
Products = products;
}
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
if (WorkerId.IsEmpty())
throw new ValidationException("Field WorkerId is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "WorkerId"));
if (!WorkerId.IsGuid())
throw new ValidationException("The value in the field WorkerId is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "WorkerId"));
if (!BuyerId?.IsGuid() ?? !BuyerId?.IsEmpty() ?? false)
throw new ValidationException("The value in the field BuyerId is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "BuyerId"));
if (Sum <= 0)
throw new ValidationException("Field Sum is less than or equal to 0");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessZero"], "Salary"));
if ((Products?.Count ?? 0) == 0)
throw new ValidationException("The sale must include products");
throw new ValidationException(localizer["ValidationExceptionMessageNoProducts"]);
}
}

View File

@@ -1,10 +1,12 @@
using DaisiesContracts.Exceptions;
using DaisiesContracts.Extensions;
using DaisiesContracts.Infrastructure;
using DaisiesContracts.Resources;
using Microsoft.Extensions.Localization;
namespace DaisiesContracts.DataModels;
public class SaleProductDataModel(string saleId, string productId, int count) : IValidation
internal class SaleProductDataModel(string saleId, string productId, int count) : IValidation
{
private readonly ProductDataModel? _product;
@@ -17,16 +19,16 @@ public class SaleProductDataModel(string saleId, string productId, int count) :
_product = product;
}
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (SaleId.IsEmpty()) { throw new ValidationException("Field SaleId is empty"); }
if (SaleId.IsEmpty()) { throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "SaleId")); }
if (!SaleId.IsGuid()) { throw new ValidationException("The value in the field SaleId is a unique identifier"); }
if (!SaleId.IsGuid()) { throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "SaleId")); }
if (ProductId.IsEmpty()) { throw new ValidationException("Field ProductId is empty"); }
if (ProductId.IsEmpty()) { throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "ProductId")); }
if (!ProductId.IsGuid()) { throw new ValidationException("The value in the field ProductId is a unique identifier"); }
if (!ProductId.IsGuid()) { throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "ProductId")); }
if (Count <= 0) { throw new ValidationException("Field Count is less than or equal to 0"); }
if (Count <= 0) { throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessZero"], "Count")); }
}
}

View File

@@ -1,17 +1,20 @@
using DaisiesContracts.Exceptions;
using DaisiesContracts.Extensions;
using DaisiesContracts.Infrastructure;
using DaisiesContracts.Resources;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Localization;
using System.Text.RegularExpressions;
namespace DaisiesContracts.DataModels;
public class WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted) : IValidation
internal class WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted) : IValidation
{
public string Id { get; private set; } = id;
public string FIO { get; private set; } = fio;
public string PostId { get; private set; } = postId;
public DateTime BirthDate { get; private set; } = birthDate;
public DateTime EmploymentDate { get; private set; } = employmentDate;
public DateTime BirthDate { get; private set; } = birthDate.ToUniversalTime();
public DateTime EmploymentDate { get; private set; } = employmentDate.ToUniversalTime();
public bool IsDeleted { get; private set; } = isDeleted;
private readonly PostDataModel? _post;
@@ -29,22 +32,24 @@ public class WorkerDataModel(string id, string fio, string postId, DateTime birt
{
}
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty()) { throw new ValidationException("Field Id is empty"); }
if (Id.IsEmpty()) { throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id")); }
if (!Id.IsGuid()) { throw new ValidationException("The value in the field Id is a unique identifier"); }
if (!Id.IsGuid()) { throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id")); }
if (FIO.IsEmpty()) { throw new ValidationException("Field FIO is empty"); }
if (FIO.IsEmpty()) { throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "FIO")); }
if (!Regex.IsMatch(FIO, @"^([А-ЯЁ][а-яё]*(-[А-ЯЁ][а-яё]*)?)\s([А-ЯЁ]\.?\s?([А-ЯЁ]\.?\s?)?)?$")) { throw new ValidationException(localizer["ValidationExceptionMessageIncorrectFIO"]); }
if (PostId.IsEmpty()) { throw new ValidationException("Field PostId is empty"); }
if (PostId.IsEmpty()) { throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "PostId")); }
if (!PostId.IsGuid()) { throw new ValidationException("The value in the field PostId is a unique identifier"); }
if (!PostId.IsGuid()) { throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "PostId")); }
if (BirthDate.Date > DateTime.Now.AddYears(-16).Date) { throw new ValidationException($"Minors cannot be hired (BirthDate = {BirthDate.ToShortDateString()})"); }
if (BirthDate.Date > DateTime.UtcNow.AddYears(-16).Date) { throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmploymentDateAndBirthDate"], EmploymentDate.ToShortDateString(), BirthDate.ToShortDateString())); }
if (EmploymentDate.Date < BirthDate.Date) { throw new ValidationException("The date of employment cannot be less than the date of birth"); }
if (EmploymentDate.Date < BirthDate.Date) { throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmploymentDateAndBirthDate"], EmploymentDate.ToShortDateString(), BirthDate.ToShortDateString())); }
if ((EmploymentDate - BirthDate).TotalDays / 365 < 16) { throw new ValidationException($"Minors cannot be hired (EmploymentDate - {EmploymentDate.ToShortDateString()}, BirthDate - {BirthDate.ToShortDateString()})"); }
if ((EmploymentDate - BirthDate).TotalDays / 365 < 16) { throw new ValidationException(string.Format(localizer["ValidationExceptionMessageMinorsEmploymentDate"], EmploymentDate.ToShortDateString(), BirthDate.ToShortDateString())); }
}
}

View File

@@ -1,6 +1,6 @@
namespace DaisiesContracts.Exceptions;
using DaisiesContracts.Resources;
using Microsoft.Extensions.Localization;
public class ElementDeletedException : Exception
{
public ElementDeletedException(string id) : base($"Cannot modify a deleted item (id: {id})") { }
}
namespace DaisiesContracts.Exceptions;
internal class ElementDeletedException(string id, IStringLocalizer<Messages> localizer) : Exception(string.Format(localizer["ElementDeletedExceptionMessage"], id)) { }

View File

@@ -1,14 +1,11 @@
namespace DaisiesContracts.Exceptions;
using DaisiesContracts.Resources;
using Microsoft.Extensions.Localization;
public class ElementExistsException : Exception
namespace DaisiesContracts.Exceptions;
internal class ElementExistsException(string paramName, string paramValue, IStringLocalizer<Messages> localizer) : Exception(string.Format(localizer["ElementExistsExceptionMessage"], paramValue, paramName))
{
public string ParamName { get; private set; }
public string ParamName { get; private set; } = paramName;
public string ParamValue { get; private set; }
public ElementExistsException(string paramName, string paramValue) : base($"There is already an element with value{paramValue} of parameter { paramName}")
{
ParamName = paramName;
ParamValue = paramValue;
}
}
public string ParamValue { get; private set; } = paramValue;
}

View File

@@ -1,11 +1,10 @@
namespace DaisiesContracts.Exceptions;
using DaisiesContracts.Resources;
using Microsoft.Extensions.Localization;
public class ElementNotFoundException : Exception
namespace DaisiesContracts.Exceptions;
internal class ElementNotFoundException(string value, IStringLocalizer<Messages> localizer) :
Exception(string.Format(localizer["ElementNotFoundExceptionMessage"], value))
{
public string Value { get; private set; }
public ElementNotFoundException(string value) : base($"Element not found at value = { value}")
{
Value = value;
}
public string Value { get; private set; } = value;
}

View File

@@ -1,8 +1,9 @@
using static System.Runtime.InteropServices.JavaScript.JSType;
using DaisiesContracts.Resources;
using Microsoft.Extensions.Localization;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace DaisiesContracts.Exceptions;
public class IncorrectDatesException : Exception
{
public IncorrectDatesException(DateTime start, DateTime end) : base($"The end date must be later than the start date..StartDate: { start: dd.MM.YYYY}. EndDate: {end:dd.MM.YYYY}") { }
}
internal class IncorrectDatesException(DateTime start, DateTime end, IStringLocalizer<Messages> localizer) :
Exception(string.Format(localizer["IncorrectDatesExceptionMessage"], start.ToShortDateString(), end.ToShortDateString()))
{ }

View File

@@ -1,6 +0,0 @@
namespace DaisiesContracts.Exceptions;
public class NullListException : Exception
{
public NullListException() : base("The returned list is null") { }
}

View File

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

View File

@@ -1,6 +1,9 @@
namespace DaisiesContracts.Infrastructure;
using DaisiesContracts.Resources;
using Microsoft.Extensions.Localization;
public interface IValidation
namespace DaisiesContracts.Infrastructure;
internal interface IValidation
{
void Validate();
void Validate(IStringLocalizer<Messages> localizer);
}

View File

@@ -0,0 +1,432 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DaisiesContracts.Resources {
using System;
/// <summary>
/// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
/// </summary>
// Этот класс создан автоматически классом StronglyTypedResourceBuilder
// с помощью такого средства, как ResGen или Visual Studio.
// Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
// с параметром /str или перестройте свой проект VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Messages {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Messages() {
}
/// <summary>
/// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DaisiesContracts.Resources.Messages", typeof(Messages).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Не найден элемент по данным: {0}.
/// </summary>
internal static string AdapterMessageElementNotFoundException {
get {
return ResourceManager.GetString("AdapterMessageElementNotFoundException", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Данные пусты.
/// </summary>
internal static string AdapterMessageEmptyDate {
get {
return ResourceManager.GetString("AdapterMessageEmptyDate", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Неправильные даты: {0}.
/// </summary>
internal static string AdapterMessageIncorrectDatesException {
get {
return ResourceManager.GetString("AdapterMessageIncorrectDatesException", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Ошибка при обработке данных: {0}.
/// </summary>
internal static string AdapterMessageInvalidOperationException {
get {
return ResourceManager.GetString("AdapterMessageInvalidOperationException", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Ошибка при работе с хранилищем данных: {0}.
/// </summary>
internal static string AdapterMessageStorageException {
get {
return ResourceManager.GetString("AdapterMessageStorageException", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Переданы неверные данные: {0}.
/// </summary>
internal static string AdapterMessageValidationException {
get {
return ResourceManager.GetString("AdapterMessageValidationException", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Название.
/// </summary>
internal static string DocumentDocCaptionName {
get {
return ResourceManager.GetString("DocumentDocCaptionName", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Предыдущие стоимости.
/// </summary>
internal static string DocumentDocCaptionPreviousPrices {
get {
return ResourceManager.GetString("DocumentDocCaptionPreviousPrices", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на История изменения продуктов.
/// </summary>
internal static string DocumentDocHeaderProducts {
get {
return ResourceManager.GetString("DocumentDocHeaderProducts", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Сформировано на дату {0}.
/// </summary>
internal static string DocumentDocSubHeader {
get {
return ResourceManager.GetString("DocumentDocSubHeader", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Количество.
/// </summary>
internal static string DocumentExcelCaptionAmount {
get {
return ResourceManager.GetString("DocumentExcelCaptionAmount", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Дата.
/// </summary>
internal static string DocumentExcelCaptionDate {
get {
return ResourceManager.GetString("DocumentExcelCaptionDate", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на ФИО.
/// </summary>
internal static string DocumentExcelCaptionFIO {
get {
return ResourceManager.GetString("DocumentExcelCaptionFIO", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Продукт.
/// </summary>
internal static string DocumentExcelCaptionProduct {
get {
return ResourceManager.GetString("DocumentExcelCaptionProduct", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Продажа.
/// </summary>
internal static string DocumentExcelCaptionSale {
get {
return ResourceManager.GetString("DocumentExcelCaptionSale", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Сумма.
/// </summary>
internal static string DocumentExcelCaptionSum {
get {
return ResourceManager.GetString("DocumentExcelCaptionSum", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Всего.
/// </summary>
internal static string DocumentExcelCaptionTotal {
get {
return ResourceManager.GetString("DocumentExcelCaptionTotal", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Работник.
/// </summary>
internal static string DocumentExcelCaptionWorker {
get {
return ResourceManager.GetString("DocumentExcelCaptionWorker", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Продажи за период.
/// </summary>
internal static string DocumentExcelHeader {
get {
return ResourceManager.GetString("DocumentExcelHeader", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на c {0} по {1}.
/// </summary>
internal static string DocumentExcelSubHeader {
get {
return ResourceManager.GetString("DocumentExcelSubHeader", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Начисления.
/// </summary>
internal static string DocumentPdfDiagramCaption {
get {
return ResourceManager.GetString("DocumentPdfDiagramCaption", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Bедомость скидок.
/// </summary>
internal static string DocumentPdfHeader {
get {
return ResourceManager.GetString("DocumentPdfHeader", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на с {0} по {1}.
/// </summary>
internal static string DocumentPdfSubHeader {
get {
return ResourceManager.GetString("DocumentPdfSubHeader", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Нельзя изменить удаленный элемент (идентификатор: {0}).
/// </summary>
internal static string ElementDeletedExceptionMessage {
get {
return ResourceManager.GetString("ElementDeletedExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Уже существует элемент со значением {0} параметра {1}.
/// </summary>
internal static string ElementExistsExceptionMessage {
get {
return ResourceManager.GetString("ElementExistsExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Элемент не найден по значению = {0}.
/// </summary>
internal static string ElementNotFoundExceptionMessage {
get {
return ResourceManager.GetString("ElementNotFoundExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Дата окончания должна быть позже даты начала. Дата начала: {0}. ​​Дата окончания: {1}.
/// </summary>
internal static string IncorrectDatesExceptionMessage {
get {
return ResourceManager.GetString("IncorrectDatesExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Недостаточно данных для обработки: {0}.
/// </summary>
internal static string NotEnoughDataToProcessExceptionMessage {
get {
return ResourceManager.GetString("NotEnoughDataToProcessExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Не найдены данные.
/// </summary>
internal static string NotFoundDataMessage {
get {
return ResourceManager.GetString("NotFoundDataMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Ошибка при работе в хранилище: {0}.
/// </summary>
internal static string StorageExceptionMessage {
get {
return ResourceManager.GetString("StorageExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Дата трудоустройства не может быть раньше даты рождения ({0}, {1}).
/// </summary>
internal static string ValidationExceptionMessageEmploymentDateAndBirthDate {
get {
return ResourceManager.GetString("ValidationExceptionMessageEmploymentDateAndBirthDate", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле {0} пусто.
/// </summary>
internal static string ValidationExceptionMessageEmptyField {
get {
return ResourceManager.GetString("ValidationExceptionMessageEmptyField", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Некорректный формат ФИО.
/// </summary>
internal static string ValidationExceptionMessageIncorrectFIO {
get {
return ResourceManager.GetString("ValidationExceptionMessageIncorrectFIO", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Некорректный формат номера телефона.
/// </summary>
internal static string ValidationExceptionMessageIncorrectPhoneNumber {
get {
return ResourceManager.GetString("ValidationExceptionMessageIncorrectPhoneNumber", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле {0} меньше или равно 0.
/// </summary>
internal static string ValidationExceptionMessageLessZero {
get {
return ResourceManager.GetString("ValidationExceptionMessageLessZero", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Несовершеннолетние не могут быть приняты на работу (Дата рождения: {0}).
/// </summary>
internal static string ValidationExceptionMessageMinorsBirthDate {
get {
return ResourceManager.GetString("ValidationExceptionMessageMinorsBirthDate", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Несовершеннолетние не могут быть приняты на работу (Дата трудоустройства: {0}, Дата рождения: {1}).
/// </summary>
internal static string ValidationExceptionMessageMinorsEmploymentDate {
get {
return ResourceManager.GetString("ValidationExceptionMessageMinorsEmploymentDate", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле {0} больше единицы.
/// </summary>
internal static string ValidationExceptionMessageMoreOne {
get {
return ResourceManager.GetString("ValidationExceptionMessageMoreOne", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Отсутствуют продукты.
/// </summary>
internal static string ValidationExceptionMessageNoProducts {
get {
return ResourceManager.GetString("ValidationExceptionMessageNoProducts", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле {0} не является типом уникального идентификатора.
/// </summary>
internal static string ValidationExceptionMessageNotAId {
get {
return ResourceManager.GetString("ValidationExceptionMessageNotAId", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле {0} не проиницализировано.
/// </summary>
internal static string ValidationExceptionMessageNotInitialized {
get {
return ResourceManager.GetString("ValidationExceptionMessageNotInitialized", resourceCulture);
}
}
}
}

View File

@@ -0,0 +1,101 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 1.3
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">1.3</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1">this is my long string</data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
[base64 mime encoded serialized .NET Framework object]
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
[base64 mime encoded string representing a byte array form of the .NET Framework object]
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>1.3</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@@ -0,0 +1,243 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="AdapterMessageElementNotFoundException" xml:space="preserve">
<value>Not found element by data: {0}</value>
</data>
<data name="AdapterMessageEmptyDate" xml:space="preserve">
<value>Data is empty</value>
</data>
<data name="AdapterMessageIncorrectDatesException" xml:space="preserve">
<value>Incorrect dates: {0}</value>
</data>
<data name="AdapterMessageInvalidOperationException" xml:space="preserve">
<value>Error processing data: {0}</value>
</data>
<data name="AdapterMessageStorageException" xml:space="preserve">
<value>Error while working with data storage: {0}</value>
</data>
<data name="AdapterMessageValidationException" xml:space="preserve">
<value>Incorrect data transmitted: {0}</value>
</data>
<data name="DocumentDocCaptionName" xml:space="preserve">
<value>Names</value>
</data>
<data name="DocumentDocCaptionPreviousPrices" xml:space="preserve">
<value>Previous prices</value>
</data>
<data name="NotFoundDataMessage" xml:space="preserve">
<value>No data found</value>
</data>
<data name="ValidationExceptionMessageEmptyField" xml:space="preserve">
<value>The value in field {0} is empty</value>
</data>
<data name="ValidationExceptionMessageNotInitialized" xml:space="preserve">
<value>The value in field {0} is not initialized</value>
</data>
<data name="DocumentDocHeaderProducts" xml:space="preserve">
<value>HistoryNames of Product</value>
</data>
<data name="DocumentDocSubHeader" xml:space="preserve">
<value>Make In Date {0}</value>
</data>
<data name="DocumentExcelCaptionAmount" xml:space="preserve">
<value>Amount</value>
</data>
<data name="DocumentExcelCaptionDate" xml:space="preserve">
<value>Date</value>
</data>
<data name="DocumentExcelCaptionFIO" xml:space="preserve">
<value>Fullname</value>
</data>
<data name="DocumentExcelCaptionProduct" xml:space="preserve">
<value>Product</value>
</data>
<data name="DocumentExcelCaptionSale" xml:space="preserve">
<value>Sale</value>
</data>
<data name="DocumentExcelCaptionSum" xml:space="preserve">
<value>Total amount</value>
</data>
<data name="DocumentExcelCaptionTotal" xml:space="preserve">
<value>Total</value>
</data>
<data name="DocumentExcelCaptionWorker" xml:space="preserve">
<value>Worker</value>
</data>
<data name="DocumentExcelHeader" xml:space="preserve">
<value>Sales for the period</value>
</data>
<data name="DocumentExcelSubHeader" xml:space="preserve">
<value>from {0} to {1}</value>
</data>
<data name="DocumentPdfDiagramCaption" xml:space="preserve">
<value>Accruals</value>
</data>
<data name="DocumentPdfHeader" xml:space="preserve">
<value>Discount</value>
</data>
<data name="DocumentPdfSubHeader" xml:space="preserve">
<value>for the period from {0} to {1}</value>
</data>
<data name="ValidationExceptionMessageNoProducts" xml:space="preserve">
<value>There must be at least one item on products</value>
</data>
<data name="ValidationExceptionMessageMinorsBirthDate" xml:space="preserve">
<value>Minors cannot be hired (BirthDate = {0})</value>
</data>
<data name="ValidationExceptionMessageMinorsEmploymentDate" xml:space="preserve">
<value>Minors cannot be hired (EmploymentDate: {0}, BirthDate {1})</value>
</data>
<data name="ValidationExceptionMessageIncorrectPhoneNumber" xml:space="preserve">
<value>Incorrect phone number format</value>
</data>
<data name="ValidationExceptionMessageIncorrectFIO" xml:space="preserve">
<value>Fio incorrect</value>
</data>
<data name="ElementDeletedExceptionMessage" xml:space="preserve">
<value>Cannot modify a deleted item (id: {0})</value>
</data>
<data name="ElementExistsExceptionMessage" xml:space="preserve">
<value>There is already an element with value {0} of parameter {1}</value>
</data>
<data name="ElementNotFoundExceptionMessage" xml:space="preserve">
<value>Element not found at value = {0}</value>
</data>
<data name="IncorrectDatesExceptionMessage" xml:space="preserve">
<value>The end date must be later than the start date.. StartDate: {0}. EndDate: {1}</value>
</data>
<data name="NotEnoughDataToProcessExceptionMessage" xml:space="preserve">
<value>Not enough data to process: {0}</value>
</data>
<data name="StorageExceptionMessage" xml:space="preserve">
<value>Error while working in storage: {0}</value>
</data>
<data name="ValidationExceptionMessageEmploymentDateAndBirthDate" xml:space="preserve">
<value>Date of employment cannot be earlier than date of birth ({0}, {1})</value>
</data>
<data name="ValidationExceptionMessageLessZero" xml:space="preserve">
<value>The value in field {0} is less than or equal to 0</value>
</data>
<data name="ValidationExceptionMessageNotAId" xml:space="preserve">
<value>The value in the {0} field is not a unique identifier type.</value>
</data>
<data name="ValidationExceptionMessageMoreOne" xml:space="preserve">
<value>The value in the {0} field is greater than one</value>
</data>
</root>

View File

@@ -0,0 +1,243 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="AdapterMessageElementNotFoundException" xml:space="preserve">
<value>Élément introuvable par données: {0}</value>
</data>
<data name="AdapterMessageEmptyDate" xml:space="preserve">
<value>Les données sont vides</value>
</data>
<data name="AdapterMessageIncorrectDatesException" xml:space="preserve">
<value>Dates incorrectes: {0}</value>
</data>
<data name="AdapterMessageInvalidOperationException" xml:space="preserve">
<value>Erreur de traitement des données: {0}</value>
</data>
<data name="AdapterMessageStorageException" xml:space="preserve">
<value>Erreur lors de l'utilisation du stockage de données: {0}</value>
</data>
<data name="AdapterMessageValidationException" xml:space="preserve">
<value>Données incorrectes transmises: {0}</value>
</data>
<data name="DocumentDocCaptionName" xml:space="preserve">
<value>Noms</value>
</data>
<data name="DocumentDocCaptionPreviousPrices" xml:space="preserve">
<value>Noms Prix</value>
</data>
<data name="NotFoundDataMessage" xml:space="preserve">
<value>Aucune donnée trouvée</value>
</data>
<data name="ValidationExceptionMessageEmptyField" xml:space="preserve">
<value>La champ {0} est vide</value>
</data>
<data name="ValidationExceptionMessageNotInitialized" xml:space="preserve">
<value>La valeur du champ {0} n'est pas initialisée</value>
</data>
<data name="DocumentDocHeaderProducts" xml:space="preserve">
<value>Historique des noms de Produit</value>
</data>
<data name="DocumentDocSubHeader" xml:space="preserve">
<value>Date d'entrée {0}</value>
</data>
<data name="DocumentExcelCaptionAmount" xml:space="preserve">
<value>Comte</value>
</data>
<data name="DocumentExcelCaptionDate" xml:space="preserve">
<value>Date</value>
</data>
<data name="DocumentExcelCaptionFIO" xml:space="preserve">
<value>nom complet</value>
</data>
<data name="DocumentExcelCaptionProduct" xml:space="preserve">
<value>Produit</value>
</data>
<data name="DocumentExcelCaptionSale" xml:space="preserve">
<value>Vente</value>
</data>
<data name="DocumentExcelCaptionSum" xml:space="preserve">
<value>Montant total</value>
</data>
<data name="DocumentExcelCaptionTotal" xml:space="preserve">
<value>Total des Dépenses</value>
</data>
<data name="DocumentExcelCaptionWorker" xml:space="preserve">
<value>Travailleur</value>
</data>
<data name="DocumentExcelHeader" xml:space="preserve">
<value>Ventes de la période</value>
</data>
<data name="DocumentExcelSubHeader" xml:space="preserve">
<value>de {0} à {1}</value>
</data>
<data name="DocumentPdfDiagramCaption" xml:space="preserve">
<value>Charges à payer</value>
</data>
<data name="DocumentPdfHeader" xml:space="preserve">
<value>Remise</value>
</data>
<data name="DocumentPdfSubHeader" xml:space="preserve">
<value>pour la période de {0} à {1}</value>
</data>
<data name="ValidationExceptionMessageNoProducts" xml:space="preserve">
<value>Il doit y avoir au moins un article sur les produits</value>
</data>
<data name="ValidationExceptionMessageMinorsBirthDate" xml:space="preserve">
<value>Les mineurs ne peuvent pas être embauchés (Date de naissance = {0})</value>
</data>
<data name="ValidationExceptionMessageMinorsEmploymentDate" xml:space="preserve">
<value>Les mineurs ne peuvent pas être embauchés (Date d'emploi: {0}, Date de naissance {1})</value>
</data>
<data name="ValidationExceptionMessageIncorrectPhoneNumber" xml:space="preserve">
<value>Format de numéro de téléphone incorrect</value>
</data>
<data name="ValidationExceptionMessageIncorrectFIO" xml:space="preserve">
<value>Fio incorrect</value>
</data>
<data name="ElementDeletedExceptionMessage" xml:space="preserve">
<value>Impossible de modifier un élément supprimé (id: {0})</value>
</data>
<data name="ElementExistsExceptionMessage" xml:space="preserve">
<value>Il y a déjà un élément avec la valeur {0} du paramètre {1}</value>
</data>
<data name="ElementNotFoundExceptionMessage" xml:space="preserve">
<value>Élément introuvable à la valeur = {0}</value>
</data>
<data name="IncorrectDatesExceptionMessage" xml:space="preserve">
<value>La date de fin doit être postérieure à la date de début.. Date de début: {0}. Date de fin: {1}</value>
</data>
<data name="NotEnoughDataToProcessExceptionMessage" xml:space="preserve">
<value>Pas assez de données à traiter: {0}</value>
</data>
<data name="StorageExceptionMessage" xml:space="preserve">
<value>Erreur lors de l'utilisation du stockage: {0}</value>
</data>
<data name="ValidationExceptionMessageEmploymentDateAndBirthDate" xml:space="preserve">
<value>La date d'emploi ne peut pas être antérieure à la date de naissance ({0}, {1})</value>
</data>
<data name="ValidationExceptionMessageLessZero" xml:space="preserve">
<value>La valeur dans le champ {0} est inférieure ou égale à 0</value>
</data>
<data name="ValidationExceptionMessageNotAId" xml:space="preserve">
<value>La valeur dans le champ {0} n'est pas un type d'identifiant unique.</value>
</data>
<data name="ValidationExceptionMessageMoreOne" xml:space="preserve">
<value>La valeur dans le champ {0} est supérieure à un</value>
</data>
</root>

View File

@@ -0,0 +1,243 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="AdapterMessageElementNotFoundException" xml:space="preserve">
<value>Не найден элемент по данным: {0}</value>
</data>
<data name="AdapterMessageEmptyDate" xml:space="preserve">
<value>Данные пусты</value>
</data>
<data name="AdapterMessageIncorrectDatesException" xml:space="preserve">
<value>Неправильные даты: {0}</value>
</data>
<data name="AdapterMessageInvalidOperationException" xml:space="preserve">
<value>Ошибка при обработке данных: {0}</value>
</data>
<data name="AdapterMessageStorageException" xml:space="preserve">
<value>Ошибка при работе с хранилищем данных: {0}</value>
</data>
<data name="AdapterMessageValidationException" xml:space="preserve">
<value>Переданы неверные данные: {0}</value>
</data>
<data name="DocumentDocCaptionName" xml:space="preserve">
<value>Название</value>
</data>
<data name="DocumentDocCaptionPreviousPrices" xml:space="preserve">
<value>Предыдущие стоимости</value>
</data>
<data name="NotFoundDataMessage" xml:space="preserve">
<value>Не найдены данные</value>
</data>
<data name="ValidationExceptionMessageEmptyField" xml:space="preserve">
<value>Значение в поле {0} пусто</value>
</data>
<data name="ValidationExceptionMessageNotInitialized" xml:space="preserve">
<value>Значение в поле {0} не проиницализировано</value>
</data>
<data name="DocumentDocHeaderProducts" xml:space="preserve">
<value>История изменения продуктов</value>
</data>
<data name="DocumentDocSubHeader" xml:space="preserve">
<value>Сформировано на дату {0}</value>
</data>
<data name="DocumentExcelCaptionAmount" xml:space="preserve">
<value>Количество</value>
</data>
<data name="DocumentExcelCaptionDate" xml:space="preserve">
<value>Дата</value>
</data>
<data name="DocumentExcelCaptionFIO" xml:space="preserve">
<value>ФИО</value>
</data>
<data name="DocumentExcelCaptionProduct" xml:space="preserve">
<value>Продукт</value>
</data>
<data name="DocumentExcelCaptionSale" xml:space="preserve">
<value>Продажа</value>
</data>
<data name="DocumentExcelCaptionSum" xml:space="preserve">
<value>Сумма</value>
</data>
<data name="DocumentExcelCaptionTotal" xml:space="preserve">
<value>Всего</value>
</data>
<data name="DocumentExcelCaptionWorker" xml:space="preserve">
<value>Работник</value>
</data>
<data name="DocumentExcelHeader" xml:space="preserve">
<value>Продажи за период</value>
</data>
<data name="DocumentExcelSubHeader" xml:space="preserve">
<value>c {0} по {1}</value>
</data>
<data name="DocumentPdfDiagramCaption" xml:space="preserve">
<value>Начисления</value>
</data>
<data name="DocumentPdfHeader" xml:space="preserve">
<value>Bедомость скидок</value>
</data>
<data name="DocumentPdfSubHeader" xml:space="preserve">
<value>с {0} по {1}</value>
</data>
<data name="ValidationExceptionMessageNoProducts" xml:space="preserve">
<value>Отсутствуют продукты</value>
</data>
<data name="ValidationExceptionMessageMinorsBirthDate" xml:space="preserve">
<value>Несовершеннолетние не могут быть приняты на работу (Дата рождения: {0})</value>
</data>
<data name="ValidationExceptionMessageMinorsEmploymentDate" xml:space="preserve">
<value>Несовершеннолетние не могут быть приняты на работу (Дата трудоустройства: {0}, Дата рождения: {1})</value>
</data>
<data name="ValidationExceptionMessageIncorrectPhoneNumber" xml:space="preserve">
<value>Некорректный формат номера телефона</value>
</data>
<data name="ValidationExceptionMessageIncorrectFIO" xml:space="preserve">
<value>Некорректный формат ФИО</value>
</data>
<data name="ElementDeletedExceptionMessage" xml:space="preserve">
<value>Нельзя изменить удаленный элемент (идентификатор: {0})</value>
</data>
<data name="ElementExistsExceptionMessage" xml:space="preserve">
<value>Уже существует элемент со значением {0} параметра {1}</value>
</data>
<data name="ElementNotFoundExceptionMessage" xml:space="preserve">
<value>Элемент не найден по значению = {0}</value>
</data>
<data name="IncorrectDatesExceptionMessage" xml:space="preserve">
<value>Дата окончания должна быть позже даты начала. Дата начала: {0}. ​​Дата окончания: {1}</value>
</data>
<data name="NotEnoughDataToProcessExceptionMessage" xml:space="preserve">
<value>Недостаточно данных для обработки: {0}</value>
</data>
<data name="StorageExceptionMessage" xml:space="preserve">
<value>Ошибка при работе в хранилище: {0}</value>
</data>
<data name="ValidationExceptionMessageEmploymentDateAndBirthDate" xml:space="preserve">
<value>Дата трудоустройства не может быть раньше даты рождения ({0}, {1})</value>
</data>
<data name="ValidationExceptionMessageLessZero" xml:space="preserve">
<value>Значение в поле {0} меньше или равно 0</value>
</data>
<data name="ValidationExceptionMessageNotAId" xml:space="preserve">
<value>Значение в поле {0} не является типом уникального идентификатора</value>
</data>
<data name="ValidationExceptionMessageMoreOne" xml:space="preserve">
<value>Значение в поле {0} больше единицы</value>
</data>
</root>

View File

@@ -0,0 +1,432 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DaisiesContracts.Resources {
using System;
/// <summary>
/// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
/// </summary>
// Этот класс создан автоматически классом StronglyTypedResourceBuilder
// с помощью такого средства, как ResGen или Visual Studio.
// Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
// с параметром /str или перестройте свой проект VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Messagess {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Messagess() {
}
/// <summary>
/// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DaisiesContracts.Resources.Messagess", typeof(Messagess).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Не найден элемент по данным: {0}.
/// </summary>
internal static string AdapterMessageElementNotFoundException {
get {
return ResourceManager.GetString("AdapterMessageElementNotFoundException", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Данные пусты.
/// </summary>
internal static string AdapterMessageEmptyDate {
get {
return ResourceManager.GetString("AdapterMessageEmptyDate", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Неправильные даты: {0}.
/// </summary>
internal static string AdapterMessageIncorrectDatesException {
get {
return ResourceManager.GetString("AdapterMessageIncorrectDatesException", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Ошибка при обработке данных: {0}.
/// </summary>
internal static string AdapterMessageInvalidOperationException {
get {
return ResourceManager.GetString("AdapterMessageInvalidOperationException", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Ошибка при работе с хранилищем данных: {0}.
/// </summary>
internal static string AdapterMessageStorageException {
get {
return ResourceManager.GetString("AdapterMessageStorageException", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Переданы неверные данные: {0}.
/// </summary>
internal static string AdapterMessageValidationException {
get {
return ResourceManager.GetString("AdapterMessageValidationException", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Название.
/// </summary>
internal static string DocumentDocCaptionName {
get {
return ResourceManager.GetString("DocumentDocCaptionName", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Предыдущие стоимости.
/// </summary>
internal static string DocumentDocCaptionPreviousPrices {
get {
return ResourceManager.GetString("DocumentDocCaptionPreviousPrices", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на История изменения продуктов.
/// </summary>
internal static string DocumentDocHeaderProducts {
get {
return ResourceManager.GetString("DocumentDocHeaderProducts", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Сформировано на дату {0}.
/// </summary>
internal static string DocumentDocSubHeader {
get {
return ResourceManager.GetString("DocumentDocSubHeader", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Количество.
/// </summary>
internal static string DocumentExcelCaptionAmount {
get {
return ResourceManager.GetString("DocumentExcelCaptionAmount", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Дата.
/// </summary>
internal static string DocumentExcelCaptionDate {
get {
return ResourceManager.GetString("DocumentExcelCaptionDate", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на ФИО.
/// </summary>
internal static string DocumentExcelCaptionFIO {
get {
return ResourceManager.GetString("DocumentExcelCaptionFIO", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Продукт.
/// </summary>
internal static string DocumentExcelCaptionProduct {
get {
return ResourceManager.GetString("DocumentExcelCaptionProduct", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Продажа.
/// </summary>
internal static string DocumentExcelCaptionSale {
get {
return ResourceManager.GetString("DocumentExcelCaptionSale", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Сумма.
/// </summary>
internal static string DocumentExcelCaptionSum {
get {
return ResourceManager.GetString("DocumentExcelCaptionSum", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Всего.
/// </summary>
internal static string DocumentExcelCaptionTotal {
get {
return ResourceManager.GetString("DocumentExcelCaptionTotal", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Работник.
/// </summary>
internal static string DocumentExcelCaptionWorker {
get {
return ResourceManager.GetString("DocumentExcelCaptionWorker", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Продажи за период.
/// </summary>
internal static string DocumentExcelHeader {
get {
return ResourceManager.GetString("DocumentExcelHeader", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на c {0} по {1}.
/// </summary>
internal static string DocumentExcelSubHeader {
get {
return ResourceManager.GetString("DocumentExcelSubHeader", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Начисления.
/// </summary>
internal static string DocumentPdfDiagramCaption {
get {
return ResourceManager.GetString("DocumentPdfDiagramCaption", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Bедомость скидок.
/// </summary>
internal static string DocumentPdfHeader {
get {
return ResourceManager.GetString("DocumentPdfHeader", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на с {0} по {1}.
/// </summary>
internal static string DocumentPdfSubHeader {
get {
return ResourceManager.GetString("DocumentPdfSubHeader", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Нельзя изменить удаленный элемент (идентификатор: {0}).
/// </summary>
internal static string ElementDeletedExceptionMessage {
get {
return ResourceManager.GetString("ElementDeletedExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Уже существует элемент со значением {0} параметра {1}.
/// </summary>
internal static string ElementExistsExceptionMessage {
get {
return ResourceManager.GetString("ElementExistsExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Элемент не найден по значению = {0}.
/// </summary>
internal static string ElementNotFoundExceptionMessage {
get {
return ResourceManager.GetString("ElementNotFoundExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Дата окончания должна быть позже даты начала. Дата начала: {0}. ​​Дата окончания: {1}.
/// </summary>
internal static string IncorrectDatesExceptionMessage {
get {
return ResourceManager.GetString("IncorrectDatesExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Недостаточно данных для обработки: {0}.
/// </summary>
internal static string NotEnoughDataToProcessExceptionMessage {
get {
return ResourceManager.GetString("NotEnoughDataToProcessExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Не найдены данные.
/// </summary>
internal static string NotFoundDataMessage {
get {
return ResourceManager.GetString("NotFoundDataMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Ошибка при работе в хранилище: {0}.
/// </summary>
internal static string StorageExceptionMessage {
get {
return ResourceManager.GetString("StorageExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Дата трудоустройства не может быть раньше даты рождения ({0}, {1}).
/// </summary>
internal static string ValidationExceptionMessageEmploymentDateAndBirthDate {
get {
return ResourceManager.GetString("ValidationExceptionMessageEmploymentDateAndBirthDate", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле {0} пусто.
/// </summary>
internal static string ValidationExceptionMessageEmptyField {
get {
return ResourceManager.GetString("ValidationExceptionMessageEmptyField", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Некорректный формат ФИО.
/// </summary>
internal static string ValidationExceptionMessageIncorrectFIO {
get {
return ResourceManager.GetString("ValidationExceptionMessageIncorrectFIO", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Некорректный формат номера телефона.
/// </summary>
internal static string ValidationExceptionMessageIncorrectPhoneNumber {
get {
return ResourceManager.GetString("ValidationExceptionMessageIncorrectPhoneNumber", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле {0} меньше или равно 0.
/// </summary>
internal static string ValidationExceptionMessageLessZero {
get {
return ResourceManager.GetString("ValidationExceptionMessageLessZero", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Несовершеннолетние не могут быть приняты на работу (Дата рождения: {0}).
/// </summary>
internal static string ValidationExceptionMessageMinorsBirthDate {
get {
return ResourceManager.GetString("ValidationExceptionMessageMinorsBirthDate", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Несовершеннолетние не могут быть приняты на работу (Дата трудоустройства: {0}, Дата рождения: {1}).
/// </summary>
internal static string ValidationExceptionMessageMinorsEmploymentDate {
get {
return ResourceManager.GetString("ValidationExceptionMessageMinorsEmploymentDate", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле {0} больше единицы.
/// </summary>
internal static string ValidationExceptionMessageMoreOne {
get {
return ResourceManager.GetString("ValidationExceptionMessageMoreOne", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Отсутствуют продукты.
/// </summary>
internal static string ValidationExceptionMessageNoProducts {
get {
return ResourceManager.GetString("ValidationExceptionMessageNoProducts", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле {0} не является типом уникального идентификатора.
/// </summary>
internal static string ValidationExceptionMessageNotAId {
get {
return ResourceManager.GetString("ValidationExceptionMessageNotAId", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле {0} не инициализировано.
/// </summary>
internal static string ValidationExceptionMessageNotInitialized {
get {
return ResourceManager.GetString("ValidationExceptionMessageNotInitialized", resourceCulture);
}
}
}
}

View File

@@ -1,8 +1,8 @@
using DaisiesContracts.DataModels;
namespace DaisiesContracts.StoragesContracts;
namespace DaisiesContracts.Resources.StoragesContracts;
public interface IBuyerStorageContract
internal interface IBuyerStorageContract
{
List<BuyerDataModel> GetList();

View File

@@ -1,8 +1,8 @@
using DaisiesContracts.DataModels;
namespace DaisiesContracts.StoragesContracts;
namespace DaisiesContracts.Resources.StoragesContracts;
public interface IClientDiscountStorageContract
internal interface IClientDiscountStorageContract
{
List<ClientDiscountDataModel> GetList();
ClientDiscountDataModel? GetElementByBuyerId(string id);

View File

@@ -1,8 +1,8 @@
using DaisiesContracts.DataModels;
namespace DaisiesContracts.StoragesContracts;
namespace DaisiesContracts.Resources.StoragesContracts;
public interface IPostStorageContract
internal interface IPostStorageContract
{
List<PostDataModel> GetList();

View File

@@ -1,8 +1,8 @@
using DaisiesContracts.DataModels;
namespace DaisiesContracts.StoragesContracts;
namespace DaisiesContracts.Resources.StoragesContracts;
public interface IProductStorageContract
internal interface IProductStorageContract
{
List<ProductDataModel> GetList(bool onlyActive = true, string? supplierId = null);

View File

@@ -1,8 +1,8 @@
using DaisiesContracts.DataModels;
namespace DaisiesContracts.StoragesContracts;
namespace DaisiesContracts.Resources.StoragesContracts;
public interface ISaleStorageContract
internal interface ISaleStorageContract
{
List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? workerId = null, string? buyerId = null, string? productId = null);

View File

@@ -1,8 +1,8 @@
using DaisiesContracts.DataModels;
namespace DaisiesContracts.StoragesContracts;
namespace DaisiesContracts.Resources.StoragesContracts;
public interface IWorkerStorageContract
internal interface IWorkerStorageContract
{
List<WorkerDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null);

View File

@@ -7,7 +7,7 @@ using Newtonsoft.Json.Linq;
namespace DaisiesDatabase;
public class DaisiesDbContext : DbContext
internal class DaisiesDbContext : DbContext
{
private readonly IConfigurationDatabase? _configurationDatabase;
public DaisiesDbContext(IConfigurationDatabase configurationDatabase)
@@ -51,10 +51,9 @@ public class DaisiesDbContext : DbContext
modelBuilder.Entity<SaleProduct>().HasKey(x => new { x.SaleId, x.ProductId });
modelBuilder.Entity<Sale>()
.HasOne(s => s.Buyer)
.WithMany(b => b.Sales)
.HasForeignKey(s => s.BuyerId)
.OnDelete(DeleteBehavior.SetNull);
.HasOne(e => e.Buyer)
.WithMany(e => e.Sales)
.OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity<ProductHistory>()
.HasOne(ph => ph.Product)

View File

@@ -16,8 +16,12 @@
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="DaisiesApi" />
<InternalsVisibleTo Include="DaisiesTests" />
</ItemGroup>
<ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DaisiesContracts\DaisiesContracts.csproj" />
</ItemGroup>

View File

@@ -1,19 +1,22 @@
using AutoMapper;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using DaisiesContracts.Resources;
using DaisiesContracts.Resources.StoragesContracts;
using DaisiesDatabase.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
namespace DaisiesDatabase.Implementations;
public class BuyerStorageContract : IBuyerStorageContract
internal class BuyerStorageContract : IBuyerStorageContract
{
private readonly DaisiesDbContext _dbContext;
private readonly Mapper _mapper;
public BuyerStorageContract(DaisiesDbContext dbContext)
private readonly IStringLocalizer<Messages> _localizer;
public BuyerStorageContract(DaisiesDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
@@ -33,6 +36,7 @@ public class BuyerStorageContract : IBuyerStorageContract
.ForMember(dest => dest.Configuration, opt => opt.MapFrom(src => src.ConfigurationModel));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<BuyerDataModel> GetList()
{
@@ -43,7 +47,7 @@ public class BuyerStorageContract : IBuyerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public BuyerDataModel? GetElementById(string id)
@@ -55,7 +59,7 @@ public class BuyerStorageContract : IBuyerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public BuyerDataModel? GetElementByFIO(string fio)
@@ -68,7 +72,7 @@ public class BuyerStorageContract : IBuyerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public BuyerDataModel? GetElementByPhoneNumber(string phoneNumber)
@@ -80,7 +84,7 @@ public class BuyerStorageContract : IBuyerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public void AddElement(BuyerDataModel buyerDataModel)
@@ -93,26 +97,26 @@ public class BuyerStorageContract : IBuyerStorageContract
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", buyerDataModel.Id);
throw new ElementExistsException("Id", buyerDataModel.Id, _localizer);
}
catch (DbUpdateException ex) when (ex.InnerException is
PostgresException { ConstraintName: "IX_Buyers_PhoneNumber" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PhoneNumber", buyerDataModel.PhoneNumber);
throw new ElementExistsException("PhoneNumber", buyerDataModel.PhoneNumber, _localizer);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public void UpdElement(BuyerDataModel buyerDataModel)
{
try
{
var element = GetBuyerById(buyerDataModel.Id) ?? throw new
ElementNotFoundException(buyerDataModel.Id);
var element = GetBuyerById(buyerDataModel.Id) ??
throw new ElementNotFoundException(buyerDataModel.Id, _localizer);
_dbContext.Buyers.Update(_mapper.Map(buyerDataModel,
element));
_dbContext.SaveChanges();
@@ -126,12 +130,12 @@ public class BuyerStorageContract : IBuyerStorageContract
PostgresException { ConstraintName: "IX_Buyers_PhoneNumber" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PhoneNumber", buyerDataModel.PhoneNumber);
throw new ElementExistsException("PhoneNumber", buyerDataModel.PhoneNumber, _localizer);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public void DelElement(string id)
@@ -139,7 +143,7 @@ public class BuyerStorageContract : IBuyerStorageContract
try
{
var element = GetBuyerById(id) ?? throw new
ElementNotFoundException(id);
ElementNotFoundException(id, _localizer);
_dbContext.Buyers.Remove(element);
_dbContext.SaveChanges();
}
@@ -151,7 +155,7 @@ public class BuyerStorageContract : IBuyerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
private Buyer? GetBuyerById(string id) => _dbContext.Buyers.FirstOrDefault(x => x.Id == id);

View File

@@ -1,19 +1,23 @@
using AutoMapper;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using DaisiesContracts.Resources;
using DaisiesContracts.Resources.StoragesContracts;
using DaisiesDatabase.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
namespace DaisiesDatabase.Implementations;
public class ClientDiscountStorageContract : IClientDiscountStorageContract
internal class ClientDiscountStorageContract : IClientDiscountStorageContract
{
private readonly DaisiesDbContext _dbContext;
private readonly IMapper _mapper;
public ClientDiscountStorageContract(DaisiesDbContext dbContext)
private readonly IStringLocalizer<Messages> _localizer;
public ClientDiscountStorageContract(DaisiesDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
@@ -30,6 +34,7 @@ public class ClientDiscountStorageContract : IClientDiscountStorageContract
cfg.CreateMap<BuyerDataModel, Buyer>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public void AddElement(ClientDiscountDataModel clientDiscountDataModel)
@@ -37,14 +42,14 @@ public class ClientDiscountStorageContract : IClientDiscountStorageContract
try
{
clientDiscountDataModel.Validate();
clientDiscountDataModel.Validate(_localizer);
_dbContext.ClientDiscounts.Add(_mapper.Map<ClientDiscount>(clientDiscountDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -52,8 +57,7 @@ public class ClientDiscountStorageContract : IClientDiscountStorageContract
{
try
{
var element = _dbContext.ClientDiscounts.FirstOrDefault(x => x.BuyerId == id) ?? throw new ElementNotFoundException(id);
_dbContext.Remove(element);
var element = _dbContext.ClientDiscounts.FirstOrDefault(x => x.BuyerId == id) ?? throw new ElementNotFoundException(id, _localizer); _dbContext.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException ex)
@@ -64,7 +68,7 @@ public class ClientDiscountStorageContract : IClientDiscountStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -78,7 +82,7 @@ public class ClientDiscountStorageContract : IClientDiscountStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -95,7 +99,7 @@ public class ClientDiscountStorageContract : IClientDiscountStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -109,7 +113,7 @@ public class ClientDiscountStorageContract : IClientDiscountStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public async Task<List<ClientDiscountDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct)
@@ -126,7 +130,7 @@ public class ClientDiscountStorageContract : IClientDiscountStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -134,7 +138,7 @@ public class ClientDiscountStorageContract : IClientDiscountStorageContract
{
try
{
clientDiscountDataModel.Validate();
clientDiscountDataModel.Validate(_localizer);
var entity = _dbContext.ClientDiscounts.FirstOrDefault(x => x.BuyerId == clientDiscountDataModel.BuyerId);
if (entity != null)
{
@@ -143,13 +147,13 @@ public class ClientDiscountStorageContract : IClientDiscountStorageContract
}
else
{
throw new ElementNotFoundException($"ClientDiscount with BuyerId={clientDiscountDataModel.BuyerId} not found");
throw new ElementNotFoundException($"ClientDiscount with BuyerId={clientDiscountDataModel.BuyerId} not found", _localizer);
}
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
}

View File

@@ -1,19 +1,23 @@
using AutoMapper;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using DaisiesContracts.Resources;
using DaisiesContracts.Resources.StoragesContracts;
using DaisiesDatabase.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
namespace DaisiesDatabase.Implementations;
public class PostStorageContract : IPostStorageContract
internal class PostStorageContract : IPostStorageContract
{
private readonly DaisiesDbContext _dbContext;
private readonly Mapper _mapper;
public PostStorageContract(DaisiesDbContext dbContext)
private readonly IStringLocalizer<Messages> _localizer;
public PostStorageContract(DaisiesDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
@@ -28,6 +32,7 @@ public class PostStorageContract : IPostStorageContract
.ForMember(x => x.ChangeDate, x => x.MapFrom(src => DateTime.UtcNow));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<PostDataModel> GetList()
@@ -40,7 +45,7 @@ public class PostStorageContract : IPostStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -54,7 +59,7 @@ public class PostStorageContract : IPostStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -67,7 +72,7 @@ public class PostStorageContract : IPostStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -80,7 +85,7 @@ public class PostStorageContract : IPostStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -94,17 +99,17 @@ public class PostStorageContract : IPostStorageContract
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostName", postDataModel.PostName);
throw new ElementExistsException("PostName", postDataModel.PostName, _localizer);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostId_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostId", postDataModel.Id);
throw new ElementExistsException("PostId", postDataModel.Id, _localizer);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -115,10 +120,9 @@ public class PostStorageContract : IPostStorageContract
var transaction = _dbContext.Database.BeginTransaction();
try
{
var element = GetPostById(postDataModel.Id) ?? throw new ElementNotFoundException(postDataModel.Id);
if (!element.IsActual)
var element = GetPostById(postDataModel.Id) ?? throw new ElementNotFoundException(postDataModel.Id, _localizer); if (!element.IsActual)
{
throw new ElementDeletedException(postDataModel.Id);
throw new ElementDeletedException(postDataModel.Id, _localizer);
}
element.IsActual = false;
_dbContext.SaveChanges();
@@ -136,7 +140,7 @@ public class PostStorageContract : IPostStorageContract
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostName", postDataModel.PostName);
throw new ElementExistsException("PostName", postDataModel.PostName, _localizer);
}
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
{
@@ -146,7 +150,7 @@ public class PostStorageContract : IPostStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -154,10 +158,9 @@ public class PostStorageContract : IPostStorageContract
{
try
{
var element = GetPostById(id) ?? throw new ElementNotFoundException(id);
if (!element.IsActual)
var element = GetPostById(id) ?? throw new ElementNotFoundException(id, _localizer); if (!element.IsActual)
{
throw new ElementDeletedException(id);
throw new ElementDeletedException(id, _localizer);
}
element.IsActual = false;
_dbContext.SaveChanges();
@@ -173,7 +176,7 @@ public class PostStorageContract : IPostStorageContract
{
try
{
var element = GetPostById(id) ?? throw new ElementNotFoundException(id);
var element = GetPostById(id) ?? throw new ElementNotFoundException(id, _localizer);
element.IsActual = true;
_dbContext.SaveChanges();
}

View File

@@ -1,21 +1,24 @@
using AutoMapper;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using DaisiesContracts.Resources;
using DaisiesContracts.Resources.StoragesContracts;
using DaisiesContracts.ViewModels;
using DaisiesDatabase.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
namespace DaisiesDatabase.Implementations;
[AutoMap(typeof(ProductDataModel), ReverseMap = true)]
public class ProductStorageContract : IProductStorageContract
internal class ProductStorageContract : IProductStorageContract
{
private readonly DaisiesDbContext _dbContext;
private readonly Mapper _mapper;
public ProductStorageContract(DaisiesDbContext dbContext)
private readonly IStringLocalizer<Messages> _localizer;
public ProductStorageContract(DaisiesDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
@@ -26,6 +29,7 @@ public class ProductStorageContract : IProductStorageContract
cfg.CreateMap<ProductHistory, ProductHistoryDataModel>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<ProductDataModel> GetList(bool onlyActive = true, string?
@@ -48,7 +52,7 @@ public class ProductStorageContract : IProductStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -61,7 +65,7 @@ public class ProductStorageContract : IProductStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -74,7 +78,7 @@ public class ProductStorageContract : IProductStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -87,7 +91,7 @@ public class ProductStorageContract : IProductStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -98,7 +102,8 @@ public class ProductStorageContract : IProductStorageContract
var transaction = _dbContext.Database.BeginTransaction();
try
{
var element = GetProductById(productDataModel.Id) ?? throw new ElementNotFoundException(productDataModel.Id);
var element = GetProductById(productDataModel.Id) ??
throw new ElementNotFoundException(productDataModel.Id, _localizer);
if (element.Price != productDataModel.Price)
{
_dbContext.ProductHistories.Add(new ProductHistory() { ProductId = element.Id, OldPrice = element.Price });
@@ -117,7 +122,7 @@ public class ProductStorageContract : IProductStorageContract
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Products_ProductName_IsDeleted" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("ProductName", productDataModel.ProductName);
throw new ElementExistsException("ProductName", productDataModel.ProductName, _localizer);
}
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
{
@@ -127,7 +132,7 @@ public class ProductStorageContract : IProductStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -135,7 +140,7 @@ public class ProductStorageContract : IProductStorageContract
{
try
{
var element = GetProductById(id) ?? throw new ElementNotFoundException(id);
var element = GetProductById(id) ?? throw new ElementNotFoundException(id, _localizer);
element.IsDeleted = true;
_dbContext.SaveChanges();
}
@@ -147,7 +152,7 @@ public class ProductStorageContract : IProductStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -162,7 +167,7 @@ public class ProductStorageContract : IProductStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -176,17 +181,17 @@ public class ProductStorageContract : IProductStorageContract
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", productDataModel.Id);
throw new ElementExistsException("Id", productDataModel.Id, _localizer);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Products_ProductName_IsDeleted" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("ProductName", productDataModel.ProductName);
throw new ElementExistsException("ProductName", productDataModel.ProductName, _localizer);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
}

View File

@@ -1,19 +1,22 @@
using AutoMapper;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using DaisiesContracts.Resources;
using DaisiesContracts.Resources.StoragesContracts;
using DaisiesDatabase.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
namespace DaisiesDatabase.Implementations;
public class SaleStorageContract : ISaleStorageContract
internal class SaleStorageContract : ISaleStorageContract
{
private readonly DaisiesDbContext _DaisiesDbContext;
private readonly DaisiesDbContext _chamomilesDbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public SaleStorageContract(DaisiesDbContext DaisiesDbContext)
public SaleStorageContract(DaisiesDbContext chamomilesDbContext, IStringLocalizer<Messages> localizer)
{
_DaisiesDbContext = DaisiesDbContext;
_chamomilesDbContext = chamomilesDbContext;
var config = new MapperConfiguration(cfg =>
{
@@ -28,6 +31,7 @@ public class SaleStorageContract : ISaleStorageContract
.ForMember(x => x.SaleProducts, x => x.MapFrom(src => src.Products));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<SaleDataModel> GetList(DateTime? startDate = null, DateTime?
@@ -36,14 +40,15 @@ public class SaleStorageContract : ISaleStorageContract
{
try
{
var query = _DaisiesDbContext.Sales
.Include(x => x.SaleProducts)
var query = _chamomilesDbContext.Sales
.Include(x => x.Buyer)
.Include(x => x.Worker)
.Include(x => x.Buyer).AsQueryable();
.Include(x => x.SaleProducts)!.ThenInclude(x => x.Product)
.AsQueryable();
if (startDate is not null && endDate is not null)
{
query = query.Where(x => x.SaleDate >= startDate &&
x.SaleDate < endDate);
query = query.Where(x => x.SaleDate.ToUniversalTime() >= startDate &&
x.SaleDate.ToUniversalTime() < endDate);
}
if (workerId is not null)
{
@@ -61,8 +66,23 @@ public class SaleStorageContract : ISaleStorageContract
}
catch (Exception ex)
{
_DaisiesDbContext.ChangeTracker.Clear();
throw new StorageException(ex);
_chamomilesDbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
}
}
public async Task<List<SaleDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct)
{
try
{
List<SaleDataModel> x = [.. await _chamomilesDbContext.Sales.Include(x => x.Buyer).Include(x => x.Worker).Include(x => x.SaleProducts)!.ThenInclude(x => x.Product)
.Where(x => x.SaleDate >= startDate && x.SaleDate < endDate).Select(x => _mapper.Map<SaleDataModel>(x)).ToListAsync(ct)];
return x;
}
catch (Exception ex)
{
_chamomilesDbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
}
}
@@ -74,8 +94,8 @@ public class SaleStorageContract : ISaleStorageContract
}
catch (Exception ex)
{
_DaisiesDbContext.ChangeTracker.Clear();
throw new StorageException(ex);
_chamomilesDbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
}
}
@@ -83,15 +103,15 @@ public class SaleStorageContract : ISaleStorageContract
{
try
{
_DaisiesDbContext.Sales.Add(_mapper.Map<Sale>(saleDataModel));
_chamomilesDbContext.Sales.Add(_mapper.Map<Sale>(saleDataModel));
_DaisiesDbContext.SaveChanges();
_chamomilesDbContext.SaveChanges();
}
catch (Exception ex)
{
_DaisiesDbContext.ChangeTracker.Clear();
throw new StorageException(ex);
_chamomilesDbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
}
}
@@ -100,44 +120,30 @@ public class SaleStorageContract : ISaleStorageContract
try
{
var element = GetSaleById(id) ?? throw new
ElementNotFoundException(id);
ElementNotFoundException(id, _localizer);
if (element.IsCancel)
{
throw new ElementDeletedException(id);
throw new ElementDeletedException(id, _localizer);
}
element.IsCancel = true;
_DaisiesDbContext.SaveChanges();
_chamomilesDbContext.SaveChanges();
}
catch (Exception ex) when (ex is ElementDeletedException || ex is
ElementNotFoundException)
{
_DaisiesDbContext.ChangeTracker.Clear();
_chamomilesDbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_DaisiesDbContext.ChangeTracker.Clear();
throw new StorageException(ex);
_chamomilesDbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
}
}
public async Task<List<SaleDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct)
{
try
{
return [.. await _DaisiesDbContext.Sales.Include(x => x.Buyer).Include(x => x.SaleProducts)!.ThenInclude(x => x.Product)
.Where(x => x.SaleDate >= startDate && x.SaleDate < endDate).Select(x => _mapper.Map<SaleDataModel>(x)).ToListAsync(ct)];
}
catch (Exception ex)
{
_DaisiesDbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Sale? GetSaleById(string id) => _DaisiesDbContext.Sales.Include(x => x.Worker)
private Sale? GetSaleById(string id) => _chamomilesDbContext.Sales.Include(x => x.Worker)
.Include(x => x.Buyer)
.Include(x => x.SaleProducts)
.Include(x => x.Worker)
.Include(x => x.Buyer).FirstOrDefault(x => x.Id == id);
.FirstOrDefault(x => x.Id == id);
}

View File

@@ -1,30 +1,38 @@
using AutoMapper;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using DaisiesContracts.Resources;
using DaisiesContracts.Resources.StoragesContracts;
using DaisiesDatabase.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
namespace DaisiesDatabase.Implementations;
public class WorkerStorageContract : IWorkerStorageContract
internal class WorkerStorageContract : IWorkerStorageContract
{
private readonly DaisiesDbContext _dbContext;
private readonly Mapper _mapper;
public WorkerStorageContract(DaisiesDbContext dbContext)
private readonly IStringLocalizer<Messages> _localizer;
public WorkerStorageContract(DaisiesDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Post, PostDataModel>()
.ForMember(x => x.Id, x => x.MapFrom(src => src.PostId));
.ForMember(x => x.Id, x => x.MapFrom(src =>
src.PostId));
cfg.CreateMap<Worker, WorkerDataModel>();
cfg.CreateMap<WorkerDataModel, Worker>();
cfg.CreateMap<WorkerDataModel, Worker>()
.ForMember(x => x.Post, x => x.Ignore());
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<WorkerDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null)
public List<WorkerDataModel> GetList(bool onlyActive = true, string? postId
= null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime?
fromEmploymentDate = null, DateTime? toEmploymentDate = null)
{
try
{
@@ -39,21 +47,23 @@ public class WorkerStorageContract : IWorkerStorageContract
}
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 >= fromBirthDate &&
x.BirthDate <= toBirthDate);
}
if (fromEmploymentDate is not null && toEmploymentDate is not null)
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 >=
fromEmploymentDate && x.EmploymentDate <= toEmploymentDate);
}
return [.. JoinPost(query).Select(x => _mapper.Map<WorkerDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public WorkerDataModel? GetElementById(string id)
{
try
@@ -63,23 +73,23 @@ public class WorkerStorageContract : IWorkerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public WorkerDataModel? GetElementByFIO(string fio)
{
try
{
return _mapper.Map<WorkerDataModel>(AddPost(_dbContext.Workers.FirstOrDefault(x => x.FIO == fio && !x.IsDeleted)));
return
_mapper.Map<WorkerDataModel>(AddPost(_dbContext.Workers.FirstOrDefault(x => x.FIO
== fio && !x.IsDeleted)));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public void AddElement(WorkerDataModel workerDataModel)
{
try
@@ -87,24 +97,31 @@ public class WorkerStorageContract : IWorkerStorageContract
_dbContext.Workers.Add(_mapper.Map<Worker>(workerDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
catch (InvalidOperationException ex) when (ex.TargetSite?.Name ==
"ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", workerDataModel.Id);
throw new ElementExistsException("Id", workerDataModel.Id, _localizer);
}
catch (DbUpdateException ex)
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", workerDataModel.Id, _localizer);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public void UpdElement(WorkerDataModel workerDataModel)
{
try
{
var element = GetWorkerById(workerDataModel.Id) ?? throw new ElementNotFoundException(workerDataModel.Id);
_dbContext.Workers.Update(_mapper.Map(workerDataModel, element));
var element = GetWorkerById(workerDataModel.Id) ?? throw new
ElementNotFoundException(workerDataModel.Id, _localizer);
_dbContext.Workers.Update(_mapper.Map(workerDataModel,
element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
@@ -115,15 +132,15 @@ public class WorkerStorageContract : IWorkerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public void DelElement(string id)
{
try
{
var element = GetWorkerById(id) ?? throw new ElementNotFoundException(id);
var element = GetWorkerById(id) ?? throw new
ElementNotFoundException(id, _localizer);
element.IsDeleted = true;
_dbContext.SaveChanges();
}
@@ -135,16 +152,17 @@ public class WorkerStorageContract : IWorkerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
private Worker? GetWorkerById(string id) => AddPost(_dbContext.Workers.FirstOrDefault(x => x.Id == id && !x.IsDeleted));
private Worker? GetWorkerById(string id) =>
AddPost(_dbContext.Workers.FirstOrDefault(x => x.Id == id && !x.IsDeleted));
private IQueryable<Worker> JoinPost(IQueryable<Worker> query)
=> query.GroupJoin(_dbContext.Posts.Where(x => x.IsActual), x => x.PostId, y => y.PostId, (x, y) => new { Worker = x, Post = y })
.SelectMany(xy => xy.Post.DefaultIfEmpty(), (x, y) => x.Worker.AddPost(y));
=> query.GroupJoin(_dbContext.Posts.Where(x => x.IsActual), x =>
x.PostId, y => y.PostId, (x, y) => new { Worker = x, Post = y })
.SelectMany(xy => xy.Post.DefaultIfEmpty(), (x, y) =>
x.Worker.AddPost(y));
private Worker? AddPost(Worker? worker)
=> worker?.AddPost(_dbContext.Posts.FirstOrDefault(x => x.PostId == worker.PostId && x.IsActual));
=> worker?.AddPost(_dbContext.Posts.FirstOrDefault(x => x.PostId ==
worker.PostId && x.IsActual));
}

View File

@@ -8,7 +8,7 @@ namespace DaisiesDatabase.Models;
[AutoMap(typeof(BuyerDataModel), ReverseMap = true)]
public class Buyer
internal class Buyer
{
[Key]
public required string Id { get; set; }

View File

@@ -3,7 +3,7 @@ using System.ComponentModel.DataAnnotations.Schema;
namespace DaisiesDatabase.Models;
public class ClientDiscount
internal class ClientDiscount
{
[Key]
public string ClientDiscountsId { get; set; } = Guid.NewGuid().ToString();

View File

@@ -6,7 +6,7 @@ using System.ComponentModel.DataAnnotations.Schema;
namespace DaisiesDatabase.Models;
[AutoMap(typeof(PostDataModel), ReverseMap = true)]
public class Post
internal class Post
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string PostId { get; set; }

View File

@@ -8,7 +8,7 @@ using System.Diagnostics;
namespace DaisiesDatabase.Models;
[AutoMap(typeof(ProductDataModel), ReverseMap = true)]
public class Product
internal class Product
{
[Required]
public required string Id { get; set; }

View File

@@ -4,7 +4,7 @@ using DaisiesContracts.DataModels;
namespace DaisiesDatabase.Models;
[AutoMap(typeof(ProductHistoryDataModel), ReverseMap = true)]
public class ProductHistory
internal class ProductHistory
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string ProductId { get; set; }

View File

@@ -4,7 +4,7 @@ using System.ComponentModel.DataAnnotations.Schema;
namespace DaisiesDatabase.Models;
public class Sale
internal class Sale
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string WorkerId { get; set; }

View File

@@ -1,6 +1,6 @@
namespace DaisiesDatabase.Models;
public class SaleProduct
internal class SaleProduct
{
public required string SaleId { get; set; }
public required string ProductId { get; set; }

View File

@@ -4,7 +4,7 @@ using System.ComponentModel.DataAnnotations.Schema;
namespace DaisiesDatabase.Models;
public class Worker
internal class Worker
{
public required string Id { get; set; }

View File

@@ -1,11 +1,12 @@
using Moq;
using NUnit.Framework.Internal;
using ILogger = Microsoft.Extensions.Logging.ILogger;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.Infrastructure.BuyerConfigurations;
using DaisiesContracts.StoragesContracts;
using DaisiesBuisnessLogic.Implementations;
using DaisiesContracts.Resources.StoragesContracts;
using DaisiesContracts.BuisnessLogicContracts;
using DaisiesTests.Infrastructure;
using Microsoft.Extensions.Logging;
namespace DaisiesTests.BuisnessLogicsTests;
@@ -19,7 +20,7 @@ internal class BuyerBusinessLogicContractTests
{
_buyerStorageContract = new Mock<IBuyerStorageContract>();
_buyerBusinessLogicContract = new
BuyerBuisnessLogicContract(_buyerStorageContract.Object, new Mock<ILogger>().Object);
BuyerBuisnessLogicContract(_buyerStorageContract.Object, StringLocalizerMockCreator.GetStringLocalizerMockObject(), new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
@@ -33,8 +34,8 @@ internal class BuyerBusinessLogicContractTests
//Arrange
var listOriginal = new List<BuyerDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", "+7-111-111-11-11",0, new BuyerConfiguration() ),
new(Guid.NewGuid().ToString(), "fio 2", "+7-555-444-33-23",0.05, new BuyerConfiguration()),
new(Guid.NewGuid().ToString(), "fio 1", "+7-111-111-11-11", 0, new BuyerConfiguration() ),
new(Guid.NewGuid().ToString(), "fio 2", "+7-555-444-33-23", 0.05, new BuyerConfiguration()),
new(Guid.NewGuid().ToString(), "fio 3", "+7-777-777-7777", 0.01, new BuyerConfiguration()),
};
_buyerStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
@@ -56,20 +57,13 @@ internal class BuyerBusinessLogicContractTests
Assert.That(list, Has.Count.EqualTo(0));
_buyerStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllBuyers_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.GetAllBuyers(),
Throws.TypeOf<NullListException>());
_buyerStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllBuyers_StorageThrowError_ThrowException_Test()
{
//Arrange
_buyerStorageContract.Setup(x => x.GetList()).Throws(new
StorageException(new InvalidOperationException()));
StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.GetAllBuyers(),
Throws.TypeOf<StorageException>());
@@ -112,7 +106,7 @@ internal class BuyerBusinessLogicContractTests
{
//Arrange
var phoneNumber = "+7-111-111-11-11";
var record = new BuyerDataModel(Guid.NewGuid().ToString(), "fio", phoneNumber, 0, new BuyerConfiguration());
var record = new BuyerDataModel(Guid.NewGuid().ToString(), "fio", phoneNumber, 0, new BuyerConfiguration());
_buyerStorageContract.Setup(x =>
x.GetElementByPhoneNumber(phoneNumber)).Returns(record);
//Act
@@ -185,13 +179,13 @@ internal class BuyerBusinessLogicContractTests
//Arrange
_buyerStorageContract.Setup(x =>
x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException()));
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
_buyerStorageContract.Setup(x =>
x.GetElementByFIO(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException()));
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
_buyerStorageContract.Setup(x =>
x.GetElementByPhoneNumber(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException()));
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() =>
_buyerBusinessLogicContract.GetBuyerByData(Guid.NewGuid().ToString()),
@@ -211,7 +205,7 @@ internal class BuyerBusinessLogicContractTests
{
//Arrange
var flag = false;
var record = new BuyerDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", "+7-111-111-11-11", 0.05, new BuyerConfiguration());
var record = new BuyerDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", "+7-111-111-11-11", 0.05, new BuyerConfiguration());
_buyerStorageContract.Setup(x =>
x.AddElement(It.IsAny<BuyerDataModel>()))
.Callback((BuyerDataModel x) =>
@@ -234,7 +228,7 @@ internal class BuyerBusinessLogicContractTests
//Arrange
_buyerStorageContract.Setup(x =>
x.AddElement(It.IsAny<BuyerDataModel>())).Throws(new
ElementExistsException("Data", "Data"));
ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() =>
_buyerBusinessLogicContract.InsertBuyer(new(Guid.NewGuid().ToString(), "Иванов И.И.", "+7-111-111-11-11", 0, new BuyerConfiguration())), Throws.TypeOf<ElementExistsException>());
@@ -265,7 +259,7 @@ internal class BuyerBusinessLogicContractTests
//Arrange
_buyerStorageContract.Setup(x =>
x.AddElement(It.IsAny<BuyerDataModel>())).Throws(new StorageException(new
InvalidOperationException()));
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() =>
_buyerBusinessLogicContract.InsertBuyer(new(Guid.NewGuid().ToString(), "Иванов И.И.", "+7-111-111-11-11", 0, new BuyerConfiguration())), Throws.TypeOf<StorageException>());
@@ -299,7 +293,7 @@ internal class BuyerBusinessLogicContractTests
//Arrange
_buyerStorageContract.Setup(x =>
x.UpdElement(It.IsAny<BuyerDataModel>())).Throws(new
ElementNotFoundException(""));
ElementNotFoundException("", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() =>
_buyerBusinessLogicContract.UpdateBuyer(new(Guid.NewGuid().ToString(), "Иванов И.И.", "+7-111-111-11-11", 0, new BuyerConfiguration())), Throws.TypeOf<ElementNotFoundException>());
@@ -312,7 +306,7 @@ internal class BuyerBusinessLogicContractTests
//Arrange
_buyerStorageContract.Setup(x =>
x.UpdElement(It.IsAny<BuyerDataModel>())).Throws(new
ElementExistsException("Data", "Data"));
ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() =>
_buyerBusinessLogicContract.UpdateBuyer(new(Guid.NewGuid().ToString(), "Иванов И.И.", "+7-111-111-11-11", 0, new BuyerConfiguration())), Throws.TypeOf<ElementExistsException>());
@@ -333,7 +327,7 @@ internal class BuyerBusinessLogicContractTests
{
//Act&Assert
Assert.That(() => _buyerBusinessLogicContract.UpdateBuyer(new
BuyerDataModel("id", "Иванов И.И.", "+7-111-111-11-11", 0.05, new BuyerConfiguration())),
BuyerDataModel("id", "Иванов И.И.", "+7-111-111-11-11", 0.05, new BuyerConfiguration())),
Throws.TypeOf<ValidationException>());
_buyerStorageContract.Verify(x =>
x.UpdElement(It.IsAny<BuyerDataModel>()), Times.Never);
@@ -344,7 +338,7 @@ internal class BuyerBusinessLogicContractTests
//Arrange
_buyerStorageContract.Setup(x =>
x.UpdElement(It.IsAny<BuyerDataModel>())).Throws(new StorageException(new
InvalidOperationException()));
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() =>
_buyerBusinessLogicContract.UpdateBuyer(new(Guid.NewGuid().ToString(), "Иванов И.И.", "+7-111-111-11-11", 0, new BuyerConfiguration())), Throws.TypeOf<StorageException>());
@@ -371,7 +365,7 @@ internal class BuyerBusinessLogicContractTests
{
//Arrange
_buyerStorageContract.Setup(x =>
x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(""));
x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() =>
_buyerBusinessLogicContract.DeleteBuyer(Guid.NewGuid().ToString()),
@@ -406,7 +400,7 @@ internal class BuyerBusinessLogicContractTests
//Arrange
_buyerStorageContract.Setup(x =>
x.DelElement(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException()));
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() =>
_buyerBusinessLogicContract.DeleteBuyer(Guid.NewGuid().ToString()),

View File

@@ -1,7 +1,8 @@
using DaisiesBuisnessLogic.Implementations;
using DaisiesContracts.BuisnessLogicContracts;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using DaisiesContracts.Resources.StoragesContracts;
using DaisiesTests.Infrastructure;
using Microsoft.Extensions.Logging;
using Moq;
@@ -22,7 +23,7 @@ internal class ClientDiscountBuisnessLogicContractTest
_clientDiscountStorageContract = new Mock<IClientDiscountStorageContract>();
_saleStorageContract = new Mock<ISaleStorageContract>();
_buyerStorageContract = new Mock<IBuyerStorageContract>();
_clientDiscountBusinessLogicContract = new ClientDiscountBuisnessLogicContract(_clientDiscountStorageContract.Object, _buyerStorageContract.Object, _saleStorageContract.Object, _configurationDiscountTest, new Mock<ILogger>().Object);
_clientDiscountBusinessLogicContract = new ClientDiscountBuisnessLogicContract(_clientDiscountStorageContract.Object, _buyerStorageContract.Object, _saleStorageContract.Object, _configurationDiscountTest, new Mock<ILogger>().Object, StringLocalizerMockCreator.GetStringLocalizerMockObject());
}
[TearDown]
public void TearDown()
@@ -73,21 +74,13 @@ internal class ClientDiscountBuisnessLogicContractTest
});
_clientDiscountStorageContract.Verify(x => x.GetList(), Times.Exactly(2));
}
[Test]
public void GetAllClientDiscount_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_clientDiscountBusinessLogicContract.GetAllClientDiscounts(),
Throws.TypeOf<NullListException>());
_clientDiscountStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllClientDiscount_StorageThrowError_ThrowException_Test()
{
//Arrange
_clientDiscountStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new
InvalidOperationException()));
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() =>
_clientDiscountBusinessLogicContract.GetAllClientDiscounts(),
@@ -165,7 +158,7 @@ internal class ClientDiscountBuisnessLogicContractTest
//Arrange
_clientDiscountStorageContract.Setup(x =>
x.AddElement(It.IsAny<ClientDiscountDataModel>())).Throws(new
ElementExistsException("Data", "Data"));
ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() =>
_clientDiscountBusinessLogicContract.InsertClientDiscount(new(Guid.NewGuid().ToString(), 10, 0.01)),
@@ -197,7 +190,7 @@ internal class ClientDiscountBuisnessLogicContractTest
//Arrange
_clientDiscountStorageContract.Setup(x =>
x.AddElement(It.IsAny<ClientDiscountDataModel>())).Throws(new StorageException(new
InvalidOperationException()));
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() =>
_clientDiscountBusinessLogicContract.InsertClientDiscount(new(Guid.NewGuid().ToString(), 10, 0.01)),
@@ -232,7 +225,7 @@ internal class ClientDiscountBuisnessLogicContractTest
//Arrange
_clientDiscountStorageContract.Setup(x =>
x.UpdElement(It.IsAny<ClientDiscountDataModel>())).Throws(new
ElementNotFoundException(""));
ElementNotFoundException("", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() =>
_clientDiscountBusinessLogicContract.UpdateClientDiscount(new(Guid.NewGuid().ToString(), 10, 0.01)),
@@ -246,7 +239,7 @@ internal class ClientDiscountBuisnessLogicContractTest
//Arrange
_clientDiscountStorageContract.Setup(x =>
x.UpdElement(It.IsAny<ClientDiscountDataModel>())).Throws(new
ElementExistsException("Data", "Data"));
ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() =>
_clientDiscountBusinessLogicContract.UpdateClientDiscount(new(Guid.NewGuid().ToString(),
@@ -279,7 +272,7 @@ internal class ClientDiscountBuisnessLogicContractTest
//Arrange
_clientDiscountStorageContract.Setup(x =>
x.UpdElement(It.IsAny<ClientDiscountDataModel>())).Throws(new StorageException(new
InvalidOperationException()));
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() =>
_clientDiscountBusinessLogicContract.UpdateClientDiscount(new(Guid.NewGuid().ToString(),
@@ -309,7 +302,7 @@ internal class ClientDiscountBuisnessLogicContractTest
//Arrange
var id = Guid.NewGuid().ToString();
_clientDiscountStorageContract.Setup(x =>
x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() =>
_clientDiscountBusinessLogicContract.DeleteClientDiscount(Guid.NewGuid().ToString()),
@@ -344,7 +337,7 @@ internal class ClientDiscountBuisnessLogicContractTest
//Arrange
_clientDiscountStorageContract.Setup(x =>
x.DelElement(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException()));
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() =>
_clientDiscountBusinessLogicContract.DeleteClientDiscount(Guid.NewGuid().ToString()),

View File

@@ -1,8 +1,10 @@
using DaisiesBuisnessLogic.Implementations;
using DaisiesContracts.BuisnessLogicContracts;
using DaisiesContracts.DataModels;
using DaisiesContracts.Enum;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using DaisiesContracts.Resources.StoragesContracts;
using DaisiesTests.Infrastructure;
using Microsoft.Extensions.Logging;
using Moq;
using NUnit.Framework;
@@ -11,444 +13,403 @@ namespace DaisiesTests.BuisnessLogicsTests;
internal class PostBuisnessLogicContractTest
{
[TestFixture]
internal class PostBusinessLogicContractTests
private PostBuisnessLogicContract _postBusinessLogicContract;
private Mock<IPostStorageContract> _postStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
private PostBuisnessLogicContract _postBusinessLogicContract;
private Mock<IPostStorageContract> _postStorageContract;
_postStorageContract = new Mock<IPostStorageContract>();
_postBusinessLogicContract = new PostBuisnessLogicContract(_postStorageContract.Object, StringLocalizerMockCreator.GetStringLocalizerMockObject(), new Mock<ILogger>().Object);
}
[OneTimeSetUp]
public void OneTimeSetUp()
[TearDown]
public void TearDown()
{
_postStorageContract.Reset();
}
[Test]
public void GetAllPosts_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<PostDataModel>()
{
_postStorageContract = new Mock<IPostStorageContract>();
_postBusinessLogicContract = new PostBuisnessLogicContract(_postStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
new(Guid.NewGuid().ToString(), "name 1", PostType.Assistant, 10),
new(Guid.NewGuid().ToString(), "name 2", PostType.Assistant, 10),
new(Guid.NewGuid().ToString(), "name 3", PostType.Assistant, 10),
};
_postStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
//Act
var list = _postBusinessLogicContract.GetAllPosts();
//Assert
Assert.Multiple(() =>
{
_postStorageContract.Reset();
}
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_postStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllPosts_ReturnListOfRecords_Test()
[Test]
public void GetAllPosts_ReturnEmptyList_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetList()).Returns([]);
//Act
var list = _postBusinessLogicContract.GetAllPosts();
//Assert
Assert.Multiple(() =>
{
var listOriginal = new List<PostDataModel>()
{
new(Guid.NewGuid().ToString(), "name 1", PostType.Assistant, 10),
new(Guid.NewGuid().ToString(), "name 2", PostType.Assistant, 10),
new(Guid.NewGuid().ToString(), "name 3", PostType.Assistant, 10),
};
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
});
}
_postStorageContract.Setup(x => x.GetList())
.Returns(listOriginal);
var result = _postBusinessLogicContract.GetAllPosts();
Assert.Multiple(() =>
{
Assert.That(result, Is.Not.Null);
Assert.That(result, Is.EquivalentTo(listOriginal));
});
[Test]
public void GetAllPosts_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllPosts(), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetList(), Times.Once);
}
_postStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllPosts_ReturnEmptyList_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetList()).Returns([]);
//Act
var listOnlyActive = _postBusinessLogicContract.GetAllPosts();
var listAll = _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));
});
_postStorageContract.Verify(x => x.GetList(), Times.Exactly(2));
}
[Test]
public void GetAllPosts_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllPosts(), Throws.TypeOf<NullListException>());
_postStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllPosts_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllPosts(), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllDataOfPost_ReturnListOfRecords_Test()
{
//Arrange
var postId = Guid.NewGuid().ToString();
var listOriginal = new List<PostDataModel>()
[Test]
public void GetAllDataOfPost_ReturnListOfRecords_Test()
{
//Arrange
var postId = Guid.NewGuid().ToString();
var listOriginal = new List<PostDataModel>()
{
new(postId, "name 1", PostType.Assistant, 10),
new(postId, "name 2", PostType.Assistant, 10)
};
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _postBusinessLogicContract.GetAllDataOfPost(postId);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
_postStorageContract.Verify(x => x.GetPostWithHistory(postId), Times.Once);
}
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _postBusinessLogicContract.GetAllDataOfPost(postId);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
_postStorageContract.Verify(x => x.GetPostWithHistory(postId), Times.Once);
}
[Test]
public void GetAllDataOfPost_ReturnEmptyList_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns([]);
//Act
var list = _postBusinessLogicContract.GetAllDataOfPost(Guid.NewGuid().ToString());
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllDataOfPost_ReturnEmptyList_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns([]);
//Act
var list = _postBusinessLogicContract.GetAllDataOfPost(Guid.NewGuid().ToString());
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllDataOfPost_PostIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(string.Empty), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllDataOfPost_PostIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(string.Empty), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllDataOfPost_PostIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost("id"), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllDataOfPost_PostIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost("id"), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllDataOfPost_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(Guid.NewGuid().ToString()), Throws.TypeOf<NullListException>());
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllDataOfPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllDataOfPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new PostDataModel(id, "name", PostType.Assistant, 10);
_postStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new PostDataModel(id, "name", PostType.Assistant, 10);
_postStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_GetByName_ReturnRecord_Test()
{
//Arrange
var postName = "name";
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.Assistant, 10);
_postStorageContract.Setup(x => x.GetElementByName(postName)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(postName);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.PostName, Is.EqualTo(postName));
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_GetByName_ReturnRecord_Test()
{
//Arrange
var postName = "name";
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.Assistant, 10);
_postStorageContract.Setup(x => x.GetElementByName(postName)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(postName);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.PostName, Is.EqualTo(postName));
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _postBusinessLogicContract.GetPostByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetPostByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _postBusinessLogicContract.GetPostByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetPostByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetPostByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetPostByData_GetByName_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData("name"), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_GetByName_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData("name"), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _postBusinessLogicContract.GetPostByData("name"), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
_postStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _postBusinessLogicContract.GetPostByData("name"), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertPost_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, 10);
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>()))
.Callback((PostDataModel x) =>
{
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary;
});
//Act
_postBusinessLogicContract.InsertPost(record);
//Assert
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertPost_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, 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;
});
[Test]
public void InsertPost_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Assistant, 10)), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
}
//Act
_postBusinessLogicContract.InsertPost(record);
//Assert
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertPost_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(null), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void InsertPost_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Assistant, 10)), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void InsertPost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Assistant, 10)), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void InsertPost_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(null), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void InsertPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Assistant, 10)), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void InsertPost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Assistant, 10)), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void UpdatePost_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, 10);
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>()))
.Callback((PostDataModel x) =>
{
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary;
});
//Act
_postBusinessLogicContract.UpdatePost(record);
//Assert
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Assistant, 10)), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void UpdatePost_RecordWithIncorrectData_ThrowException_Test()
[Test]
public void UpdatePost_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, 10);
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Callback((PostDataModel x) =>
{
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Assistant, 10)), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary;
});
//Act
_postBusinessLogicContract.UpdatePost(record);
//Assert
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdatePost_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.Assistant, 10)), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void UpdatePost_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Assistant, 10)), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void UpdatePost_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(null), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void UpdatePost_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.Assistant, 10)), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void UpdatePost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Assistant, 10)), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void UpdatePost_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(null), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void UpdatePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Assistant, 10)), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void UpdatePost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Assistant, 10)), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void DeletePost_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_postStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_postBusinessLogicContract.DeletePost(id);
//Assert
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdatePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Assistant, 10)), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void DeletePost_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeletePost_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_postStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_postBusinessLogicContract.DeletePost(id);
//Assert
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void DeletePost_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _postBusinessLogicContract.DeletePost(string.Empty), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeletePost_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeletePost_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost("id"), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeletePost_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _postBusinessLogicContract.DeletePost(string.Empty), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeletePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void RestorePost_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_postStorageContract.Setup(x => x.ResElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_postBusinessLogicContract.RestorePost(id);
//Assert
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void RestorePost_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_postStorageContract.Setup(x => x.ResElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_postBusinessLogicContract.RestorePost(id);
//Assert
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void RestorePost_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void RestorePost_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void RestorePost_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _postBusinessLogicContract.RestorePost(string.Empty), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void RestorePost_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _postBusinessLogicContract.RestorePost(string.Empty), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void RestorePost_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost("id"), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void RestorePost_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost("id"), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void RestorePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void RestorePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -1,8 +1,10 @@
using DaisiesBuisnessLogic.Implementations;
using DaisiesContracts.BuisnessLogicContracts;
using DaisiesContracts.DataModels;
using DaisiesContracts.Enum;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using DaisiesContracts.Resources.StoragesContracts;
using DaisiesTests.Infrastructure;
using Microsoft.Extensions.Logging;
using Moq;
using NUnit.Framework;
@@ -14,20 +16,19 @@ internal class ProductBusinessLogicContractTests
{
private ProductBuisnessLogicContract _productBusinessLogicContract;
private Mock<IProductStorageContract> _productStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_productStorageContract = new Mock<IProductStorageContract>();
_productBusinessLogicContract = new ProductBuisnessLogicContract(_productStorageContract.Object, new Mock<ILogger>().Object);
_productBusinessLogicContract = new
ProductBuisnessLogicContract(_productStorageContract.Object, StringLocalizerMockCreator.GetStringLocalizerMockObject(), new
Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
[TearDown]
public void TearDown()
{
_productStorageContract.Reset();
}
[Test]
public void GetAllProducts_ReturnListOfRecords_Test()
{
@@ -35,11 +36,11 @@ internal class ProductBusinessLogicContractTests
var listOriginal = new List<ProductDataModel>()
{
new(Guid.NewGuid().ToString(), "name 1",
ProductType.Composition, Guid.NewGuid().ToString(), 10, false),
ProductType.Bouquet, Guid.NewGuid().ToString(), 10, false),
new(Guid.NewGuid().ToString(), "name 2",
ProductType.Composition, Guid.NewGuid().ToString(), 10, true),
new(Guid.NewGuid().ToString(), "name 3",
ProductType.Composition, Guid.NewGuid().ToString(), 10, false),
ProductType.Accessory, Guid.NewGuid().ToString(), 10, false),
};
_productStorageContract.Setup(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string>())).Returns(listOriginal);
@@ -60,7 +61,6 @@ internal class ProductBusinessLogicContractTests
_productStorageContract.Verify(x => x.GetList(false, null),
Times.Once);
}
[Test]
public void GetAllProducts_ReturnEmptyList_Test()
{
@@ -83,22 +83,13 @@ internal class ProductBusinessLogicContractTests
null), Times.Exactly(2));
}
[Test]
public void GetAllProducts_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_productBusinessLogicContract.GetAllProducts(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllProducts_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException()));
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() =>
_productBusinessLogicContract.GetAllProducts(It.IsAny<bool>()),
@@ -106,7 +97,105 @@ internal class ProductBusinessLogicContractTests
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllProductsBySupplierr_ReturnListOfRecords_Test()
{
//Arrange
var supplierrId = Guid.NewGuid().ToString();
var listOriginal = new List<ProductDataModel>()
{
new(Guid.NewGuid().ToString(), "name 1",ProductType.Bouquet,
Guid.NewGuid().ToString(), 10, false),
new(Guid.NewGuid().ToString(), "name 2",
ProductType.Composition, Guid.NewGuid().ToString(), 10, true),
new(Guid.NewGuid().ToString(), "name 3",
ProductType.Accessory, Guid.NewGuid().ToString(), 10, false),
};
_productStorageContract.Setup(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string>())).Returns(listOriginal);
//Act
var listOnlyActive =
_productBusinessLogicContract.GetAllProductsBySupplier(supplierrId, true);
var list =
_productBusinessLogicContract.GetAllProductsBySupplier(supplierrId,
false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_productStorageContract.Verify(x => x.GetList(true, supplierrId),
Times.Once);
_productStorageContract.Verify(x => x.GetList(false, supplierrId),
Times.Once);
}
[Test]
public void GetAllProductsBySupplier_ReturnEmptyList_Test()
{
//Arrange
var supplierId = Guid.NewGuid().ToString();
_productStorageContract.Setup(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string>())).Returns([]);
//Act
var listOnlyActive =
_productBusinessLogicContract.GetAllProductsBySupplier(supplierId, true);
var list =
_productBusinessLogicContract.GetAllProductsBySupplier(supplierId,
false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(list, Has.Count.EqualTo(0));
});
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(),
supplierId), Times.Exactly(2));
}
[Test]
public void
GetAllProductsBySupplier_SupplierIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_productBusinessLogicContract.GetAllProductsBySupplier(null,
It.IsAny<bool>()), Throws.TypeOf<ArgumentNullException>());
Assert.That(() =>
_productBusinessLogicContract.GetAllProductsBySupplier(string.Empty,
It.IsAny<bool>()), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string>()), Times.Never);
}
[Test]
public void
GetAllProductsBySupplier_SupplierIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_productBusinessLogicContract.GetAllProductsBySupplier("supplierrId",
It.IsAny<bool>()), Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string>()), Times.Never);
}
[Test]
public void
GetAllProductsBySupplier_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() =>
_productBusinessLogicContract.GetAllProductsBySupplier(Guid.NewGuid().ToString(), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductHistoryByProduct_ReturnListOfRecords_Test()
{
@@ -114,305 +203,390 @@ internal class ProductBusinessLogicContractTests
var productId = Guid.NewGuid().ToString();
var listOriginal = new List<ProductHistoryDataModel>()
{
new(Guid.NewGuid().ToString(), 10),
new(Guid.NewGuid().ToString(), 15),
new(Guid.NewGuid().ToString(), 10),
new(Guid.NewGuid().ToString(), 10),
new(Guid.NewGuid().ToString(), 15),
new(Guid.NewGuid().ToString(), 10),
};
_productStorageContract.Setup(x => x.GetHistoryByProductId(It.IsAny<string>())).Returns(listOriginal);
_productStorageContract.Setup(x =>
x.GetHistoryByProductId(It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _productBusinessLogicContract.GetProductHistoryByProduct(productId);
var list =
_productBusinessLogicContract.GetProductHistoryByProduct(productId);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_productStorageContract.Verify(x => x.GetHistoryByProductId(productId), Times.Once);
_productStorageContract.Verify(x =>
x.GetHistoryByProductId(productId), Times.Once);
}
[Test]
public void GetProductHistoryByProduct_ReturnEmptyList_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetHistoryByProductId(It.IsAny<string>())).Returns([]);
_productStorageContract.Setup(x =>
x.GetHistoryByProductId(It.IsAny<string>())).Returns([]);
//Act
var list = _productBusinessLogicContract.GetProductHistoryByProduct(Guid.NewGuid().ToString());
var list =
_productBusinessLogicContract.GetProductHistoryByProduct(Guid.NewGuid().ToString(
));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Once);
_productStorageContract.Verify(x =>
x.GetHistoryByProductId(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductHistoryByProduct_ProductIdIsNullOrEmpty_ThrowException_Test()
public void
GetProductHistoryByProduct_ProductIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(string.Empty), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Never);
Assert.That(() =>
_productBusinessLogicContract.GetProductHistoryByProduct(null),
Throws.TypeOf<ArgumentNullException>());
Assert.That(() =>
_productBusinessLogicContract.GetProductHistoryByProduct(string.Empty),
Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x =>
x.GetHistoryByProductId(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetProductHistoryByProduct_ProductIdIsNotGuid_ThrowException_Test()
public void
GetProductHistoryByProduct_ProductIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct("productId"), Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Never);
Assert.That(() =>
_productBusinessLogicContract.GetProductHistoryByProduct("productId"),
Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x =>
x.GetHistoryByProductId(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetProductHistoryByProduct_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(Guid.NewGuid().ToString()), Throws.TypeOf<NullListException>());
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductHistoryByProduct_StorageThrowError_ThrowException_Test()
public void
GetProductHistoryByProduct_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetHistoryByProductId(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_productStorageContract.Setup(x =>
x.GetHistoryByProductId(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Once);
Assert.That(() =>
_productBusinessLogicContract.GetProductHistoryByProduct(Guid.NewGuid().ToString(
)), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x =>
x.GetHistoryByProductId(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new ProductDataModel(id, "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
_productStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
var record = new ProductDataModel(id, "name", ProductType.Accessory,
Guid.NewGuid().ToString(), 10, false);
_productStorageContract.Setup(x =>
x.GetElementById(id)).Returns(record);
//Act
var element = _productBusinessLogicContract.GetProductByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_productStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_productStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_GetByName_ReturnRecord_Test()
{
//Arrange
var name = "name";
var record = new ProductDataModel(Guid.NewGuid().ToString(), name, ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
_productStorageContract.Setup(x => x.GetElementByName(name)).Returns(record);
var record = new ProductDataModel(Guid.NewGuid().ToString(), name,
ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
_productStorageContract.Setup(x =>
x.GetElementByName(name)).Returns(record);
//Act
var element = _productBusinessLogicContract.GetProductByData(name);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.ProductName, Is.EqualTo(name));
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
_productStorageContract.Verify(x =>
x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _productBusinessLogicContract.GetProductByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
Assert.That(() =>
_productBusinessLogicContract.GetProductByData(null),
Throws.TypeOf<ArgumentNullException>());
Assert.That(() =>
_productBusinessLogicContract.GetProductByData(string.Empty),
Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x =>
x.GetElementByName(It.IsAny<string>()), Times.Never);
_productStorageContract.Verify(x =>
x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetProductByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
Assert.That(() =>
_productBusinessLogicContract.GetProductByData(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_GetByName_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductByData("name"), Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
Assert.That(() =>
_productBusinessLogicContract.GetProductByData("name"),
Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x =>
x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_productStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_productStorageContract.Setup(x =>
x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
_productStorageContract.Setup(x =>
x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _productBusinessLogicContract.GetProductByData("name"), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
Assert.That(() =>
_productBusinessLogicContract.GetProductByData(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
Assert.That(() =>
_productBusinessLogicContract.GetProductByData("name"),
Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Once);
_productStorageContract.Verify(x =>
x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertProduct_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new ProductDataModel(Guid.NewGuid().ToString(), "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
_productStorageContract.Setup(x => x.AddElement(It.IsAny<ProductDataModel>()))
.Callback((ProductDataModel x) =>
{
flag = x.Id == record.Id && x.ProductName == record.ProductName && x.ProductType == record.ProductType &&
x.Price == record.Price && x.IsDeleted == record.IsDeleted;
});
var record = new ProductDataModel(Guid.NewGuid().ToString(), "name",
ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
_productStorageContract.Setup(x =>
x.AddElement(It.IsAny<ProductDataModel>()))
.Callback((ProductDataModel x) =>
{
flag = x.Id == record.Id && x.ProductName ==
record.ProductName && x.ProductType == record.ProductType &&
x.SupplierId == record.SupplierId && x.Price ==
record.Price && x.IsDeleted == record.IsDeleted;
});
//Act
_productBusinessLogicContract.InsertProduct(record);
//Assert
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Once);
_productStorageContract.Verify(x =>
x.AddElement(It.IsAny<ProductDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertProduct_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.AddElement(It.IsAny<ProductDataModel>())).Throws(new ElementExistsException("Data", "Data"));
_productStorageContract.Setup(x =>
x.AddElement(It.IsAny<ProductDataModel>())).Throws(new
ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.InsertProduct(new(Guid.NewGuid().ToString(), "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false)), Throws.TypeOf<ElementExistsException>());
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Once);
Assert.That(() =>
_productBusinessLogicContract.InsertProduct(new(Guid.NewGuid().ToString(),
"name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false)),
Throws.TypeOf<ElementExistsException>());
_productStorageContract.Verify(x =>
x.AddElement(It.IsAny<ProductDataModel>()), Times.Once);
}
[Test]
public void InsertProduct_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.InsertProduct(null), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Never);
Assert.That(() => _productBusinessLogicContract.InsertProduct(null),
Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x =>
x.AddElement(It.IsAny<ProductDataModel>()), Times.Never);
}
[Test]
public void InsertProduct_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.InsertProduct(new ProductDataModel("id", "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false)), Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Never);
Assert.That(() => _productBusinessLogicContract.InsertProduct(new
ProductDataModel("id", "name", ProductType.Accessory, Guid.NewGuid().ToString(),
10, false)), Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x =>
x.AddElement(It.IsAny<ProductDataModel>()), Times.Never);
}
[Test]
public void InsertProduct_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.AddElement(It.IsAny<ProductDataModel>())).Throws(new StorageException(new InvalidOperationException()));
_productStorageContract.Setup(x =>
x.AddElement(It.IsAny<ProductDataModel>())).Throws(new StorageException(new
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.InsertProduct(new(Guid.NewGuid().ToString(), "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false)), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Once);
Assert.That(() =>
_productBusinessLogicContract.InsertProduct(new(Guid.NewGuid().ToString(),
"name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false)),
Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x =>
x.AddElement(It.IsAny<ProductDataModel>()), Times.Once);
}
[Test]
public void UpdateProduct_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new ProductDataModel(Guid.NewGuid().ToString(), "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<ProductDataModel>()))
.Callback((ProductDataModel x) =>
{
flag = x.Id == record.Id && x.ProductName == record.ProductName && x.ProductType == record.ProductType &&
x.Price == record.Price && x.IsDeleted == record.IsDeleted;
});
var record = new ProductDataModel(Guid.NewGuid().ToString(), "name",
ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
_productStorageContract.Setup(x =>
x.UpdElement(It.IsAny<ProductDataModel>()))
.Callback((ProductDataModel x) =>
{
flag = x.Id == record.Id && x.ProductName ==
record.ProductName && x.ProductType == record.ProductType &&
x.SupplierId == record.SupplierId && x.Price ==
record.Price && x.IsDeleted == record.IsDeleted;
});
//Act
_productBusinessLogicContract.UpdateProduct(record);
//Assert
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
_productStorageContract.Verify(x =>
x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdateProduct_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new ElementNotFoundException(""));
_productStorageContract.Setup(x =>
x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new
ElementNotFoundException("", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(new(Guid.NewGuid().ToString(), "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false)), Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
Assert.That(() =>
_productBusinessLogicContract.UpdateProduct(new(Guid.NewGuid().ToString(),
"name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false)),
Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x =>
x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
}
[Test]
public void UpdateProduct_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new ElementExistsException("Data", "Data"));
_productStorageContract.Setup(x =>
x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new
ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(new(Guid.NewGuid().ToString(), "anme", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false)), Throws.TypeOf<ElementExistsException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
Assert.That(() =>
_productBusinessLogicContract.UpdateProduct(new(Guid.NewGuid().ToString(),
"anme", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false)),
Throws.TypeOf<ElementExistsException>());
_productStorageContract.Verify(x =>
x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
}
[Test]
public void UpdateProduct_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(null), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Never);
Assert.That(() => _productBusinessLogicContract.UpdateProduct(null),
Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x =>
x.UpdElement(It.IsAny<ProductDataModel>()), Times.Never);
}
[Test]
public void UpdateProduct_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(new ProductDataModel("id", "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false)), Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Never);
Assert.That(() => _productBusinessLogicContract.UpdateProduct(new
ProductDataModel("id", "name", ProductType.Accessory, Guid.NewGuid().ToString(),
10, false)), Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x =>
x.UpdElement(It.IsAny<ProductDataModel>()), Times.Never);
}
[Test]
public void UpdateProduct_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new StorageException(new InvalidOperationException()));
_productStorageContract.Setup(x =>
x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new StorageException(new
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(new(Guid.NewGuid().ToString(), "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false)), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
Assert.That(() =>
_productBusinessLogicContract.UpdateProduct(new(Guid.NewGuid().ToString(),
"name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false)),
Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x =>
x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
}
[Test]
public void DeleteProduct_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_productStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
_productStorageContract.Setup(x => x.DelElement(It.Is((string x) => x
== id))).Callback(() => { flag = true; });
//Act
_productBusinessLogicContract.DeleteProduct(id);
//Assert
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()),
Times.Once);
Assert.That(flag);
}
[Test]
public void DeleteProduct_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_productStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
_productStorageContract.Setup(x =>
x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.DeleteProduct(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(() =>
_productBusinessLogicContract.DeleteProduct(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()),
Times.Once);
}
[Test]
public void DeleteProduct_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.DeleteProduct(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _productBusinessLogicContract.DeleteProduct(string.Empty), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
Assert.That(() => _productBusinessLogicContract.DeleteProduct(null),
Throws.TypeOf<ArgumentNullException>());
Assert.That(() =>
_productBusinessLogicContract.DeleteProduct(string.Empty),
Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()),
Times.Never);
}
[Test]
public void DeleteProduct_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.DeleteProduct("id"), Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
Assert.That(() => _productBusinessLogicContract.DeleteProduct("id"),
Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()),
Times.Never);
}
[Test]
public void DeleteProduct_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_productStorageContract.Setup(x =>
x.DelElement(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.DeleteProduct(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(() =>
_productBusinessLogicContract.DeleteProduct(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()),
Times.Once);
}
}

View File

@@ -4,7 +4,8 @@ using DaisiesContracts.DataModels;
using DaisiesContracts.Enum;
using DaisiesContracts.Exceptions;
using DaisiesContracts.Infrastructure.BuyerConfigurations;
using DaisiesContracts.StoragesContracts;
using DaisiesContracts.Resources.StoragesContracts;
using DaisiesTests.Infrastructure;
using Microsoft.Extensions.Logging;
using Moq;
@@ -12,7 +13,6 @@ namespace DaisiesTests.BuisnessLogicsTests;
public class ReportContractTests
{
private ReportContract _reportContract;
private Mock<IProductStorageContract> _productStorageContract;
private Mock<ISaleStorageContract> _saleStorageContract;
@@ -31,7 +31,7 @@ public class ReportContractTests
_baseExcelBuilder = new Mock<BaseExcelBuilder>();
_basePdfBuilder = new Mock<BasePdfBuilder>();
_reportContract = new ReportContract(_productStorageContract.Object, new Mock<ILogger>().Object, _baseWordBuilder.Object, _saleStorageContract.Object,
_discountStorageContract.Object, _baseExcelBuilder.Object, _basePdfBuilder.Object);
_discountStorageContract.Object, _baseExcelBuilder.Object, _basePdfBuilder.Object, StringLocalizerMockCreator.GetStringLocalizerMockObject());
}
@@ -47,8 +47,8 @@ public class ReportContractTests
public async Task GetDataProductPricesByProductAsync_ShouldSuccess_Test()
{
var product1 = new ProductDataModel(Guid.NewGuid().ToString(), "Name1", ProductType.Bouquet, Guid.NewGuid().ToString(), 10, false);
var product2 = new ProductDataModel(Guid.NewGuid().ToString(), "Name2", ProductType.Bouquet, Guid.NewGuid().ToString(), 10, false);
var product1 = new ProductDataModel(Guid.NewGuid().ToString(), "Name1", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
var product2 = new ProductDataModel(Guid.NewGuid().ToString(), "Name2", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
//Arrange
_productStorageContract.Setup(x => x.GetListAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult(new List<ProductHistoryDataModel>()
{
@@ -90,7 +90,7 @@ public class ReportContractTests
//Arrange
_productStorageContract.Setup(x =>
x.GetListAsync(It.IsAny<CancellationToken>())).Throws(new StorageException(new
InvalidOperationException()));
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(async () => await
_reportContract.GetDataProductPricesByProductAsync(CancellationToken.None),
@@ -107,8 +107,8 @@ public class ReportContractTests
var productId2 = Guid.NewGuid().ToString();
var product1 = new ProductDataModel(productId1, "name1", ProductType.Bouquet, Guid.NewGuid().ToString(), 10, false);
var product2 = new ProductDataModel(productId2, "name2", ProductType.Bouquet, Guid.NewGuid().ToString(), 10, false);
var product1 = new ProductDataModel(productId1, "name1", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
var product2 = new ProductDataModel(productId2, "name2", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
_productStorageContract.Setup(x => x.GetListAsync(It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(new List<ProductHistoryDataModel>()
@@ -154,12 +154,6 @@ public class ReportContractTests
Assert.That(firstDataRow, Has.Length.EqualTo(3));
Assert.That(secondDataRow, Has.Length.EqualTo(3));
Assert.That(firstDataRow[0], Is.EqualTo("Название продукта"));
Assert.That(firstDataRow[1], Is.EqualTo("Цены"));
Assert.That(secondDataRow[0], Is.EqualTo("name1"));
Assert.That(secondDataRow[1], Is.EqualTo(""));
});
}
@@ -218,7 +212,7 @@ public class ReportContractTests
{
//Arrange
_saleStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
.Throws(new StorageException(new InvalidOperationException()));
.Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(async () => await _reportContract.GetDataSaleByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None),
Throws.TypeOf<StorageException>());
@@ -230,13 +224,13 @@ public class ReportContractTests
public async Task CreateDocumentSalesByPeriod_ShouldSuccess_Test()
{
// Arrange
var product1 = new ProductDataModel(Guid.NewGuid().ToString(), "Name1", ProductType.Bouquet, Guid.NewGuid().ToString(), 15, false);
var product2 = new ProductDataModel(Guid.NewGuid().ToString(), "Name2", ProductType.Bouquet, Guid.NewGuid().ToString(), 10, false);
var product1 = new ProductDataModel(Guid.NewGuid().ToString(), "Name1", ProductType.Accessory, Guid.NewGuid().ToString(), 15, false);
var product2 = new ProductDataModel(Guid.NewGuid().ToString(), "Name2", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
var buyer1 = new BuyerDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", "+7-555-444-33-23", 0.05, new BuyerConfiguration());
var buyer1 = new BuyerDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", "+7-555-444-33-23", 0.05, new BuyerConfiguration());
var buyer2 = new BuyerDataModel(Guid.NewGuid().ToString(), "fio 3", "+7-777-777-7777", 0.01, new BuyerConfiguration());
var worker = new WorkerDataModel(Guid.NewGuid().ToString(), "fio 1", Guid.NewGuid().ToString(), DateTime.MinValue, DateTime.Now, false);
var worker = new WorkerDataModel(Guid.NewGuid().ToString(), "fio 1", Guid.NewGuid().ToString(), DateTime.MinValue, DateTime.UtcNow, false);
_saleStorageContract.Setup(x => x.GetListAsync(
It.IsAny<DateTime>(),
@@ -304,27 +298,6 @@ public class ReportContractTests
Assert.That(firstProductRow, Is.Not.Empty);
});
Assert.Multiple(() =>
{
Assert.That(headerRow[0], Is.EqualTo("Дата"));
Assert.That(headerRow[1], Is.EqualTo("ФИО"));
Assert.That(headerRow[2], Is.EqualTo("Сумма"));
Assert.That(headerRow[3], Is.EqualTo("Продукт"));
Assert.That(headerRow[4], Is.EqualTo("Количество"));
Assert.That(firstDataRow[0], Is.EqualTo(DateTime.UtcNow.ToString("dd.MM.yyyy")));
Assert.That(firstDataRow[1], Is.EqualTo("Иванов И.И."));
Assert.That(firstDataRow[2], Is.EqualTo(400.ToString("N2")));
Assert.That(firstDataRow[3], Is.Empty);
Assert.That(firstDataRow[4], Is.Empty);
Assert.That(firstProductRow[0], Is.Empty);
Assert.That(firstProductRow[1], Is.Empty);
Assert.That(firstProductRow[2], Is.Empty);
Assert.That(firstProductRow[3], Is.EqualTo(product1.ProductName));
Assert.That(firstProductRow[4], Is.EqualTo(15.ToString("N2")));
});
_saleStorageContract.Verify(x => x.GetListAsync(
It.IsAny<DateTime>(),
It.IsAny<DateTime>(),
@@ -353,8 +326,8 @@ public class ReportContractTests
var startDate = DateTime.UtcNow.AddDays(-20);
var endDate = DateTime.UtcNow.AddDays(5);
var buyer1 = new BuyerDataModel(Guid.NewGuid().ToString(), "fio 2", "+7-555-444-33-23", 0.05, new BuyerConfiguration());
var buyer2 = new BuyerDataModel(Guid.NewGuid().ToString(), "fio 3", "+7-777-777-7777", 0.01, new BuyerConfiguration());
var buyer1 = new BuyerDataModel(Guid.NewGuid().ToString(), "fio 2", "+7-555-444-33-23", 0.05, new BuyerConfiguration());
var buyer2 = new BuyerDataModel(Guid.NewGuid().ToString(), "fio 3","+7-777-777-7777", 0.01, new BuyerConfiguration());
_discountStorageContract.Setup(x =>
x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
@@ -439,7 +412,7 @@ public class ReportContractTests
// Arrange
_discountStorageContract.Setup(x =>
x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
.ThrowsAsync(new StorageException(new InvalidOperationException()));
.ThrowsAsync(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
// Act & Assert
Assert.That(async () => await _reportContract.GetDataDiscountByPeriodAsync(
@@ -509,14 +482,6 @@ public class ReportContractTests
endDate,
CancellationToken.None);
// Assert
//Assert.Multiple(() =>
//{
// Assert.That(countRows, Is.EqualTo(2));
// Assert.That(firstRow, Is.Not.EqualTo(default));
// Assert.That(secondRow, Is.Not.EqualTo(default));
//});
Assert.Multiple(() =>
{
Assert.That(firstRow.Item1, Is.EqualTo(buyer1.FIO));

View File

@@ -3,7 +3,8 @@ using Microsoft.Extensions.Logging;
using DaisiesBuisnessLogic.Implementations;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using DaisiesContracts.Resources.StoragesContracts;
using DaisiesTests.Infrastructure;
namespace DaisiesTests.BuisnessLogicsTests;
@@ -17,7 +18,7 @@ internal class SaleBusinessLogicContractTests
public void OneTimeSetUp()
{
_saleStorageContract = new Mock<ISaleStorageContract>();
_saleBusinessLogicContract = new SaleBusinessLogicContract(_saleStorageContract.Object, new Mock<ILogger>().Object);
_saleBusinessLogicContract = new SaleBusinessLogicContract(_saleStorageContract.Object, StringLocalizerMockCreator.GetStringLocalizerMockObject(), new Mock<ILogger>().Object);
}
[TearDown]
@@ -71,22 +72,13 @@ internal class SaleBusinessLogicContractTests
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_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(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.
GetAllSalesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
@@ -153,19 +145,12 @@ internal class SaleBusinessLogicContractTests
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByWorkerByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByWorkerByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_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(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
@@ -222,8 +207,7 @@ internal class SaleBusinessLogicContractTests
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(null, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(string.
Empty, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(string.Empty, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
@@ -235,19 +219,11 @@ internal class SaleBusinessLogicContractTests
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByBuyerByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByBuyerByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_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(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
@@ -294,8 +270,7 @@ internal class SaleBusinessLogicContractTests
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.
GetAllSalesByProductByPeriod(Guid.NewGuid().ToString(), date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(Guid.NewGuid().ToString(), date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(Guid.NewGuid().ToString(), date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
@@ -317,19 +292,11 @@ internal class SaleBusinessLogicContractTests
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByProductByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByProductByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_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(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
@@ -364,8 +331,7 @@ internal class SaleBusinessLogicContractTests
public void GetSaleByData_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.
That(() => _saleBusinessLogicContract.GetSaleByData("saleId"), Throws.TypeOf<ValidationException>());
Assert.That(() => _saleBusinessLogicContract.GetSaleByData("saleId"), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
}
@@ -381,7 +347,7 @@ internal class SaleBusinessLogicContractTests
public void GetSaleByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_saleStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetSaleByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
@@ -415,7 +381,7 @@ internal class SaleBusinessLogicContractTests
public void InsertSale_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new ElementExistsException("Data", "Data"));
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), 10, false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
@@ -442,11 +408,10 @@ internal class SaleBusinessLogicContractTests
public void InsertSale_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new StorageException(new InvalidOperationException()));
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().
ToString(), 10, false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
Guid.NewGuid().ToString(), 10, false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
}
@@ -469,7 +434,7 @@ internal class SaleBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
_saleStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.CancelSale(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
@@ -496,7 +461,7 @@ internal class SaleBusinessLogicContractTests
public void CancelSale_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_saleStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.CancelSale(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);

View File

@@ -2,9 +2,11 @@
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using Microsoft.Extensions.Logging;
using DaisiesContracts.StoragesContracts;
using Moq;
using NUnit.Framework;
using DaisiesContracts.Resources.StoragesContracts;
using DaisiesContracts.BuisnessLogicContracts;
using DaisiesTests.Infrastructure;
namespace DaisiesTests.BuisnessLogicsTests;
@@ -13,33 +15,41 @@ internal class WorkerBusinessLogicContractTests
{
private WorkerBuisnessLogicContract _workerBusinessLogicContract;
private Mock<IWorkerStorageContract> _workerStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_workerStorageContract = new Mock<IWorkerStorageContract>();
_workerBusinessLogicContract = new WorkerBuisnessLogicContract(_workerStorageContract.Object, new Mock<ILogger>().Object);
_workerBusinessLogicContract = new
WorkerBuisnessLogicContract(_workerStorageContract.Object, StringLocalizerMockCreator.GetStringLocalizerMockObject(), new
Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
[TearDown]
public void TearDown()
{
_workerStorageContract.Reset();
}
[Test]
public void GetAllWorkers_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<WorkerDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
};
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
{
new(Guid.NewGuid().ToString(), "fio 1",
Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-16).AddDays(-1), DateTime.UtcNow,
false),
new(Guid.NewGuid().ToString(), "fio 2",
Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-16).AddDays(-1), DateTime.UtcNow,
true),
new(Guid.NewGuid().ToString(), "fio 3",
Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-16).AddDays(-1), DateTime.UtcNow,
false),
};
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllWorkers(true);
var listOnlyActive =
_workerBusinessLogicContract.GetAllWorkers(true);
var list = _workerBusinessLogicContract.GetAllWorkers(false);
//Assert
Assert.Multiple(() =>
@@ -49,17 +59,21 @@ internal class WorkerBusinessLogicContractTests
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_workerStorageContract.Verify(x => x.GetList(true, null, null, null, null, null), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, null, null, null, null, null), Times.Once);
_workerStorageContract.Verify(x => x.GetList(true, null, null, null,
null, null), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, null, null, null,
null, null), Times.Once);
}
[Test]
public void GetAllWorkers_ReturnEmptyList_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns([]);
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns([]);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllWorkers(true);
var listOnlyActive =
_workerBusinessLogicContract.GetAllWorkers(true);
var list = _workerBusinessLogicContract.GetAllWorkers(false);
//Assert
Assert.Multiple(() =>
@@ -69,42 +83,50 @@ internal class WorkerBusinessLogicContractTests
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(list, Has.Count.EqualTo(0));
});
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), null, null, null, null, null), Times.Exactly(2));
}
[Test]
public void GetAllWorkers_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkers(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), null,
null, null, null, null), Times.Exactly(2));
}
[Test]
public void GetAllWorkers_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkers(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), null, null, null, null, null), Times.Once);
Assert.That(() =>
_workerBusinessLogicContract.GetAllWorkers(It.IsAny<bool>()),
Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), null,
null, null, null, null), Times.Once);
}
[Test]
public void GetAllWorkersByPost_ReturnListOfRecords_Test()
{
//Arrange
var postId = Guid.NewGuid().ToString();
var listOriginal = new List<WorkerDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
};
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
{
new(Guid.NewGuid().ToString(), "fio 1",
Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-16).AddDays(-1), DateTime.UtcNow,
false),
new(Guid.NewGuid().ToString(), "fio 2",
Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-16).AddDays(-1), DateTime.UtcNow,
true),
new(Guid.NewGuid().ToString(), "fio 3",
Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-16).AddDays(-1), DateTime.UtcNow,
false),
};
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllWorkersByPost(postId, true);
var list = _workerBusinessLogicContract.GetAllWorkersByPost(postId, false);
var listOnlyActive =
_workerBusinessLogicContract.GetAllWorkersByPost(postId, true);
var list = _workerBusinessLogicContract.GetAllWorkersByPost(postId,
false);
//Assert
Assert.Multiple(() =>
{
@@ -113,18 +135,25 @@ internal class WorkerBusinessLogicContractTests
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_workerStorageContract.Verify(x => x.GetList(true, postId, null, null, null, null), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, postId, null, null, null, null), Times.Once);
_workerStorageContract.Verify(x => x.GetList(true, postId, null,
null, null, null), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, postId, null,
null, null, null), Times.Once);
}
[Test]
public void GetAllWorkersByPost_ReturnEmptyList_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns([]);
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns([]);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllWorkersByPost(Guid.NewGuid().ToString(), true);
var list = _workerBusinessLogicContract.GetAllWorkersByPost(Guid.NewGuid().ToString(), false);
var listOnlyActive =
_workerBusinessLogicContract.GetAllWorkersByPost(Guid.NewGuid().ToString(),
true);
var list =
_workerBusinessLogicContract.GetAllWorkersByPost(Guid.NewGuid().ToString(),
false);
//Assert
Assert.Multiple(() =>
{
@@ -133,59 +162,79 @@ internal class WorkerBusinessLogicContractTests
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(list, Has.Count.EqualTo(0));
});
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Exactly(2));
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Exactly(2));
}
[Test]
public void GetAllWorkersByPost_PostIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByPost(null, It.IsAny<bool>()), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByPost(string.Empty, It.IsAny<bool>()), Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
Assert.That(() =>
_workerBusinessLogicContract.GetAllWorkersByPost(null, It.IsAny<bool>()),
Throws.TypeOf<ArgumentNullException>());
Assert.That(() =>
_workerBusinessLogicContract.GetAllWorkersByPost(string.Empty, It.IsAny<bool>()),
Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllWorkersByPost_PostIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByPost("postId", It.IsAny<bool>()), Throws.TypeOf<ValidationException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllWorkersByPost_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByPost(Guid.NewGuid().ToString(), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
Assert.That(() =>
_workerBusinessLogicContract.GetAllWorkersByPost("postId", It.IsAny<bool>()),
Throws.TypeOf<ValidationException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllWorkersByPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByPost(Guid.NewGuid().ToString(), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
Assert.That(() =>
_workerBusinessLogicContract.GetAllWorkersByPost(Guid.NewGuid().ToString(),
It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkersByBirthDate_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var listOriginal = new List<WorkerDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
};
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
{
new(Guid.NewGuid().ToString(), "fio 1",
Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-16).AddDays(-1), DateTime.UtcNow,
false),
new(Guid.NewGuid().ToString(), "fio 2",
Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-16).AddDays(-1), DateTime.UtcNow,
true),
new(Guid.NewGuid().ToString(), "fio 3",
Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-16).AddDays(-1), DateTime.UtcNow,
false),
};
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllWorkersByBirthDate(date, date.AddDays(1), true);
var list = _workerBusinessLogicContract.GetAllWorkersByBirthDate(date, date.AddDays(1), false);
var listOnlyActive =
_workerBusinessLogicContract.GetAllWorkersByBirthDate(date, date.AddDays(1),
true);
var list =
_workerBusinessLogicContract.GetAllWorkersByBirthDate(date, date.AddDays(1),
false);
//Assert
Assert.Multiple(() =>
{
@@ -194,17 +243,22 @@ internal class WorkerBusinessLogicContractTests
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_workerStorageContract.Verify(x => x.GetList(true, null, date, date.AddDays(1), null, null), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, null, date, date.AddDays(1), null, null), Times.Once);
_workerStorageContract.Verify(x => x.GetList(true, null, date,
date.AddDays(1), null, null), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, null, date,
date.AddDays(1), null, null), Times.Once);
}
[Test]
public void GetAllWorkersByBirthDate_ReturnEmptyList_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns([]);
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns([]);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllWorkersByBirthDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), true);
var listOnlyActive =
_workerBusinessLogicContract.GetAllWorkersByBirthDate(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1), true);
var list = _workerBusinessLogicContract.GetAllWorkers(false);
//Assert
Assert.Multiple(() =>
@@ -214,54 +268,72 @@ internal class WorkerBusinessLogicContractTests
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(list, Has.Count.EqualTo(0));
});
_workerStorageContract.Verify(x => x.GetList(true, null, It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), null, null), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, null, It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), null, null), Times.Once);
_workerStorageContract.Verify(x => x.GetList(true, null,
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), null, null), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, null,
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), null, null), Times.Once);
}
[Test]
public void GetAllWorkersByBirthDate_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByBirthDate(date, date, It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByBirthDate(date, date.AddSeconds(-1), It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
Assert.That(() =>
_workerBusinessLogicContract.GetAllWorkersByBirthDate(date, date,
It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() =>
_workerBusinessLogicContract.GetAllWorkersByBirthDate(date, date.AddSeconds(-1),
It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllWorkersByBirthDate_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByBirthDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkersByBirthDate_StorageThrowError_ThrowException_Test()
public void
GetAllWorkersByBirthDate_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByBirthDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
Assert.That(() =>
_workerBusinessLogicContract.GetAllWorkersByBirthDate(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1), It.IsAny<bool>()),
Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkersByEmploymentDate_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var listOriginal = new List<WorkerDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
};
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
{
new(Guid.NewGuid().ToString(), "fio 1",
Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-16).AddDays(-1), DateTime.UtcNow,
false),
new(Guid.NewGuid().ToString(), "fio 2",
Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-16).AddDays(-1), DateTime.UtcNow,
true),
new(Guid.NewGuid().ToString(), "fio 3",
Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-16).AddDays(-1), DateTime.UtcNow,
false),
};
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(date, date.AddDays(1), true);
var list = _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(date, date.AddDays(1), false);
var listOnlyActive =
_workerBusinessLogicContract.GetAllWorkersByEmploymentDate(date, date.AddDays(1),
true);
var list =
_workerBusinessLogicContract.GetAllWorkersByEmploymentDate(date, date.AddDays(1),
false);
//Assert
Assert.Multiple(() =>
{
@@ -270,18 +342,25 @@ internal class WorkerBusinessLogicContractTests
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_workerStorageContract.Verify(x => x.GetList(true, null, null, null, date, date.AddDays(1)), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, null, null, null, date, date.AddDays(1)), Times.Once);
_workerStorageContract.Verify(x => x.GetList(true, null, null, null,
date, date.AddDays(1)), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, null, null, null,
date, date.AddDays(1)), Times.Once);
}
[Test]
public void GetAllWorkersByEmploymentDate_ReturnEmptyList_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns([]);
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns([]);
//Act
var listOnlyActive = _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), true);
var list = _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), false);
var listOnlyActive =
_workerBusinessLogicContract.GetAllWorkersByEmploymentDate(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1), true);
var list =
_workerBusinessLogicContract.GetAllWorkersByEmploymentDate(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1), false);
//Assert
Assert.Multiple(() =>
{
@@ -290,269 +369,351 @@ internal class WorkerBusinessLogicContractTests
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(list, Has.Count.EqualTo(0));
});
_workerStorageContract.Verify(x => x.GetList(true, null, null, null, It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, null, null, null, It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
_workerStorageContract.Verify(x => x.GetList(true, null, null, null,
It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
_workerStorageContract.Verify(x => x.GetList(false, null, null, null,
It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkersByEmploymentDate_IncorrectDates_ThrowException_Test()
public void
GetAllWorkersByEmploymentDate_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(date, date, It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(date, date.AddSeconds(-1), It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
Assert.That(() =>
_workerBusinessLogicContract.GetAllWorkersByEmploymentDate(date, date,
It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() =>
_workerBusinessLogicContract.GetAllWorkersByEmploymentDate(date,
date.AddSeconds(-1), It.IsAny<bool>()),
Throws.TypeOf<IncorrectDatesException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllWorkersByEmploymentDate_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkersByEmploymentDate_StorageThrowError_ThrowException_Test()
public void
GetAllWorkersByEmploymentDate_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
Assert.That(() =>
_workerBusinessLogicContract.GetAllWorkersByEmploymentDate(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1), It.IsAny<bool>()),
Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(),
It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetWorkerByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new WorkerDataModel(id, "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false);
_workerStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
var record = new WorkerDataModel(id, "fio",
Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-16).AddDays(-1), DateTime.UtcNow,
false);
_workerStorageContract.Setup(x =>
x.GetElementById(id)).Returns(record);
//Act
var element = _workerBusinessLogicContract.GetWorkerByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_workerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_workerStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetWorkerByData_GetByFio_ReturnRecord_Test()
{
//Arrange
var fio = "fio";
var record = new WorkerDataModel(Guid.NewGuid().ToString(), fio, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false);
_workerStorageContract.Setup(x => x.GetElementByFIO(fio)).Returns(record);
var record = new WorkerDataModel(Guid.NewGuid().ToString(), fio,
Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-16).AddDays(-1), DateTime.UtcNow,
false);
_workerStorageContract.Setup(x =>
x.GetElementByFIO(fio)).Returns(record);
//Act
var element = _workerBusinessLogicContract.GetWorkerByData(fio);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.FIO, Is.EqualTo(fio));
_workerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
_workerStorageContract.Verify(x =>
x.GetElementByFIO(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetWorkerByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_workerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData(null),
Throws.TypeOf<ArgumentNullException>());
Assert.That(() =>
_workerBusinessLogicContract.GetWorkerByData(string.Empty),
Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Never);
_workerStorageContract.Verify(x =>
x.GetElementByFIO(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetWorkerByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_workerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
Assert.That(() =>
_workerBusinessLogicContract.GetWorkerByData(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Once);
_workerStorageContract.Verify(x =>
x.GetElementByFIO(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetWorkerByData_GetByFio_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData("fio"), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_workerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
Assert.That(() =>
_workerBusinessLogicContract.GetWorkerByData("fio"),
Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Never);
_workerStorageContract.Verify(x =>
x.GetElementByFIO(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetWorkerByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.GetElementByFIO(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x =>
x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
_workerStorageContract.Setup(x =>
x.GetElementByFIO(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData("fio"), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_workerStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
Assert.That(() =>
_workerBusinessLogicContract.GetWorkerByData(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
Assert.That(() =>
_workerBusinessLogicContract.GetWorkerByData("fio"),
Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Once);
_workerStorageContract.Verify(x =>
x.GetElementByFIO(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertWorker_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new WorkerDataModel(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false);
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>()))
.Callback((WorkerDataModel x) =>
{
flag = x.Id == record.Id && x.FIO == record.FIO && x.PostId == record.PostId && x.BirthDate == record.BirthDate &&
x.EmploymentDate == record.EmploymentDate && x.IsDeleted == record.IsDeleted;
});
var record = new WorkerDataModel(Guid.NewGuid().ToString(), "Иванов И.И.",
Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-16).AddDays(-1), DateTime.UtcNow,
false);
_workerStorageContract.Setup(x =>
x.AddElement(It.IsAny<WorkerDataModel>()))
.Callback((WorkerDataModel x) =>
{
flag = x.Id == record.Id && x.FIO == record.FIO &&
x.PostId == record.PostId && x.BirthDate == record.BirthDate &&
x.EmploymentDate == record.EmploymentDate &&
x.IsDeleted == record.IsDeleted;
});
//Act
_workerBusinessLogicContract.InsertWorker(record);
//Assert
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Once);
_workerStorageContract.Verify(x =>
x.AddElement(It.IsAny<WorkerDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertWorker_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>())).Throws(new ElementExistsException("Data", "Data"));
_workerStorageContract.Setup(x =>
x.AddElement(It.IsAny<WorkerDataModel>())).Throws(new
ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementExistsException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Once);
Assert.That(() =>
_workerBusinessLogicContract.InsertWorker(new(Guid.NewGuid().ToString(), "Иванов И.И.",
Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-16).AddDays(-1), DateTime.UtcNow,
false)), Throws.TypeOf<ElementExistsException>());
_workerStorageContract.Verify(x =>
x.AddElement(It.IsAny<WorkerDataModel>()), Times.Once);
}
[Test]
public void InsertWorker_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.InsertWorker(null), Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Never);
Assert.That(() => _workerBusinessLogicContract.InsertWorker(null),
Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.Verify(x =>
x.AddElement(It.IsAny<WorkerDataModel>()), Times.Never);
}
[Test]
public void InsertWorker_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new WorkerDataModel("id", "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ValidationException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Never);
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new
WorkerDataModel("id", "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-
16).AddDays(-1), DateTime.UtcNow, false)), Throws.TypeOf<ValidationException>());
_workerStorageContract.Verify(x =>
x.AddElement(It.IsAny<WorkerDataModel>()), Times.Never);
}
[Test]
public void InsertWorker_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x =>
x.AddElement(It.IsAny<WorkerDataModel>())).Throws(new StorageException(new
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Once);
Assert.That(() =>
_workerBusinessLogicContract.InsertWorker(new(Guid.NewGuid().ToString(), "Иванов И.И.",
Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-16).AddDays(-1), DateTime.UtcNow,
false)), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x =>
x.AddElement(It.IsAny<WorkerDataModel>()), Times.Once);
}
[Test]
public void UpdateWorker_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new WorkerDataModel(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false);
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>()))
.Callback((WorkerDataModel x) =>
{
flag = x.Id == record.Id && x.FIO == record.FIO && x.PostId == record.PostId && x.BirthDate == record.BirthDate &&
x.EmploymentDate == record.EmploymentDate && x.IsDeleted == record.IsDeleted;
});
var record = new WorkerDataModel(Guid.NewGuid().ToString(), "Иванов И.И.",
Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-16).AddDays(-1), DateTime.UtcNow,
false);
_workerStorageContract.Setup(x =>
x.UpdElement(It.IsAny<WorkerDataModel>()))
.Callback((WorkerDataModel x) =>
{
flag = x.Id == record.Id && x.FIO == record.FIO &&
x.PostId == record.PostId && x.BirthDate == record.BirthDate &&
x.EmploymentDate == record.EmploymentDate &&
x.IsDeleted == record.IsDeleted;
});
//Act
_workerBusinessLogicContract.UpdateWorker(record);
//Assert
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Once);
_workerStorageContract.Verify(x =>
x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdateWorker_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>())).Throws(new ElementNotFoundException(""));
_workerStorageContract.Setup(x =>
x.UpdElement(It.IsAny<WorkerDataModel>())).Throws(new
ElementNotFoundException("", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Once);
Assert.That(() =>
_workerBusinessLogicContract.UpdateWorker(new(Guid.NewGuid().ToString(), "Иванов И.И.",
Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-16).AddDays(-1), DateTime.UtcNow,
false)), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x =>
x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Once);
}
[Test]
public void UpdateWorker_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(null), Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Never);
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(null),
Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.Verify(x =>
x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Never);
}
[Test]
public void UpdateWorker_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new WorkerDataModel("id", "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ValidationException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Never);
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new
WorkerDataModel("id", "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-
16).AddDays(-1), DateTime.UtcNow, false)), Throws.TypeOf<ValidationException>());
_workerStorageContract.Verify(x =>
x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Never);
}
[Test]
public void UpdateWorker_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x =>
x.UpdElement(It.IsAny<WorkerDataModel>())).Throws(new StorageException(new
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Once);
Assert.That(() =>
_workerBusinessLogicContract.UpdateWorker(new(Guid.NewGuid().ToString(), "Иванов И.И.",
Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-16).AddDays(-1), DateTime.UtcNow,
false)), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x =>
x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Once);
}
[Test]
public void DeleteWorker_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_workerStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
_workerStorageContract.Setup(x => x.DelElement(It.Is((string x) => x
== id))).Callback(() => { flag = true; });
//Act
_workerBusinessLogicContract.DeleteWorker(id);
//Assert
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()),
Times.Once);
Assert.That(flag);
}
[Test]
public void DeleteWorker_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_workerStorageContract.Setup(x => x.DelElement(It.Is((string x) => x != id))).Throws(new ElementNotFoundException(id));
_workerStorageContract.Setup(x => x.DelElement(It.Is((string x) => x
!= id))).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.DeleteWorker(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(() =>
_workerBusinessLogicContract.DeleteWorker(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()),
Times.Once);
}
[Test]
public void DeleteWorker_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.DeleteWorker(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _workerBusinessLogicContract.DeleteWorker(string.Empty), Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
Assert.That(() => _workerBusinessLogicContract.DeleteWorker(null),
Throws.TypeOf<ArgumentNullException>());
Assert.That(() =>
_workerBusinessLogicContract.DeleteWorker(string.Empty),
Throws.TypeOf<ArgumentNullException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()),
Times.Never);
}
[Test]
public void DeleteWorker_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.DeleteWorker("id"), Throws.TypeOf<ValidationException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
Assert.That(() => _workerBusinessLogicContract.DeleteWorker("id"),
Throws.TypeOf<ValidationException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()),
Times.Never);
}
[Test]
public void DeleteWorker_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x =>
x.DelElement(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.DeleteWorker(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(() =>
_workerBusinessLogicContract.DeleteWorker(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()),
Times.Once);
}
}

View File

@@ -3,6 +3,7 @@ using NUnit.Framework;
using DaisiesContracts.Exceptions;
using DaisiesContracts.Infrastructure.BuyerConfigurations;
using System;
using DaisiesTests.Infrastructure;
namespace DaisiesTests.DataModelsTests;
@@ -12,52 +13,52 @@ internal class BuyerDataModelTests
[Test]
public void IdIsNullOrEmptyTest()
{
var model = CreateDataModel(null, "Иванов И.И.", "number", 15, new BuyerConfiguration() { });
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
var model = CreateDataModel(null, "Иванов И.И.", DateTime.UtcNow.AddYears(-20), "number", 10, 15, new BuyerConfiguration() { });
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
model = CreateDataModel(string.Empty, "Иванов И.И.", "number", 15, new BuyerConfiguration() { });
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(string.Empty, "Иванов И.И.", DateTime.UtcNow.AddYears(-20), "number", 10, 15, new BuyerConfiguration() { });
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var model = CreateDataModel("not a guid", "Иванов И.И.", "number", 15, new BuyerConfiguration() { });
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
var model = CreateDataModel("not a guid", "Иванов И.И.", DateTime.UtcNow.AddYears(-20), "number", 10, 15, new BuyerConfiguration() { });
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void FioIsNullOrEmptyTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), null, "number", 15, new BuyerConfiguration() { });
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
var model = CreateDataModel(Guid.NewGuid().ToString(), null, DateTime.UtcNow.AddYears(-20), "number", 10, 15, new BuyerConfiguration() { });
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, "number", 15, new BuyerConfiguration() { });
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, DateTime.UtcNow.AddYears(-20), "number", 10, 15, new BuyerConfiguration() { });
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void FioIsNotCorrectTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов","number", 15, new BuyerConfiguration() { });
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
var model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов", DateTime.UtcNow.AddYears(-20), "number", 10, 15, new BuyerConfiguration() { });
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void PhoneNumberIsNullOrEmptyTest()
{
var buyer = CreateDataModel(Guid.NewGuid().ToString(), "fio", null, 15, new BuyerConfiguration() { });
Assert.That(() => buyer.Validate(),
var buyer = CreateDataModel(Guid.NewGuid().ToString(), "fio", DateTime.UtcNow.AddYears(-20), null, 10, 15, new BuyerConfiguration() { });
Assert.That(() => buyer.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
buyer = CreateDataModel(Guid.NewGuid().ToString(), "fio", string.Empty, 15, new BuyerConfiguration() { });
Assert.That(() => buyer.Validate(),
buyer = CreateDataModel(Guid.NewGuid().ToString(), "fio", DateTime.UtcNow.AddYears(-20), string.Empty, 10, 15, new BuyerConfiguration() { });
Assert.That(() => buyer.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
[Test]
public void PhoneNumberIsIncorrectTest()
{
var buyer = CreateDataModel(Guid.NewGuid().ToString(), "fio", "7777", 15, new BuyerConfiguration() { });
Assert.That(() => buyer.Validate(),
var buyer = CreateDataModel(Guid.NewGuid().ToString(), "fio", DateTime.UtcNow.AddYears(-20), "7777", 10, 15, new BuyerConfiguration() { });
Assert.That(() => buyer.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
@@ -65,8 +66,8 @@ internal class BuyerDataModelTests
[Test]
public void BirthDateIsFutureTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), "fio","number", 15, new BuyerConfiguration() { });
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
var model = CreateDataModel(Guid.NewGuid().ToString(), "fio", DateTime.UtcNow.AddYears(-14).AddDays(1), "number", 10, 15, new BuyerConfiguration() { });
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -74,11 +75,13 @@ internal class BuyerDataModelTests
{
var id = Guid.NewGuid().ToString();
var fio = "Иванов И.И.";
var birthDate = DateTime.UtcNow.AddYears(-20);
var phoneNumber = "+7-777-777-77-77";
var drinksBought = 2;
var discountSize = 11;
var configuration = new BuyerConfiguration() { };
var model = CreateDataModel(id, fio, phoneNumber, discountSize, configuration);
Assert.That(() => model.Validate(), Throws.Nothing);
var model = CreateDataModel(id, fio, birthDate, phoneNumber, drinksBought, discountSize, configuration);
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(model.Id, Is.EqualTo(id));
@@ -91,21 +94,22 @@ internal class BuyerDataModelTests
[Test]
public void ConfigurationModelIsNullTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), "fio", "number", 15, null);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
var model = CreateDataModel(Guid.NewGuid().ToString(), "fio", DateTime.UtcNow.AddYears(-14).AddDays(1), "number", 10, 15, null);
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void DiscountMultiplierIsLessZeroOrMoreOneTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), "fio", "number", 15, new BuyerConfiguration() { DiscountMultiplier = -1 });
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), "fio", "number", 15, new BuyerConfiguration() { DiscountMultiplier = 1.2 });
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
var model = CreateDataModel(Guid.NewGuid().ToString(), "fio", DateTime.UtcNow.AddYears(-14).AddDays(1), "number", 10, 15, new BuyerConfiguration() { DiscountMultiplier = -1 });
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), "fio", DateTime.UtcNow.AddYears(-14).AddDays(1), "number", 10, 15, new BuyerConfiguration() { DiscountMultiplier = 1.2 });
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
private static BuyerDataModel CreateDataModel(string? id, string? fio,string? phoneNumber, double discountSize, BuyerConfiguration configuration)
private static BuyerDataModel CreateDataModel(string? id, string? fio, DateTime birthDate, string? phoneNumber, int drinksBought, double discountSize, BuyerConfiguration configuration)
=> new(id, fio, phoneNumber, discountSize, configuration);
}

View File

@@ -2,34 +2,36 @@
using NUnit.Framework;
using DaisiesContracts.Exceptions;
using DaisiesTests.StoragesContracts;
using DaisiesTests.Infrastructure;
namespace DaisiesTests.DataModelsTests;
[TestFixture]
internal class ClientDiscountDataModelTests
{
[Test]
public void BuyerIdIsNullOrEmptyTest()
{
var product = CreateDataModel(null, 100, 10);
Assert.That(() => product.Validate(),
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
product = CreateDataModel(string.Empty, 100, 10);
Assert.That(() => product.Validate(),
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductIdIsNotGuidTest()
{
var product = CreateDataModel("id", 100, 10);
Assert.That(() => product.Validate(),
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
[Test]
public void personalDiscountIsLessThenZeroTest()
{
var product = CreateDataModel(Guid.NewGuid().ToString(), -100, 10);
Assert.That(() => product.Validate(),
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
@@ -37,7 +39,7 @@ internal class ClientDiscountDataModelTests
public void TotalSumIsLessThenZeroTest()
{
var product = CreateDataModel(Guid.NewGuid().ToString(), -100, 10);
Assert.That(() => product.Validate(),
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
@@ -48,7 +50,7 @@ internal class ClientDiscountDataModelTests
var totalSum = 100;
var personalDiscount = 10;
var clientDiscount = CreateDataModel(buyerId, totalSum, personalDiscount);
Assert.That(() => clientDiscount.Validate(), Throws.Nothing);
Assert.That(() => clientDiscount.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(clientDiscount.BuyerId, Is.EqualTo(buyerId));

View File

@@ -1,6 +1,7 @@
using DaisiesContracts.DataModels;
using DaisiesContracts.Enum;
using DaisiesContracts.Exceptions;
using DaisiesTests.Infrastructure;
using NUnit.Framework;
namespace DaisiesTests.DataModelsTests;
@@ -11,64 +12,67 @@ internal class PostDataModelTests
[Test]
public void IdIsNullOrEmptyTest()
{
var post = CreateDataModel(null, "name", PostType.Assistant, 10);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(string.Empty, "name", PostType.Assistant, 10);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
var model = CreateDataModel(null, "name", PostType.Florist, 100);
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
model = CreateDataModel(string.Empty, "name", PostType.Florist, 100);
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var post = CreateDataModel("id", "name", PostType.Assistant, 10);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
var model = CreateDataModel("id", "name", PostType.Florist, 100);
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostNameIsEmptyTest()
public void PostNameIsNullOrEmptyTest()
{
var manufacturer = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Assistant, 10);
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
manufacturer = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Assistant, 10);
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
var model = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Florist, 100);
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Florist, 100);
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostTypeIsNoneTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.None, 10);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
var model = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.None, 100);
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void SalaryIsLessOrZeroTest()
public void SalaryIsZeroNegativeTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, 0);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, -10);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
var model = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Florist, 0);
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Florist, -1);
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var postId = Guid.NewGuid().ToString();
var postPostId = Guid.NewGuid().ToString();
var id = Guid.NewGuid().ToString();
var postName = "name";
var postType = PostType.Assistant;
var salary = 10;
var isActual = false;
var changeDate = DateTime.UtcNow.AddDays(-1);
var post = CreateDataModel(postId, postName, postType, salary);
Assert.That(() => post.Validate(), Throws.Nothing);
var postType = PostType.Florist;
var salary = 100.50;
var isActual = true;
var changeDate = DateTime.UtcNow;
var model = CreateDataModel(id, postName, postType, salary);
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(post.Id, Is.EqualTo(postId));
Assert.That(post.PostName, Is.EqualTo(postName));
Assert.That(post.PostType, Is.EqualTo(postType));
Assert.That(post.Salary, Is.EqualTo(salary));
Assert.That(model.Id, Is.EqualTo(id));
Assert.That(model.PostName, Is.EqualTo(postName));
Assert.That(model.PostType, Is.EqualTo(postType));
Assert.That(model.Salary, Is.EqualTo(salary));
});
}
private static PostDataModel CreateDataModel(string? id, string? postName, PostType postType, double salary) => new(id, postName, postType, salary);
private static PostDataModel CreateDataModel(string? id, string? postName, PostType postType, double salary)
=> new(id, postName, postType, salary);
}

View File

@@ -1,6 +1,7 @@
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.Enum;
using DaisiesTests.Infrastructure;
namespace DaisiesTests.DataModelsTests;
@@ -10,30 +11,30 @@ internal class ProductDataModelTests
[Test]
public void IdIsNullOrEmptyTest()
{
var product = CreateDataModel(null, "name", ProductType.Composition, Guid.NewGuid().ToString(), 10, false);
Assert.That(() => product.Validate(),
var product = CreateDataModel(null, "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
product = CreateDataModel(string.Empty, "name", ProductType.Composition, Guid.NewGuid().ToString(), 10, false);
Assert.That(() => product.Validate(),
product = CreateDataModel(string.Empty, "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var product = CreateDataModel("id", "name", ProductType.Composition, Guid.NewGuid().ToString(), 10, false);
Assert.That(() => product.Validate(),
var product = CreateDataModel("id", "name", ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductNameIsEmptyTest()
{
var product = CreateDataModel(Guid.NewGuid().ToString(), null,
ProductType.Composition, Guid.NewGuid().ToString(), 10, false);
Assert.That(() => product.Validate(),
ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
product = CreateDataModel(Guid.NewGuid().ToString(), string.Empty,
ProductType.Composition, Guid.NewGuid().ToString(), 10, false);
Assert.That(() => product.Validate(),
ProductType.Accessory, Guid.NewGuid().ToString(), 10, false);
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
[Test]
@@ -41,39 +42,39 @@ internal class ProductDataModelTests
{
var product = CreateDataModel(Guid.NewGuid().ToString(), null,
ProductType.None, Guid.NewGuid().ToString(), 10, false);
Assert.That(() => product.Validate(),
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
[Test]
public void SupplierIdIsNullOrEmptyTest()
{
var product = CreateDataModel(Guid.NewGuid().ToString(), "name",
ProductType.Composition, null, 10, false);
Assert.That(() => product.Validate(),
ProductType.Accessory, null, 10, false);
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
product = CreateDataModel(Guid.NewGuid().ToString(), "name",
ProductType.Composition, string.Empty, 10, false);
Assert.That(() => product.Validate(),
ProductType.Accessory, string.Empty, 10, false);
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
[Test]
public void SupplierIdIsNotGuidTest()
{
var product = CreateDataModel(Guid.NewGuid().ToString(), "name",
ProductType.Composition, "supplierId", 10, false);
Assert.That(() => product.Validate(),
ProductType.Accessory, "supplierId", 10, false);
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
[Test]
public void PriceIsLessOrZeroTest()
{
var product = CreateDataModel(Guid.NewGuid().ToString(), "name",
ProductType.Composition, Guid.NewGuid().ToString(), 0, false);
Assert.That(() => product.Validate(),
ProductType.Accessory, Guid.NewGuid().ToString(), 0, false);
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
product = CreateDataModel(Guid.NewGuid().ToString(), "name",
ProductType.Composition, Guid.NewGuid().ToString(), -10, false);
Assert.That(() => product.Validate(),
ProductType.Accessory, Guid.NewGuid().ToString(), -10, false);
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
[Test]
@@ -81,13 +82,13 @@ internal class ProductDataModelTests
{
var productId = Guid.NewGuid().ToString();
var productName = "name";
var productType = ProductType.Composition;
var productType = ProductType.Accessory;
var productSupplierId = Guid.NewGuid().ToString();
var productPrice = 10;
var productIsDelete = false;
var product = CreateDataModel(productId, productName, productType,
productSupplierId, productPrice, productIsDelete);
Assert.That(() => product.Validate(), Throws.Nothing);
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(product.Id, Is.EqualTo(productId));

View File

@@ -1,5 +1,6 @@
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesTests.Infrastructure;
using NUnit.Framework;
namespace DaisiesTests.DataModelsTests;
@@ -11,44 +12,47 @@ internal class ProductHistoryDataModelTests
public void ProductIdIsNullOrEmptyTest()
{
var product = CreateDataModel(null, 10);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
product = CreateDataModel(string.Empty, 10);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductIdIsNotGuidTest()
{
var product = CreateDataModel("id", 10);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
[Test]
public void OldPriceIsLessOrZeroTest()
{
var product = CreateDataModel(Guid.NewGuid().ToString(), 0);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
product = CreateDataModel(Guid.NewGuid().ToString(), -10);
Assert.That(() => product.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => product.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var productId = Guid.NewGuid().ToString();
var oldPrice = 10;
var productHistory = CreateDataModel(productId, oldPrice);
Assert.That(() => productHistory.Validate(), Throws.Nothing);
Assert.That(() => productHistory.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(productHistory.ProductId, Is.EqualTo(productId));
Assert.That(productHistory.OldPrice, Is.EqualTo(oldPrice));
Assert.That(productHistory.ChangeDate, Is.LessThan(DateTime.UtcNow));
Assert.That(productHistory.ChangeDate, Is.GreaterThan(DateTime.UtcNow.AddMinutes(-1)));
Assert.That(productHistory.ChangeDate,
Is.LessThan(DateTime.UtcNow));
Assert.That(productHistory.ChangeDate,
Is.GreaterThan(DateTime.UtcNow.AddMinutes(-1)));
});
}
private static ProductHistoryDataModel CreateDataModel(string? productId, double oldPrice) =>
new(productId, oldPrice);
private static ProductHistoryDataModel CreateDataModel(string? productId,
double oldPrice) =>
new(productId, oldPrice);
}

View File

@@ -1,5 +1,6 @@
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesTests.Infrastructure;
namespace DaisiesTests.DataModelsTests;
@@ -10,56 +11,56 @@ internal class SaleDataModelTests
public void IdIsNullOrEmptyTest()
{
var sale = CreateDataModel(null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
sale = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var sale = CreateDataModel("id", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void WorkerIdIsNullOrEmptyTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), null, Guid.NewGuid().ToString(), 10, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
sale = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, Guid.NewGuid().ToString(), 10, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void WorkerIdIsNotGuidTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), "workerId", Guid.NewGuid().ToString(), 10, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void BuyerIdIsNotGuidTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "buyerId", 10, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void SumIsLessOrZeroTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -10, false, CreateSubDataModel());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductsIsNullOrEmptyTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, false, null);
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, false, []);
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -72,7 +73,7 @@ internal class SaleDataModelTests
var isCancel = true;
var products = CreateSubDataModel();
var sale = CreateDataModel(saleId, workerId, buyerId, sum, isCancel, products);
Assert.That(() => sale.Validate(), Throws.Nothing);
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(sale.Id, Is.EqualTo(saleId));
@@ -84,8 +85,8 @@ internal class SaleDataModelTests
});
}
private static SaleDataModel CreateDataModel(string? id, string? workerId, string? buyerId, double sum, bool isCancel, List<SaleProductDataModel>? products) => new(id, workerId, buyerId, sum, isCancel, products);
private static SaleDataModel CreateDataModel(string? id, string? workerId, string? buyerId, double sum, bool isCancel, List<SaleProductDataModel>? products) =>
new(id, workerId, buyerId, sum, isCancel, products);
private static List<SaleProductDataModel> CreateSubDataModel()
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)];

View File

@@ -1,5 +1,6 @@
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesTests.Infrastructure;
using NUnit.Framework;
namespace DaisiesTests.DataModelsTests;
@@ -10,44 +11,55 @@ internal class SaleProductDataModelTests
[Test]
public void SaleIdIsNullOrEmptyTest()
{
var saleProduct = CreateDataModel(null, Guid.NewGuid().ToString(), 10);
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
saleProduct = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10);
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
var saleProduct = CreateDataModel(null, Guid.NewGuid().ToString(),
10);
Assert.That(() => saleProduct.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
saleProduct = CreateDataModel(string.Empty,
Guid.NewGuid().ToString(), 10);
Assert.That(() => saleProduct.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
[Test]
public void SaleIdIsNotGuidTest()
{
var saleProduct = CreateDataModel("saleId", Guid.NewGuid().ToString(), 10);
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
var saleProduct = CreateDataModel("saleId",
Guid.NewGuid().ToString(), 10);
Assert.That(() => saleProduct.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductIdIsNullOrEmptyTest()
{
var saleProduct = CreateDataModel(Guid.NewGuid().ToString(), null, 10);
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
saleProduct = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10);
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
var saleProduct = CreateDataModel(Guid.NewGuid().ToString(), null,
10);
Assert.That(() => saleProduct.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
saleProduct = CreateDataModel(string.Empty,
Guid.NewGuid().ToString(), 10);
Assert.That(() => saleProduct.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductIdIsNotGuidTest()
{
var saleProduct = CreateDataModel(Guid.NewGuid().ToString(), "productId", 10);
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
var saleProduct = CreateDataModel(Guid.NewGuid().ToString(),
"productId", 10);
Assert.That(() => saleProduct.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
[Test]
public void CountIsLessOrZeroTest()
{
var saleProduct = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0);
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
saleProduct = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -10);
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
var saleProduct = CreateDataModel(Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), 0);
Assert.That(() => saleProduct.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
saleProduct = CreateDataModel(Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), -10);
Assert.That(() => saleProduct.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
@@ -55,7 +67,7 @@ internal class SaleProductDataModelTests
var productId = Guid.NewGuid().ToString();
var count = 10;
var saleProduct = CreateDataModel(saleId, productId, count);
Assert.That(() => saleProduct.Validate(), Throws.Nothing);
Assert.That(() => saleProduct.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(saleProduct.SaleId, Is.EqualTo(saleId));
@@ -63,7 +75,7 @@ internal class SaleProductDataModelTests
Assert.That(saleProduct.Count, Is.EqualTo(count));
});
}
private static SaleProductDataModel CreateDataModel(string? saleId, string? productId, int count) =>
new(saleId, productId, count);
private static SaleProductDataModel CreateDataModel(string? saleId, string?
productId, int count) =>
new(saleId, productId, count);
}

View File

@@ -1,5 +1,6 @@
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesTests.Infrastructure;
using NUnit.Framework;
namespace DaisiesTests.DataModelsTests;
@@ -10,71 +11,98 @@ internal class WorkerDataModelTests
[Test]
public void IdIsNullOrEmptyTest()
{
var worker = CreateDataModel(null, "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
worker = CreateDataModel(string.Empty, "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
var worker = CreateDataModel(null, "fio", Guid.NewGuid().ToString(),
DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
worker = CreateDataModel(string.Empty, "fio",
Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var worker = CreateDataModel("id", "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
var worker = CreateDataModel("id", "fio", Guid.NewGuid().ToString(),
DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
[Test]
public void FIOIsNullOrEmptyTest()
{
var worker = CreateDataModel(Guid.NewGuid().ToString(), null, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
worker = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
var worker = CreateDataModel(Guid.NewGuid().ToString(), null,
Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
worker = CreateDataModel(Guid.NewGuid().ToString(), string.Empty,
Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
[Test]
public void FioIsNotCorrectTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-20), DateTime.UtcNow, false);
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostIdIsNullOrEmptyTest()
{
var worker = CreateDataModel(Guid.NewGuid().ToString(), "fio", null, DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
worker = CreateDataModel(Guid.NewGuid().ToString(), "fio", string.Empty, DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
var worker = CreateDataModel(Guid.NewGuid().ToString(), "fio", null,
DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
worker = CreateDataModel(Guid.NewGuid().ToString(), "fio",
string.Empty, DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
[Test]
public void PostIdIsNotGuidTest()
{
var worker = CreateDataModel(Guid.NewGuid().ToString(), "fio", "postId", DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
var worker = CreateDataModel(Guid.NewGuid().ToString(), "fio",
"postId", DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
[Test]
public void BirthDateIsNotCorrectTest()
{
var worker = CreateDataModel(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(1), DateTime.Now, false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
var worker = CreateDataModel(Guid.NewGuid().ToString(), "fio",
Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-16).AddDays(1), DateTime.UtcNow,
false);
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
[Test]
public void BirthDateAndEmploymentDateIsCorrectTest()
public void BirthDateAndEmploymentDateIsNotCorrectTest()
{
var worker = CreateDataModel(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-14), DateTime.Now.AddYears(16).AddDays(-1), false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
worker = CreateDataModel(Guid.NewGuid().ToString(), "fio", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-14), DateTime.Now.AddYears(16), false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>());
var worker = CreateDataModel(Guid.NewGuid().ToString(), "fio",
Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18), DateTime.UtcNow.AddYears(-
18).AddDays(-1), false);
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
worker = CreateDataModel(Guid.NewGuid().ToString(), "fio",
Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18), DateTime.UtcNow.AddYears(-
16), false);
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
var workerId = Guid.NewGuid().ToString();
var fio = "fio";
var fio = "Иванов И. И.";
var postId = Guid.NewGuid().ToString();
var birthDate = DateTime.Now.AddYears(-16).AddDays(-1);
var employmentDate = DateTime.Now;
var birthDate = DateTime.UtcNow.AddYears(-16).AddDays(-1);
var employmentDate = DateTime.UtcNow;
var isDelete = false;
var worker = CreateDataModel(workerId, fio, postId, birthDate, employmentDate, isDelete);
Assert.That(() => worker.Validate(), Throws.Nothing);
var worker = CreateDataModel(workerId, fio, postId, birthDate,
employmentDate, isDelete);
Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(worker.Id, Is.EqualTo(workerId));
@@ -82,11 +110,11 @@ internal class WorkerDataModelTests
Assert.That(worker.PostId, Is.EqualTo(postId));
Assert.That(worker.BirthDate, Is.EqualTo(birthDate));
Assert.That(worker.EmploymentDate,
Is.EqualTo(employmentDate));
Is.EqualTo(employmentDate));
Assert.That(worker.IsDeleted, Is.EqualTo(isDelete));
});
}
private static WorkerDataModel CreateDataModel(string? id, string? fio, string? postId, DateTime birthDate, DateTime employmentDate, bool isDeleted) =>
new(id, fio, postId, birthDate, employmentDate, isDeleted);
private static WorkerDataModel CreateDataModel(string? id, string? fio,
string? postId, DateTime birthDate, DateTime employmentDate, bool isDeleted) =>
new(id, fio, postId, birthDate, employmentDate, isDeleted);
}

View File

@@ -6,7 +6,7 @@ using Microsoft.EntityFrameworkCore;
namespace DaisiesTests.Infrastructure;
public static class DaisiesDbContextExtensions
internal static class DaisiesDbContextExtensions
{
public static Buyer InsertBuyerToDatabaseAndReturn(this DaisiesDbContext
dbContext, string? id = null, string fio = "Иванов И.И.", string phoneNumber = "+7-777-777-77-77", double discountSize = 0.01, BuyerConfiguration? configuration = null)
@@ -133,6 +133,7 @@ public static class DaisiesDbContextExtensions
public static Buyer? GetBuyerFromDatabase(this DaisiesDbContext dbContext, string id) => dbContext.Buyers.FirstOrDefault(x => x.Id == id);
public static Post? GetPostFromDatabaseByPostId(this DaisiesDbContext dbContext, string id) => dbContext.Posts.FirstOrDefault(x => x.PostId == id && x.IsActual); public static Product? GetProductFromDatabaseById(this DaisiesDbContext dbContext, string id) => dbContext.Products.FirstOrDefault(x => x.Id == id);
public static Post[] GetPostsFromDatabaseByPostId(this DaisiesDbContext dbContext, string id) => [.. dbContext.Posts.Where(x => x.PostId == id).OrderByDescending(x => x.ChangeDate)];
public static Sale? GetSaleFromDatabaseById(this DaisiesDbContext dbContext, string id) => dbContext.Sales.Include(x => x.SaleProducts).FirstOrDefault(x => x.Id == id);
public static Sale[] GetSalesByBuyerId(this DaisiesDbContext dbContext, string? buyerId) => [.. dbContext.Sales.Include(x => x.SaleProducts).Where(x => x.BuyerId == buyerId)];
public static Worker? GetWorkerFromDatabaseById(this DaisiesDbContext dbContext, string id) => dbContext.Workers.FirstOrDefault(x => x.Id == id);

View File

@@ -0,0 +1,19 @@
using DaisiesContracts.Resources;
using Microsoft.Extensions.Localization;
using Moq;
namespace DaisiesTests.Infrastructure;
internal class StringLocalizerMockCreator
{
private static Mock<IStringLocalizer<Messages>>? _mockObject = null;
public static IStringLocalizer<Messages> GetStringLocalizerMockObject()
{
if (_mockObject is null)
{
_mockObject = new Mock<IStringLocalizer<Messages>>();
_mockObject.Setup(_ => _[It.IsAny<string>()]).Returns(new LocalizedString("name", "value"));
}
return _mockObject!.Object;
}
}

View File

@@ -0,0 +1,506 @@
using DaisiesContracts.BindingModels;
using DaisiesContracts.Enum;
using DaisiesContracts.Infrastructure.BuyerConfigurations;
using DaisiesTests.Infrastructure;
using Microsoft.AspNetCore.Mvc.Testing;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Text.Json;
using System.Text;
using Microsoft.AspNetCore.TestHost;
using DaisiesDatabase;
using Microsoft.Extensions.Logging;
using Serilog;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace DaisiesTests.LocalizationTests;
internal abstract class BaseLocalizationControllerTests
{
protected abstract string GetLocale();
private WebApplicationFactory<Program> _webApplication;
protected HttpClient HttpClient { get; private set; }
protected static DaisiesDbContext DaisiesDbContext { get; private set; }
protected static readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNameCaseInsensitive = true };
private static string _workerId;
private static string _buyerId;
private static string _postId;
private static string _productId;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_webApplication = new CustomWebApplicationFactory<Program>();
HttpClient = _webApplication
.WithWebHostBuilder(builder =>
{
builder.ConfigureTestServices(services =>
{
using var loggerFactory = new LoggerFactory();
loggerFactory.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build())
.CreateLogger());
services.AddSingleton(loggerFactory);
});
})
.CreateClient();
var request = HttpClient.GetAsync("/login/user").GetAwaiter().GetResult();
var data = request.Content.ReadAsStringAsync().GetAwaiter().GetResult();
HttpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {data}");
HttpClient.DefaultRequestHeaders.Add("Accept-Language", GetLocale());
DaisiesDbContext = _webApplication.Services.GetRequiredService<DaisiesDbContext>();
DaisiesDbContext.Database.EnsureDeleted();
DaisiesDbContext.Database.EnsureCreated();
}
[SetUp]
public void SetUp()
{
_workerId = DaisiesDbContext.InsertWorkerToDatabaseAndReturn(fio: "Worker W.W.").Id;
_buyerId = DaisiesDbContext.InsertBuyerToDatabaseAndReturn(fio: "Buyer B.B.").Id;
_postId = DaisiesDbContext.InsertPostToDatabaseAndReturn(postName: "Post").PostId;
_productId = DaisiesDbContext.InsertProductToDatabaseAndReturn().Id;
}
[TearDown]
public void TearDown()
{
DaisiesDbContext.RemoveClientDiscountsFromDatabase();
DaisiesDbContext.RemoveSalesFromDatabase();
DaisiesDbContext.RemoveWorkersFromDatabase();
DaisiesDbContext.RemovePostsFromDatabase();
DaisiesDbContext.RemoveProductsFromDatabase();
DaisiesDbContext.RemoveBuyersFromDatabase();
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
DaisiesDbContext?.Database.EnsureDeleted();
DaisiesDbContext?.Dispose();
HttpClient?.Dispose();
_webApplication?.Dispose();
}
protected static async Task<T?> GetModelFromResponseAsync<T>(HttpResponseMessage response) =>
JsonSerializer.Deserialize<T>(await response.Content.ReadAsStringAsync(), JsonSerializerOptions);
protected static StringContent MakeContent(object model) =>
new(JsonSerializer.Serialize(model), Encoding.UTF8, "application/json");
[Test]
public async Task LoadProductsHistory_ReturnsFile()
{
//Arrange
var supplierId = Guid.NewGuid().ToString();
var product1 = DaisiesDbContext.InsertProductToDatabaseAndReturn(
productName: "Name1",
productType: ProductType.Composition,
supplierId: Guid.NewGuid().ToString(),
price: 15,
isDeleted: false);
var product2 = DaisiesDbContext.InsertProductToDatabaseAndReturn(
productName: "Name2",
productType: ProductType.Composition,
supplierId: Guid.NewGuid().ToString(),
price: 10,
isDeleted: false);
var productId1 = product1.Id;
var productId2 = product2.Id;
DaisiesDbContext.InsertProductHistoryToDatabaseAndReturn(productId1, 19, DateTime.UtcNow);
DaisiesDbContext.InsertProductHistoryToDatabaseAndReturn(productId2, 20, DateTime.UtcNow);
DaisiesDbContext.InsertProductHistoryToDatabaseAndReturn(productId1, 44, DateTime.UtcNow);
DaisiesDbContext.InsertProductHistoryToDatabaseAndReturn(productId1, 43, DateTime.UtcNow);
DaisiesDbContext.InsertProductHistoryToDatabaseAndReturn(productId2, 75, DateTime.UtcNow);
//Act
var response = await HttpClient.GetAsync("/api/report/LoadHistories");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
using var data = await response.Content.ReadAsStreamAsync();
Assert.That(data, Is.Not.Null);
Assert.That(data.Length, Is.GreaterThan(0));
await AssertStreamAsync(response, $"file-{GetLocale()}.docx");
}
[Test]
public async Task LoadSales_WhenHaveRecords_ShouldSuccess_Test()
{
// Arrange
var worker1 = DaisiesDbContext.InsertWorkerToDatabaseAndReturn();
var worker2 = DaisiesDbContext.InsertWorkerToDatabaseAndReturn();
var buyer1 = DaisiesDbContext.InsertBuyerToDatabaseAndReturn(Guid.NewGuid().ToString(), "Покупатель И.И.", "+7-555-444-33-23", 0.05, new BuyerConfiguration());
var buyer2 = DaisiesDbContext.InsertBuyerToDatabaseAndReturn(fio: "fio 2", phoneNumber: "+7-777-777-12-12");
var product1 = DaisiesDbContext.InsertProductToDatabaseAndReturn(
productName: "name 1", price: 100);
var product2 = DaisiesDbContext.InsertProductToDatabaseAndReturn(
productName: "name 2", price: 700);
DaisiesDbContext.InsertProductHistoryToDatabaseAndReturn(product1.Id, 90, DateTime.UtcNow.AddDays(-1));
DaisiesDbContext.InsertProductHistoryToDatabaseAndReturn(product2.Id, 600, DateTime.UtcNow.AddDays(-1));
var x = DaisiesDbContext.InsertSaleToDatabaseAndReturn(
worker1.Id,
buyer1.Id,
saleDate: DateTime.UtcNow.AddDays(-1),
products: [(product1.Id, 20, 100), (product2.Id, 10, 100)], sum: 200);
DaisiesDbContext.InsertSaleToDatabaseAndReturn(
worker2.Id,
buyer2.Id,
saleDate: DateTime.UtcNow.AddDays(0),
products: [(product2.Id, 10, 100)], sum: 100);
//Act
var response = await HttpClient.GetAsync($"/api/report/loadsales?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
await AssertStreamAsync(response, $"file-{GetLocale()}.xlsx");
}
[Test]
public async Task LoadSalary_WhenHaveRecords_ShouldSuccess_Test()
{
// Arrange
var buyer1 = DaisiesDbContext.InsertBuyerToDatabaseAndReturn(fio: "Иванов И.И.", phoneNumber: "+7-777-77-12-11");
var buyer2 = DaisiesDbContext.InsertBuyerToDatabaseAndReturn(fio: "Александр А.А.", phoneNumber: "+7-777-77-12-12");
DaisiesDbContext.InsertClientDiscountToDatabaseAndReturn(
buyer1.Id,
totalSum: 100,
personalDiscount: 0.01,
discountDate: DateTime.UtcNow.AddDays(-10));
DaisiesDbContext.InsertClientDiscountToDatabaseAndReturn(
buyer1.Id,
totalSum: 200,
personalDiscount: 0.02,
discountDate: DateTime.UtcNow.AddDays(-2));
DaisiesDbContext.InsertClientDiscountToDatabaseAndReturn(
buyer1.Id,
totalSum: 300,
personalDiscount: 0.03,
discountDate: DateTime.UtcNow.AddDays(5));
DaisiesDbContext.InsertClientDiscountToDatabaseAndReturn(
buyer2.Id,
totalSum: 50,
personalDiscount: 0.005,
discountDate: DateTime.UtcNow.AddDays(-5));
DaisiesDbContext.InsertClientDiscountToDatabaseAndReturn(
buyer2.Id,
totalSum: 100,
personalDiscount: 0.01,
discountDate: DateTime.UtcNow.AddDays(-3));
//Act
var response = await HttpClient.GetAsync($"/api/report/loaddiscount?fromDate={DateTime.UtcNow.AddDays(-7):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(0):MM/dd/yyyy HH:mm:ss}");
//Assert
await AssertStreamAsync(response, $"file-{GetLocale()}.pdf");
}
private static async Task AssertStreamAsync(HttpResponseMessage response, string fileNameForSave = "")
{
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
using var data = await response.Content.ReadAsStreamAsync();
Assert.That(data, Is.Not.Null);
Assert.That(data.Length, Is.GreaterThan(0));
await SaveStreamAsync(data, fileNameForSave);
}
private static async Task SaveStreamAsync(Stream stream, string fileName)
{
if (string.IsNullOrEmpty(fileName))
{
return;
}
var path = Path.Combine(Directory.GetCurrentDirectory(), fileName);
if (File.Exists(path))
{
File.Delete(path);
}
stream.Position = 0;
using var fileStream = new FileStream(path, FileMode.OpenOrCreate);
await stream.CopyToAsync(fileStream);
}
protected abstract string MessageElementNotFound();
[TestCase("posts")]
[TestCase("workers/getrecord")]
public async Task Api_GetElement_NotFound_Test(string path)
{
//Act
var response = await HttpClient.GetAsync($"/api/{path}/{Guid.NewGuid()}");
//Assert
Assert.That(JToken.Parse(await response.Content.ReadAsStringAsync()).ToString(), Does.StartWith(MessageElementNotFound()));
}
private static IEnumerable<TestCaseData> TestDataElementExists()
{
yield return new TestCaseData(() => {
var model = CreatePostModel();
DaisiesDbContext.InsertPostToDatabaseAndReturn(model.Id);
return model;
}, "posts");
yield return new TestCaseData(() =>
{
var model = CreateWorkerModel(_postId);
DaisiesDbContext.InsertWorkerToDatabaseAndReturn(model.Id, postId: _postId);
return model;
}, "workers/register");
}
protected abstract string MessageElementExists();
[TestCaseSource(nameof(TestDataElementExists))]
public async Task Api_Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test(Func<object> createModel, string path)
{
//Arrange
var model = createModel();
//Act
var response = await HttpClient.PostAsync($"/api/{path}", MakeContent(model));
//Assert
Assert.That(JToken.Parse(await response.Content.ReadAsStringAsync()).ToString(), Does.StartWith(MessageElementExists()));
}
private static IEnumerable<TestCaseData> TestDataIdIncorrect()
{
yield return new TestCaseData(() => {
var model = CreateSaleModel(_workerId, _buyerId, _productId);
model.Id = "Id";
return model;
}, "sales/sale");
yield return new TestCaseData(() => {
var model = CreateProductModel(Guid.NewGuid().ToString());
model.Id = "Id";
return model;
}, "products/register");
yield return new TestCaseData(() => {
var model = CreateWorkerModel(_postId);
model.Id = "Id";
return model;
}, "workers/register");
}
protected abstract string MessageElementIdIncorrect();
[TestCaseSource(nameof(TestDataIdIncorrect))]
public async Task Api_Post_WhenDataIsIncorrect_ShouldBadRequest_Test(Func<object> createModel, string path)
{
//Arrange
var model = createModel();
//Act
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/{path}", MakeContent(model));
//Assert
Assert.That(JToken.Parse(await responseWithIdIncorrect.Content.ReadAsStringAsync()).ToString(), Does.StartWith(MessageElementIdIncorrect()));
}
[TestCase("products/delete")]
[TestCase("sales/cancel")]
[TestCase("posts")]
[TestCase("workers/delete")]
public async Task Api_DelElement_NotFound_Test(string path)
{
//Act
var response = await HttpClient.DeleteAsync($"/api/{path}/{Guid.NewGuid()}");
//Assert
Assert.That(JToken.Parse(await response.Content.ReadAsStringAsync()).ToString(), Does.StartWith(MessageElementNotFound()));
}
private static PostBindingModel CreatePostModel(string? postId = null, string postName = "name", int salary = 100, PostType postType = PostType.Florist)
=> new()
{
Id = postId ?? Guid.NewGuid().ToString(),
PostName = postName,
PostType = postType.ToString(),
Salary = salary
};
protected abstract string MessageValidationErrorIDIsEmpty();
private static IEnumerable<TestCaseData> TestDataValidationErrorIdIsEmpty()
{
yield return new TestCaseData(() =>
{
var model = CreatePostModel();
model.Id = "";
return model;
}, "posts");
yield return new TestCaseData(() =>
{
var model = CreateProductModel(Guid.NewGuid().ToString());
model.Id = "";
return model;
}, "products/changeinfo/");
yield return new TestCaseData(() => {
var model = CreateWorkerModel(_postId);
model.Id = "";
return model;
}, "workers/changeinfo/");
}
[TestCaseSource(nameof(TestDataValidationErrorIdIsEmpty))]
public async Task Api_Put_ValidationError_IdIsEmpty_ShouldBadRequest_Test(Func<object> createModel, string path)
{
//Arrange
var model = createModel();
//Act
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/{path}", MakeContent(model));
//Assert
Assert.That(JToken.Parse(await responseWithIdIncorrect.Content.ReadAsStringAsync()).ToString(), Does.StartWith(MessageValidationErrorIDIsEmpty()));
}
protected abstract string MessageValidationErrorIDIsNotGuid();
private static IEnumerable<TestCaseData> TestDataValidationErrorIdIsNotGuid()
{
yield return new TestCaseData(() =>
{
var model = CreatePostModel();
model.Id = "id";
return model;
}, "posts");
yield return new TestCaseData(() =>
{
var model = CreateProductModel(Guid.NewGuid().ToString());
model.Id = "id";
return model;
}, "products/changeinfo/");
yield return new TestCaseData(() => {
var model = CreateWorkerModel(_postId);
model.Id = "id";
return model;
}, "workers/changeinfo/");
}
[TestCaseSource(nameof(TestDataValidationErrorIdIsNotGuid))]
public async Task Api_Put_ValidationError_IIsNotGuid_ShouldBadRequest_Test(Func<object> createModel, string path)
{
//Arrange
var model = createModel();
//Act
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/{path}", MakeContent(model));
//Assert
Assert.That(JToken.Parse(await responseWithIdIncorrect.Content.ReadAsStringAsync()).ToString(), Does.StartWith(MessageValidationErrorIDIsNotGuid()));
}
protected abstract string MessageValidationStringIsEmpty();
private static IEnumerable<TestCaseData> TestDataValidationErrorStringIsEmpty()
{
yield return new TestCaseData(() =>
{
var model = CreateWorkerModel(_postId);
model.FIO = "";
return model;
}, "workers/changeinfo/");
yield return new TestCaseData(() =>
{
var model = CreateProductModel(Guid.NewGuid().ToString());
model.ProductName = "";
return model;
}, "products/changeinfo/");
}
[TestCaseSource(nameof(TestDataValidationErrorStringIsEmpty))]
public async Task Api_Put_ValidationError_StringIsEmpty_ShouldBadRequest_Test(Func<object> createModel, string path)
{
//Arrange
var model = createModel();
//Act
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/{path}", MakeContent(model));
//Assert
Assert.That(JToken.Parse(await responseWithIdIncorrect.Content.ReadAsStringAsync()).ToString(), Does.StartWith(MessageValidationStringIsEmpty()));
}
protected abstract string MessageElemenValidationErrorPostNameEmpty();
[TestCase("posts")]
public async Task Api_Put_ValidationError_PostNameIsEmpty_ShouldBadRequest_Test(string path)
{
//Arrange
var model = CreatePostModel();
model.PostName = "";
//Act
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/{path}", MakeContent(model));
//Assert
Assert.That(JToken.Parse(await responseWithIdIncorrect.Content.ReadAsStringAsync()).ToString(), Does.StartWith(MessageElemenValidationErrorPostNameEmpty()));
}
protected abstract string MessageElemenValidationErrorFioISEmpty();
[TestCase("workers/changeinfo/")]
public async Task Api_Put_ValidationError_FioIsEmpty_ShouldBadRequest_Test(string path)
{
//Arrange
var model = CreateWorkerModel(_postId);
model.FIO = "";
//Act
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/{path}", MakeContent(model));
//Assert
Assert.That(JToken.Parse(await responseWithIdIncorrect.Content.ReadAsStringAsync()).ToString(), Does.StartWith(MessageElemenValidationErrorFioISEmpty()));
}
private static WorkerBindingModel CreateWorkerModel(string postId, string? id = null, string fio = "Иванов И.В.", DateTime? birthDate = null, DateTime? employmentDate = null, string? configuration = null)
{
return new()
{
Id = id ?? Guid.NewGuid().ToString(),
FIO = fio,
BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-22),
EmploymentDate = employmentDate ?? DateTime.UtcNow.AddDays(-5),
PostId = postId
};
}
private static ProductBindingModel CreateProductModel(string supplierId,string? id = null, string productName = "name", ProductType productType =ProductType.Bouquet, double price = 1)=> new()
{
Id = id ?? Guid.NewGuid().ToString(),
SupplierId = supplierId,
ProductName = productName,
ProductType = productType.ToString(),
Price = price
};
private static SaleBindingModel CreateSaleModel(string workerId, string? buyerId, string productId, string? id = null, int count = 1, double price = 1.1)
{
var saleId = id ?? Guid.NewGuid().ToString();
return new()
{
Id = saleId,
WorkerId = workerId,
BuyerId = buyerId,
Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = productId, Count = count }]
};
}
private static SaleProductBindingModel CreateSaleProductModel(string productId, string? id = null, int count = 5)
{
return new() { SaleId = id ?? Guid.NewGuid().ToString(), ProductId = productId, Count = count };
}
}

View File

@@ -0,0 +1,15 @@
namespace DaisiesTests.LocalizationTests;
[TestFixture]
internal class DefaultTests : BaseLocalizationControllerTests
{
protected override string GetLocale() => "bla-BLA";
protected override string MessageElementExists() => "Уже существует элемент со значением";
protected override string MessageElementNotFound() => "Не найден элемент по данным";
protected override string MessageElementIdIncorrect() => "Переданы неверные данные";
protected override string MessageValidationErrorIDIsEmpty() => "Переданы неверные данные: Значение в поле Id пусто";
protected override string MessageValidationErrorIDIsNotGuid() => "Переданы неверные данные: Значение в поле Id не является типом уникального идентификатора";
protected override string MessageValidationStringIsEmpty() => "Переданы неверные данные: Значение в поле";
protected override string MessageElemenValidationErrorPostNameEmpty() => "Переданы неверные данные: Значение в поле PostName пусто";
protected override string MessageElemenValidationErrorFioISEmpty() => "Переданы неверные данные: Значение в поле FIO пусто";
}

View File

@@ -0,0 +1,14 @@
namespace DaisiesTests.LocalizationTests;
internal class EnUSTests : BaseLocalizationControllerTests
{
protected override string GetLocale() => "en-US";
protected override string MessageElementExists() => "There is already an element with value";
protected override string MessageElementNotFound() => "Not found element by data";
protected override string MessageElementIdIncorrect() => "Incorrect data transmitted";
protected override string MessageValidationErrorIDIsEmpty() => "Incorrect data transmitted: The value in field Id is empty";
protected override string MessageValidationErrorIDIsNotGuid() => "Incorrect data transmitted: The value in the Id field is not a unique identifier type.";
protected override string MessageValidationStringIsEmpty() => "Incorrect data transmitted: The value in field";
protected override string MessageElemenValidationErrorPostNameEmpty() => "Incorrect data transmitted: The value in field PostName is empty";
protected override string MessageElemenValidationErrorFioISEmpty() => "Incorrect data transmitted: The value in field FIO is empty";
}

View File

@@ -0,0 +1,16 @@
using System.Net;
namespace DaisiesTests.LocalizationTests;
internal class FrFRTests : BaseLocalizationControllerTests
{
protected override string GetLocale() => "fr-FR";
protected override string MessageElementExists() => "Il y a déjà un élément avec la valeur";
protected override string MessageElementNotFound() => "Élément introuvable par données";
protected override string MessageElementIdIncorrect() => "Données incorrectes transmises";
protected override string MessageValidationErrorIDIsEmpty() => "Données incorrectes transmises: La champ Id est vide";
protected override string MessageValidationErrorIDIsNotGuid() => "Données incorrectes transmises: La valeur dans le champ Id n'est pas un type d'identifiant unique.";
protected override string MessageValidationStringIsEmpty() => "Données incorrectes transmises: La champ ";
protected override string MessageElemenValidationErrorPostNameEmpty() => "Données incorrectes transmises: La champ PostName est vide";
protected override string MessageElemenValidationErrorFioISEmpty() => "Données incorrectes transmises: La champ FIO est vide";
}

View File

@@ -0,0 +1,14 @@
namespace DaisiesTests.LocalizationTests;
internal class RuRUTests : BaseLocalizationControllerTests
{
protected override string GetLocale() => "ru-RU";
protected override string MessageElementExists() => "Уже существует элемент со значением";
protected override string MessageElementNotFound() => "Не найден элемент по данным";
protected override string MessageElementIdIncorrect() => "Переданы неверные данные";
protected override string MessageValidationErrorIDIsEmpty() => "Переданы неверные данные: Значение в поле Id пусто";
protected override string MessageValidationErrorIDIsNotGuid() => "Переданы неверные данные: Значение в поле Id не является типом уникального идентификатора";
protected override string MessageValidationStringIsEmpty() => "Переданы неверные данные: Значение в поле ";
protected override string MessageElemenValidationErrorPostNameEmpty() => "Переданы неверные данные: Значение в поле PostName пусто";
protected override string MessageElemenValidationErrorFioISEmpty() => "Переданы неверные данные: Значение в поле FIO пусто";
}

View File

@@ -14,11 +14,11 @@ namespace DaisiesTests.StoragesContracts;
[TestFixture]
internal class BuyerStorageContractTest : BaseStorageContractTest
{
private BuyerStorageContract _buyerStorageContract;
private BuyerStorageContract _buyerStorageContract;
[SetUp]
public void SetUp()
{
_buyerStorageContract = new BuyerStorageContract(DaisiesDbContext);
_buyerStorageContract = new BuyerStorageContract(DaisiesDbContext, StringLocalizerMockCreator.GetStringLocalizerMockObject());
}
[TearDown]
public void TearDown()
@@ -46,7 +46,7 @@ internal class BuyerStorageContractTest : BaseStorageContractTest
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var buyer = DaisiesDbContext.InsertBuyerToDatabaseAndReturn();
@@ -88,22 +88,22 @@ internal class BuyerStorageContractTest : BaseStorageContractTest
[Test]
public void Try_AddElement_Test()
{
var buyer = CreateModel(Guid.NewGuid().ToString(), configurationModel: new BuyerConfiguration() { DiscountMultiplier = .001});
var buyer = CreateModel(Guid.NewGuid().ToString(), configurationModel: new BuyerConfiguration() { DiscountMultiplier = .001 });
_buyerStorageContract.AddElement(buyer);
AssertElement(DaisiesDbContext.GetBuyerFromDatabase(buyer.Id),buyer);
AssertElement(DaisiesDbContext.GetBuyerFromDatabase(buyer.Id), buyer);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var buyer = CreateModel(Guid.NewGuid().ToString(), fio: "New Fio", phoneNumber: "+5-555-555-55-55", discountSize: 500, configurationModel: new BuyerConfiguration() { DiscountMultiplier = .001 });
var buyer = CreateModel(Guid.NewGuid().ToString(), fio: "New Fio", phoneNumber: "+5-555-555-55-55", birthDate: DateTime.UtcNow.AddYears(-25), drinksBought: 5, discountSize: 500, configurationModel: new BuyerConfiguration() { DiscountMultiplier = .001 });
DaisiesDbContext.InsertBuyerToDatabaseAndReturn(buyer.Id);
Assert.That(() => _buyerStorageContract.AddElement(buyer),
Throws.TypeOf<ElementExistsException>());
Assert.That(() => _buyerStorageContract.AddElement(buyer),
Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSamePhoneNumber_Test()
{
var buyer = CreateModel(Guid.NewGuid().ToString(), fio: "New Fio", phoneNumber: "+5-555-555-55-55", discountSize: 500, configurationModel: new BuyerConfiguration() { DiscountMultiplier = .001 });
var buyer = CreateModel(Guid.NewGuid().ToString(), fio: "New Fio", phoneNumber: "+5-555-555-55-55", birthDate: DateTime.UtcNow.AddYears(-25), drinksBought: 5, discountSize: 500, configurationModel: new BuyerConfiguration() { DiscountMultiplier = .001 });
DaisiesDbContext.InsertBuyerToDatabaseAndReturn(phoneNumber:
buyer.PhoneNumber);
Assert.That(() => _buyerStorageContract.AddElement(buyer),
@@ -112,7 +112,7 @@ internal class BuyerStorageContractTest : BaseStorageContractTest
[Test]
public void Try_UpdElement_Test()
{
var buyer = CreateModel(Guid.NewGuid().ToString(), fio: "New Fio", phoneNumber: "+5-555-555-55-55",discountSize: 500);
var buyer = CreateModel(Guid.NewGuid().ToString(), fio: "New Fio", phoneNumber: "+5-555-555-55-55", birthDate: DateTime.UtcNow.AddYears(-25), drinksBought: 5, discountSize: 500);
DaisiesDbContext.InsertBuyerToDatabaseAndReturn(buyer.Id);
_buyerStorageContract.UpdElement(buyer);
AssertElement(DaisiesDbContext.GetBuyerFromDatabase(buyer.Id),
@@ -147,8 +147,8 @@ internal class BuyerStorageContractTest : BaseStorageContractTest
{
var buyer = DaisiesDbContext.InsertBuyerToDatabaseAndReturn();
var worker = DaisiesDbContext.InsertWorkerToDatabaseAndReturn();
DaisiesDbContext.InsertSaleToDatabaseAndReturn(worker.Id,buyer.Id);
DaisiesDbContext.InsertSaleToDatabaseAndReturn(worker.Id,buyer.Id);
DaisiesDbContext.InsertSaleToDatabaseAndReturn(worker.Id, buyer.Id);
DaisiesDbContext.InsertSaleToDatabaseAndReturn(worker.Id, buyer.Id);
var salesBeforeDelete = DaisiesDbContext.GetSalesByBuyerId(buyer.Id);
_buyerStorageContract.DelElement(buyer.Id);
var element = DaisiesDbContext.GetBuyerFromDatabase(buyer.Id);
@@ -171,7 +171,7 @@ internal class BuyerStorageContractTest : BaseStorageContractTest
}
[Test]
public void Try_AddElement_WithConstantCustomerConfiguration_Test()
public void Try_AddElement_WithConstantBuyerConfiguration_Test()
{
var constantDiscountMultiplyer = .001;
var discountMultiplier = .0005;
@@ -186,106 +186,42 @@ internal class BuyerStorageContractTest : BaseStorageContractTest
Assert.That((element.Configuration as ConstantBuyerConfiguration)!.RegularDiscountMultiplyer, Is.EqualTo(constantDiscountMultiplyer));
});
}
[Test]
public void Try_AddElement_WithVipCustomerConfiguration_Test()
public void Try_AddElement_WithVipBuyerConfiguration_Test()
{
// Arrange
var constantDiscountMultiplier = 0.001;
var discountMultiplier = 0.0005;
var extraDiscountMultiplier = 0.0009;
var buyer = CreateModel(
Guid.NewGuid().ToString(),
configurationModel: new VipBuyerConfiguration()
{
DiscountMultiplier = discountMultiplier,
ConstantDiscountMultiplier = constantDiscountMultiplier,
ExtraDiscountMultiplyer = extraDiscountMultiplier
});
// Act
var constantDiscountMultiplyer = .001;
var discountMultiplier = .0005;
var extraDiscountMultiplier = .0009;
var buyer = CreateModel(Guid.NewGuid().ToString(), configurationModel: new VipBuyerConfiguration() { DiscountMultiplier = discountMultiplier, ConstantDiscountMultiplier = constantDiscountMultiplyer, ExtraDiscountMultiplyer = extraDiscountMultiplier });
_buyerStorageContract.AddElement(buyer);
var element = DaisiesDbContext.GetBuyerFromDatabase(buyer.Id);
// Assert
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(VipBuyerConfiguration).Name));
Assert.That(
(element.Configuration as VipBuyerConfiguration)!.ConstantDiscountMultiplier,
Is.EqualTo(constantDiscountMultiplier).Within(0.0000001));
Assert.That(
(element.Configuration as VipBuyerConfiguration)!.DiscountMultiplier,
Is.EqualTo(discountMultiplier).Within(0.0000001));
Assert.That(
(element.Configuration as VipBuyerConfiguration)!.ExtraDiscountMultiplyer,
Is.EqualTo(extraDiscountMultiplier).Within(0.0000001));
Assert.That((element.Configuration as VipBuyerConfiguration)!.ConstantDiscountMultiplier, Is.EqualTo(constantDiscountMultiplyer));
Assert.That((element.Configuration as VipBuyerConfiguration)!.DiscountMultiplier, Is.EqualTo(discountMultiplier));
Assert.That((element.Configuration as VipBuyerConfiguration)!.ExtraDiscountMultiplyer, Is.EqualTo(extraDiscountMultiplier));
});
}
[Test]
public void Try_UpdElement_WithConstantCustomerConfiguration_Test()
public void Try_UpdElement_WithVipBuyerConfiguration_Test()
{
var buyer = DaisiesDbContext.InsertBuyerToDatabaseAndReturn();
var constantDiscountMultiplyer = .001;
var discountMultiplier = .0005;
_buyerStorageContract.UpdElement(CreateModel(buyer.Id, configurationModel: new ConstantBuyerConfiguration() { RegularDiscountMultiplyer = constantDiscountMultiplyer, DiscountMultiplier = discountMultiplier }));
var extraDiscountMultiplier = .0009;
_buyerStorageContract.UpdElement(CreateModel(buyer.Id, configurationModel: new VipBuyerConfiguration() { DiscountMultiplier = discountMultiplier, ConstantDiscountMultiplier = constantDiscountMultiplyer, ExtraDiscountMultiplyer = extraDiscountMultiplier }));
var element = DaisiesDbContext.GetBuyerFromDatabase(buyer.Id);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(ConstantBuyerConfiguration).Name));
Assert.That((element.Configuration as ConstantBuyerConfiguration)!.DiscountMultiplier, Is.EqualTo(discountMultiplier));
Assert.That((element.Configuration as ConstantBuyerConfiguration)!.RegularDiscountMultiplyer, Is.EqualTo(constantDiscountMultiplyer));
});
}
[Test]
public void Try_UpdElement_WithVipCustomerConfiguration_Test()
{
// Arrange
var buyer = DaisiesDbContext.InsertBuyerToDatabaseAndReturn();
var constantDiscountMultiplier = 0.001;
var discountMultiplier = 0.0005;
var extraDiscountMultiplier = 0.0009;
var updatedBuyer = CreateModel(
buyer.Id,
configurationModel: new VipBuyerConfiguration()
{
DiscountMultiplier = discountMultiplier,
ConstantDiscountMultiplier = constantDiscountMultiplier,
ExtraDiscountMultiplyer = extraDiscountMultiplier
});
// Act
_buyerStorageContract.UpdElement(updatedBuyer);
var element = DaisiesDbContext.GetBuyerFromDatabase(buyer.Id);
// Assert
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type,
Is.EqualTo(typeof(VipBuyerConfiguration).Name));
Assert.That(
(element.Configuration as VipBuyerConfiguration)!.ConstantDiscountMultiplier,
Is.EqualTo(constantDiscountMultiplier).Within(0.0000001),
"ConstantDiscountMultiplier не совпадает");
Assert.That(
(element.Configuration as VipBuyerConfiguration)!.DiscountMultiplier,
Is.EqualTo(discountMultiplier).Within(0.0000001),
"DiscountMultiplier не совпадает");
Assert.That(
(element.Configuration as VipBuyerConfiguration)!.ExtraDiscountMultiplyer,
Is.EqualTo(extraDiscountMultiplier).Within(0.0000001),
"ExtraDiscountMultiplyer не совпадает");
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(VipBuyerConfiguration).Name));
Assert.That((element.Configuration as VipBuyerConfiguration)!.ConstantDiscountMultiplier, Is.EqualTo(constantDiscountMultiplyer));
Assert.That((element.Configuration as VipBuyerConfiguration)!.DiscountMultiplier, Is.EqualTo(discountMultiplier));
Assert.That((element.Configuration as VipBuyerConfiguration)!.ExtraDiscountMultiplyer, Is.EqualTo(extraDiscountMultiplier));
});
}
private static void AssertElement(BuyerDataModel? actual, Buyer expected)
@@ -299,8 +235,8 @@ internal class BuyerStorageContractTest : BaseStorageContractTest
Assert.That(actual.DiscountSize, Is.EqualTo(expected.DiscountSize));
});
}
private static BuyerDataModel CreateModel(string id, string fio = "test", string phoneNumber = "+7-777-777-77-77", double discountSize = 10, BuyerConfiguration? configurationModel = null)
=> new(id, fio, phoneNumber, discountSize, configurationModel ?? new BuyerConfiguration() { DiscountMultiplier =.001});
private static BuyerDataModel CreateModel(string id, string fio = "test", DateTime? birthDate = null, string phoneNumber = "+7-777-777-77-77", int drinksBought = 0, double discountSize = 10, BuyerConfiguration? configurationModel = null)
=> new(id, fio, phoneNumber, discountSize, configurationModel ?? new BuyerConfiguration() { DiscountMultiplier = .001 });
private static void AssertElement(Buyer? actual, BuyerDataModel expected)
{
Assert.That(actual, Is.Not.Null);

View File

@@ -3,6 +3,7 @@ using DaisiesContracts.Exceptions;
using DaisiesContracts.Infrastructure.BuyerConfigurations;
using DaisiesDatabase.Implementations;
using DaisiesDatabase.Models;
using DaisiesTests.Infrastructure;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
@@ -17,7 +18,7 @@ internal class ClientDiscountStorageContractTests : BaseStorageContractTest
[SetUp]
public void SetUp()
{
_clientDiscountStorageContract = new ClientDiscountStorageContract(DaisiesDbContext);
_clientDiscountStorageContract = new ClientDiscountStorageContract(DaisiesDbContext, StringLocalizerMockCreator.GetStringLocalizerMockObject());
_buyer = InsertBuyerToDatabaseAndReturn();
}
@@ -27,6 +28,33 @@ internal class ClientDiscountStorageContractTests : BaseStorageContractTest
DaisiesDbContext.Database.ExecuteSqlRaw("TRUNCATE \"ClientDiscounts\" CASCADE;");
DaisiesDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Buyers\" CASCADE;");
}
[Test]
public async Task Try_GetListAsync_ByPeriod_Test()
{
InsertClientDiscountToDatabaseAndReturn(_buyer.Id, 10, 0.01, DateTime.UtcNow.AddDays(-1).AddMinutes(-5));
InsertClientDiscountToDatabaseAndReturn(_buyer.Id, 11, 0.011, DateTime.UtcNow.AddDays(-1).AddMinutes(-5));
InsertClientDiscountToDatabaseAndReturn(_buyer.Id, 12, 0.012, DateTime.UtcNow.AddDays(-1).AddMinutes(5));
InsertClientDiscountToDatabaseAndReturn(_buyer.Id, 13, 0.013, DateTime.UtcNow.AddDays(1).AddMinutes(-5));
InsertClientDiscountToDatabaseAndReturn(_buyer.Id, 14, 0.014, DateTime.UtcNow.AddDays(1).AddMinutes(5));
InsertClientDiscountToDatabaseAndReturn(_buyer.Id, 15, 0.015, DateTime.UtcNow.AddDays(-2));
var list = await _clientDiscountStorageContract.GetListAsync(DateTime.UtcNow.AddDays(-1),
DateTime.UtcNow.AddDays(1), CancellationToken.None);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(2));
});
}
[Test]
public async Task Try_GetListAsync_WhenNoRecords_Test()
{
var list = await _clientDiscountStorageContract.GetListAsync(DateTime.UtcNow.AddDays(-10),
DateTime.UtcNow.AddDays(10), CancellationToken.None);
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
@@ -60,8 +88,7 @@ internal class ClientDiscountStorageContractTests : BaseStorageContractTest
{
var invalidClientDiscount = new ClientDiscountDataModel("InvalidId", 100, 10);
Assert.That(() => _clientDiscountStorageContract.AddElement(invalidClientDiscount),
Throws.TypeOf<StorageException>()
.With.Message.Contains("The value in the field Id is not a unique identifier"));
Throws.TypeOf<StorageException>());
}
@@ -102,13 +129,14 @@ internal class ClientDiscountStorageContractTests : BaseStorageContractTest
Throws.TypeOf<StorageException>());
}
private ClientDiscount InsertClientDiscountToDatabaseAndReturn(string buyerId, double totalSum, double personalDiscount)
private ClientDiscount InsertClientDiscountToDatabaseAndReturn(string buyerId, double totalSum, double personalDiscount, DateTime? discountDate = null)
{
var clientDiscount = new ClientDiscount
{
BuyerId = buyerId,
TotalSum = totalSum,
PersonalDiscount = personalDiscount
PersonalDiscount = personalDiscount,
DiscountDate = discountDate ?? DateTime.UtcNow
};
DaisiesDbContext.ClientDiscounts.Add(clientDiscount);
DaisiesDbContext.SaveChanges();
@@ -118,7 +146,7 @@ internal class ClientDiscountStorageContractTests : BaseStorageContractTest
private ClientDiscount? GetClientDiscountFromDatabaseByBuyerId(string buyerId) =>
DaisiesDbContext.ClientDiscounts.FirstOrDefault(x => x.BuyerId == buyerId);
private Buyer InsertBuyerToDatabaseAndReturn(string fio = "test", string phoneNumber = null, BuyerConfiguration? configuration = null)
private Buyer InsertBuyerToDatabaseAndReturn(string fio = "test", DateTime? birthDate = null, string phoneNumber = null, BuyerConfiguration? configuration = null)
{
phoneNumber ??= $"+7-{Guid.NewGuid().ToString("N").Substring(0, 10)}";
var buyer = new Buyer()
@@ -134,5 +162,4 @@ internal class ClientDiscountStorageContractTests : BaseStorageContractTest
return buyer;
}
}

View File

@@ -1,11 +1,9 @@
using DaisiesContracts.DataModels;
using DaisiesContracts.Enum;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using DaisiesDatabase.Implementations;
using DaisiesDatabase.Models;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using DaisiesTests.Infrastructure;
namespace DaisiesTests.StoragesContracts;
@@ -17,33 +15,25 @@ internal class PostStorageContractTest : BaseStorageContractTest
[SetUp]
public void SetUp()
{
_postStorageContract = new PostStorageContract(DaisiesDbContext);
_postStorageContract = new PostStorageContract(DaisiesDbContext, StringLocalizerMockCreator.GetStringLocalizerMockObject());
}
[TearDown]
public void TearDown()
{
DaisiesDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Posts\" CASCADE;");
DaisiesDbContext.RemovePostsFromDatabase();
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
// Arrange
var post1 = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
var post2 = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2");
var post3 = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3");
// Act
var post = DaisiesDbContext.InsertPostToDatabaseAndReturn(postName: "name 1");
DaisiesDbContext.InsertPostToDatabaseAndReturn(postName: "name 2");
DaisiesDbContext.InsertPostToDatabaseAndReturn(postName: "name 3");
var list = _postStorageContract.GetList();
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertPostInList(list, post1);
AssertPostInList(list, post2);
AssertPostInList(list, post3);
AssertElement(list.First(x => x.Id == post.PostId), post);
}
[Test]
@@ -54,167 +44,204 @@ internal class PostStorageContractTest : BaseStorageContractTest
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_OnlyActual_Test()
{
// Arrange
var activePost1 = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "Active 1", isActual: true);
var inactivePost = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "Inactive", isActual: false);
var activePost2 = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "Active 2", isActual: true);
// Act
var allPosts = _postStorageContract.GetList();
var activePostIds = DaisiesDbContext.Posts
.Where(p => p.IsActual)
.Select(p => p.PostId)
.ToList();
var filteredPosts = allPosts.Where(p => activePostIds.Contains(p.Id)).ToList();
// Assert
Assert.That(filteredPosts, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(filteredPosts, Has.Count.EqualTo(2));
Assert.That(filteredPosts.Any(p => p.Id == activePost1.PostId));
Assert.That(filteredPosts.Any(p => p.Id == activePost2.PostId));
Assert.That(!filteredPosts.Any(p => p.Id == inactivePost.PostId));
});
}
[Test]
public void Try_GetList_IncludeNoActual_Test()
{
var post1 = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
var post2 = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2");
var post3 = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3", isActual: false);
var list = _postStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertPostInList(list, post1);
AssertPostInList(list, post2);
AssertPostInList(list, post3);
}
[Test]
public void Try_GetPostWithHistory_WhenHaveRecords_Test()
{
var postId = Guid.NewGuid().ToString();
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isActual: true);
InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
DaisiesDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
DaisiesDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
DaisiesDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
var list = _postStorageContract.GetPostWithHistory(postId);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
}
[Test]
public void Try_GetPostWithHistory_WhenNoRecords_Test()
{
var postId = Guid.NewGuid().ToString();
DaisiesDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
DaisiesDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
DaisiesDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
var list = _postStorageContract.GetPostWithHistory(Guid.NewGuid().ToString());
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var post = DaisiesDbContext.InsertPostToDatabaseAndReturn();
AssertElement(_postStorageContract.GetElementById(post.PostId), post);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
DaisiesDbContext.InsertPostToDatabaseAndReturn();
Assert.That(() => _postStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementById_WhenRecordWasDeleted_Test()
{
var post = DaisiesDbContext.InsertPostToDatabaseAndReturn(isActual: false);
Assert.That(() => _postStorageContract.GetElementById(post.PostId), Is.Null);
}
[Test]
public void Try_GetElementById_WhenTrySearchById_Test()
{
var post = DaisiesDbContext.InsertPostToDatabaseAndReturn();
Assert.That(() => _postStorageContract.GetElementById(post.Id), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenHaveRecord_Test()
{
var post = DaisiesDbContext.InsertPostToDatabaseAndReturn();
AssertElement(_postStorageContract.GetElementByName(post.PostName), post);
}
[Test]
public void Try_GetElementByName_WhenNoRecord_Test()
{
DaisiesDbContext.InsertPostToDatabaseAndReturn();
Assert.That(() => _postStorageContract.GetElementByName("name"), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenRecordWasDeleted_Test()
{
var post = DaisiesDbContext.InsertPostToDatabaseAndReturn(isActual: false);
Assert.That(() => _postStorageContract.GetElementById(post.PostName), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var postModel = CreateModel(Guid.NewGuid().ToString());
_postStorageContract.AddElement(postModel);
var dbPost = GetPostFromDatabaseByPostId(postModel.Id);
AssertElement(dbPost, postModel);
var post = CreateModel(Guid.NewGuid().ToString());
_postStorageContract.AddElement(post);
AssertElement(DaisiesDbContext.GetPostFromDatabaseByPostId(post.Id), post);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
{
var postName = "Test Post";
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), postName);
var postModel = CreateModel(Guid.NewGuid().ToString(), postName);
var post = CreateModel(Guid.NewGuid().ToString(), "name unique");
DaisiesDbContext.InsertPostToDatabaseAndReturn(postName: post.PostName, isActual: true);
Assert.That(() => _postStorageContract.AddElement(post), Throws.TypeOf<ElementExistsException>());
}
Assert.That(() => _postStorageContract.AddElement(postModel),
Throws.TypeOf<ElementExistsException>());
[Test]
public void Try_AddElement_WhenHaveRecordWithSamePostId_Test()
{
var post = CreateModel(Guid.NewGuid().ToString());
DaisiesDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: true);
Assert.That(() => _postStorageContract.AddElement(post), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_Test()
{
var postId = Guid.NewGuid().ToString();
InsertPostToDatabaseAndReturn(postId, "Old Name");
var updatedModel = CreateModel(postId, "New Name");
var post = CreateModel(Guid.NewGuid().ToString());
DaisiesDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: true);
_postStorageContract.UpdElement(post);
var posts = DaisiesDbContext.GetPostsFromDatabaseByPostId(post.Id);
Assert.That(posts, Is.Not.Null);
Assert.That(posts, Has.Length.EqualTo(2));
AssertElement(posts[0], CreateModel(post.Id));
AssertElement(posts[^1], CreateModel(post.Id));
}
_postStorageContract.UpdElement(updatedModel);
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _postStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
}
var dbPost = GetPostFromDatabaseByPostId(postId);
Assert.That(dbPost, Is.Not.Null);
Assert.That(dbPost.PostName, Is.EqualTo("New Name"));
[Test]
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
{
var post = CreateModel(Guid.NewGuid().ToString(), "New Name");
DaisiesDbContext.InsertPostToDatabaseAndReturn(post.Id, postName: "name");
DaisiesDbContext.InsertPostToDatabaseAndReturn(postName: post.PostName);
Assert.That(() => _postStorageContract.UpdElement(post), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_WhenRecordWasDeleted_Test()
{
var post = CreateModel(Guid.NewGuid().ToString());
DaisiesDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: false);
Assert.That(() => _postStorageContract.UpdElement(post), Throws.TypeOf<ElementDeletedException>());
}
[Test]
public void Try_DelElement_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: true);
var post = DaisiesDbContext.InsertPostToDatabaseAndReturn(isActual: true);
_postStorageContract.DelElement(post.PostId);
var element = GetPostFromDatabaseByPostId(post.PostId);
Assert.Multiple(() =>
{
Assert.That(element, Is.Not.Null);
Assert.That(!element!.IsActual);
});
Assert.That(DaisiesDbContext.GetPostFromDatabaseByPostId(post.PostId), Is.Null);
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _postStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_WhenRecordWasDeleted_Test()
{
var post = DaisiesDbContext.InsertPostToDatabaseAndReturn(isActual: false);
Assert.That(() => _postStorageContract.DelElement(post.PostId), Throws.TypeOf<ElementDeletedException>());
}
[Test]
public void Try_ResElement_Test()
{
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
_postStorageContract.ResElement((post.PostId));
var dbPost = GetPostFromDatabaseByPostId(post.PostId);
Assert.That(dbPost, Is.Not.Null);
Assert.That(dbPost.IsActual, Is.True);
}
private Post InsertPostToDatabaseAndReturn(
string postId,
string postName = "test",
PostType postType = PostType.Assistant,
double salary = 10,
bool isActual = true)
{
var post = new Post
{
Id = Guid.NewGuid().ToString(),
PostId = postId,
PostName = postName,
PostType = postType,
Salary = salary,
IsActual = isActual,
ChangeDate = DateTime.UtcNow
};
DaisiesDbContext.Posts.Add(post);
DaisiesDbContext.SaveChanges();
return post;
}
private void AssertPostInList(IEnumerable<PostDataModel> list, Post expected)
{
var foundPost = list.FirstOrDefault(x => x.Id.ToString() == expected.PostId);
Assert.That(foundPost, Is.Not.Null, $"Не найден пост с ID {expected.PostId}");
AssertElement(foundPost, expected);
}
private static void AssertElement(PostDataModel actual, Post expected)
{
var post = DaisiesDbContext.InsertPostToDatabaseAndReturn(isActual: false);
_postStorageContract.ResElement(post.PostId);
var element = DaisiesDbContext.GetPostFromDatabaseByPostId(post.PostId);
Assert.Multiple(() =>
{
Assert.That(actual.Id.ToString(), Is.EqualTo(expected.PostId));
Assert.That(element, Is.Not.Null);
Assert.That(element!.IsActual);
});
}
[Test]
public void Try_ResElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _postStorageContract.ResElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_ResElement_WhenRecordNotWasDeleted_Test()
{
var post = DaisiesDbContext.InsertPostToDatabaseAndReturn(isActual: true);
Assert.That(() => _postStorageContract.ResElement(post.PostId), Throws.Nothing);
}
private static void AssertElement(PostDataModel? actual, Post expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.PostId));
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
Assert.That(actual.PostType, Is.EqualTo(expected.PostType));
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
});
}
private static void AssertElement(Post actual, PostDataModel expected)
private static PostDataModel CreateModel(string postId, string postName = "test", PostType postType = PostType.Assistant, double salary = 10)
=> new(postId, postName, postType, salary);
private static void AssertElement(Post? actual, PostDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.PostId, Is.EqualTo(expected.Id));
@@ -223,21 +250,4 @@ internal class PostStorageContractTest : BaseStorageContractTest
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
});
}
private static PostDataModel CreateModel(
string postId,
string postName = "test",
PostType postType = PostType.Assistant,
double salary = 10)
{
return new PostDataModel(postId, postName, postType, salary);
}
private Post GetPostFromDatabaseByPostId(string postId)
{
return DaisiesDbContext.Posts
.Where(x => x.PostId == postId)
.OrderByDescending(x => x.ChangeDate)
.FirstOrDefault();
}
}

View File

@@ -6,6 +6,7 @@ using DaisiesDatabase.Implementations;
using DaisiesDatabase.Models;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using DaisiesTests.Infrastructure;
namespace DaisiesTests.StoragesContracts;
@@ -17,7 +18,7 @@ internal class ProductStorageContractTest : BaseStorageContractTest
[SetUp]
public void SetUp()
{
_productStorageContract = new ProductStorageContract(DaisiesDbContext);
_productStorageContract = new ProductStorageContract(DaisiesDbContext, StringLocalizerMockCreator.GetStringLocalizerMockObject());
}
[TearDown]
@@ -39,6 +40,14 @@ internal class ProductStorageContractTest : BaseStorageContractTest
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(x => x.Id == product.Id), product);
}
[Test]
public async Task Try_GetListAsync_WhenNoRecords_Test()
{
var list = await
_productStorageContract.GetListAsync(CancellationToken.None);
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
@@ -90,16 +99,17 @@ internal class ProductStorageContractTest : BaseStorageContractTest
var supplierId2 = Guid.NewGuid().ToString();
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId1, "name 1", isDeleted: true);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId1, "name 2", isDeleted: false);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId2, "name 3", isDeleted: false);
var list = _productStorageContract.GetList(onlyActive: false);
var list = _productStorageContract.GetList(SupplierId: supplierId1, onlyActive: false);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.SupplierId == supplierId1));
});
}
[Test]
public void Try_GetList_BySupplierOnlyActual_Test()
{
@@ -107,12 +117,14 @@ internal class ProductStorageContractTest : BaseStorageContractTest
var supplierId2 = Guid.NewGuid().ToString();
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId1, "name 1", isDeleted: true);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId1, "name 2", isDeleted: false);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId2, "name 3", isDeleted: false);
var list = _productStorageContract.GetList(onlyActive: true);
var list = _productStorageContract.GetList(SupplierId: supplierId1, onlyActive: true);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(1));
Assert.That(list.All(x => x.SupplierId == supplierId1 && !x.IsDeleted));
});
}
@@ -184,7 +196,6 @@ internal class ProductStorageContractTest : BaseStorageContractTest
Assert.That(() => _productStorageContract.GetElementByName("name"), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenRecordHasDeleted_Test()
{
@@ -265,7 +276,6 @@ internal class ProductStorageContractTest : BaseStorageContractTest
Assert.That(() => _productStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString(), supplierId)), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
{
@@ -353,13 +363,13 @@ internal class ProductStorageContractTest : BaseStorageContractTest
return productHistory;
}
private static void AssertElement(ProductDataModel? actual, Product expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.SupplierId, Is.EqualTo(expected.SupplierId));
Assert.That(actual.ProductName, Is.EqualTo(expected.ProductName));
Assert.That(actual.ProductType, Is.EqualTo(expected.ProductType));
Assert.That(actual.Price, Is.EqualTo(expected.Price));
@@ -367,6 +377,17 @@ internal class ProductStorageContractTest : BaseStorageContractTest
});
}
private static void AssertElement(ProductHistoryDataModel? actual, ProductHistory expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.ProductId, Is.EqualTo(expected.Id));
Assert.That(actual.ProductName, Is.EqualTo(expected.Product.ProductName));
Assert.That(actual.OldPrice, Is.EqualTo(expected.OldPrice));
});
}
private static ProductDataModel CreateModel(string id, string supplierId, string productName = "test", ProductType productType = ProductType.Composition, double price = 1, bool isDeleted = false)
{
return new ProductDataModel(
@@ -390,6 +411,7 @@ internal class ProductStorageContractTest : BaseStorageContractTest
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.SupplierId, Is.EqualTo(expected.SupplierId));
Assert.That(actual.ProductName, Is.EqualTo(expected.ProductName));
Assert.That(actual.ProductType, Is.EqualTo(expected.ProductType));
Assert.That(actual.Price, Is.EqualTo(expected.Price));

View File

@@ -4,396 +4,326 @@ using DaisiesContracts.Exceptions;
using DaisiesDatabase.Implementations;
using DaisiesDatabase.Models;
using DaisiesContracts.Enum;
using DaisiesContracts.Infrastructure.BuyerConfigurations;
using DaisiesTests.Infrastructure;
namespace DaisiesTests.StoragesContracts;
[TestFixture]
internal class SaleStorageContractTests : BaseStorageContractTest
{
private ProductStorageContract _productStorageContract;
private SaleStorageContract _saleStorageContract;
private Buyer _buyer;
private Worker _worker;
private Product _product;
[SetUp]
public void SetUp()
{
_productStorageContract = new ProductStorageContract(DaisiesDbContext);
_saleStorageContract = new SaleStorageContract(DaisiesDbContext, StringLocalizerMockCreator.GetStringLocalizerMockObject());
_buyer = InsertBuyerToDatabaseAndReturn();
_worker = InsertWorkerToDatabaseAndReturn();
_product = InsertProductToDatabaseAndReturn();
}
[TearDown]
public void TearDown()
{
DaisiesDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Sales\" CASCADE;");
DaisiesDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Buyers\" CASCADE;");
DaisiesDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Workers\" CASCADE;");
DaisiesDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Products\" CASCADE;");
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var supplierId = Guid.NewGuid().ToString();
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId, "name 1");
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId, "name 2");
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId, "name 3");
var list = _productStorageContract.GetList();
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 5)]);
InsertSaleToDatabaseAndReturn(_worker.Id, null, products: [(_product.Id, 10)]);
var list = _saleStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(x => x.Id == product.Id), product);
AssertElement(list.First(x => x.Id == sale.Id), sale);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
public async Task Try_GetListAsync_ByPeriod_Test()
{
var list = _productStorageContract.GetList();
DaisiesDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), products: [(_product.Id, 1, 1.2)]);
DaisiesDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1, 1.2)]);
DaisiesDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1, 1.2)]);
DaisiesDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(3), products: [(_product.Id, 1, 1.2)]);
var list = await _saleStorageContract.GetListAsync(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1), CancellationToken.None);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
}
[Test]
public async Task Try_GetListAsync_WhenNoRecords_Test()
{
var list = await _saleStorageContract.GetListAsync(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1), CancellationToken.None);
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_OnlyActual_Test()
public void Try_GetList_WhenNoRecords_Test()
{
var supplierId = Guid.NewGuid().ToString();
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId, "name 1", isDeleted: true);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId, "name 2", isDeleted: false);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId, "name 3", isDeleted: false);
var list = _productStorageContract.GetList(onlyActive: true);
var list = _saleStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(!list.Any(x => x.IsDeleted));
});
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_IncludeNoActual_Test()
public void Try_GetList_ByPeriod_Test()
{
var supplierId = Guid.NewGuid().ToString();
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId, "name 1", isDeleted: true);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId, "name 2", isDeleted: true);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId, "name 3", isDeleted: false);
var list = _productStorageContract.GetList(onlyActive: false);
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(3), products: [(_product.Id, 1)]);
var list = _saleStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1));
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(3));
Assert.That(list.Count(x => x.IsDeleted), Is.EqualTo(2));
Assert.That(list.Count(x => !x.IsDeleted), Is.EqualTo(1));
});
Assert.That(list, Has.Count.EqualTo(2));
}
[Test]
public void Try_GetList_BySupplier_Test()
public void Try_GetList_ByWorkerId_Test()
{
var supplierId1 = Guid.NewGuid().ToString();
var supplierId2 = Guid.NewGuid().ToString();
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId1, "name 1", isDeleted: true);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId1, "name 2", isDeleted: false);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId2, "name 3", isDeleted: false);
var list = _productStorageContract.GetList(SupplierId: supplierId1, onlyActive: false);
var worker = InsertWorkerToDatabaseAndReturn("Other worker");
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(worker.Id, null, products: [(_product.Id, 1)]);
var list = _saleStorageContract.GetList(workerId: _worker.Id);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.SupplierId == supplierId1));
});
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.WorkerId == _worker.Id));
}
[Test]
public void Try_GetList_BySupplierOnlyActual_Test()
public void Try_GetList_ByBuyerId_Test()
{
var supplierId1 = Guid.NewGuid().ToString();
var supplierId2 = Guid.NewGuid().ToString();
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId1, "name 1", isDeleted: true);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId1, "name 2", isDeleted: false);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId2, "name 3", isDeleted: false);
var list = _productStorageContract.GetList(SupplierId: supplierId1, onlyActive: true);
var buyer = InsertBuyerToDatabaseAndReturn("Other fio", DateTime.UtcNow.AddYears(-20), "+8-888-888- 88 - 88");
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, buyer.Id, products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, null, products: [(_product.Id, 1)]);
var list = _saleStorageContract.GetList(buyerId: _buyer.Id);
Assert.That(list, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(list, Has.Count.EqualTo(1));
Assert.That(list.All(x => x.SupplierId == supplierId1 && !x.IsDeleted));
});
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(list.All(x => x.BuyerId == _buyer.Id));
}
[Test]
public void Try_GetHistoryByProductId_WhenHaveRecords_Test()
public void Try_GetList_ByProductId_Test()
{
var supplierId = Guid.NewGuid().ToString();
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId, "name 1");
InsertProductHistoryToDatabaseAndReturn(product.Id, 20, DateTime.UtcNow.AddDays(-1));
InsertProductHistoryToDatabaseAndReturn(product.Id, 30, DateTime.UtcNow.AddMinutes(-10));
InsertProductHistoryToDatabaseAndReturn(product.Id, 40, DateTime.UtcNow.AddDays(1));
var list = _productStorageContract.GetHistoryByProductId(product.Id);
var product = InsertProductToDatabaseAndReturn("Other name");
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 5)]);
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1), (product.Id, 4)]);
InsertSaleToDatabaseAndReturn(_worker.Id, null, products: [(product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, null, products: [(product.Id, 1), (_product.Id, 1)]);
var list = _saleStorageContract.GetList(productId: _product.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
Assert.That(list.All(x => x.Products.Any(y => y.ProductId == _product.Id)));
}
[Test]
public void Try_GetHistoryByProductId_WhenNoRecords_Test()
public void Try_GetList_ByAllParameters_Test()
{
var supplierId = Guid.NewGuid().ToString();
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId, "name 1");
InsertProductHistoryToDatabaseAndReturn(product.Id, 20, DateTime.UtcNow.AddDays(-1));
InsertProductHistoryToDatabaseAndReturn(product.Id, 30, DateTime.UtcNow.AddMinutes(-10));
InsertProductHistoryToDatabaseAndReturn(product.Id, 40, DateTime.UtcNow.AddDays(1));
var list = _productStorageContract.GetHistoryByProductId(Guid.NewGuid().ToString());
var worker = InsertWorkerToDatabaseAndReturn("Other worker");
var buyer = InsertBuyerToDatabaseAndReturn("Other fio", DateTime.UtcNow.AddYears(-20), "+8-888-888- 88 - 88");
var product = InsertProductToDatabaseAndReturn("Other name");
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(worker.Id, null, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, buyer.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1)]);
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(product.Id, 1)]);
InsertSaleToDatabaseAndReturn(worker.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1)]);
var list = _saleStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1), workerId: _worker.Id, buyerId: _buyer.Id, productId: product.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
Assert.That(list, Has.Count.EqualTo(1));
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var supplierId = Guid.NewGuid().ToString();
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId);
AssertElement(_productStorageContract.GetElementById(product.Id), product);
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1)]);
AssertElement(_saleStorageContract.GetElementById(sale.Id), sale);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
var supplierId = Guid.NewGuid().ToString();
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId);
Assert.That(() => _productStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1)]);
Assert.That(() => _saleStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementById_WhenRecordHasDeleted_Test()
public void Try_GetElementById_WhenRecordHasCanceled_Test()
{
var supplierId = Guid.NewGuid().ToString();
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId, isDeleted: true);
Assert.That(() => _productStorageContract.GetElementById(product.Id), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenHaveRecord_Test()
{
var supplierId = Guid.NewGuid().ToString();
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId);
AssertElement(_productStorageContract.GetElementByName(product.ProductName), product);
}
[Test]
public void Try_GetElementByName_WhenNoRecord_Test()
{
var supplierId = Guid.NewGuid().ToString();
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId);
Assert.That(() => _productStorageContract.GetElementByName("name"), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenRecordHasDeleted_Test()
{
var supplierId = Guid.NewGuid().ToString();
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId, isDeleted: true);
Assert.That(() => _productStorageContract.GetElementByName(product.ProductName), Is.Null);
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1)], isCancel: true);
AssertElement(_saleStorageContract.GetElementById(sale.Id), sale);
}
[Test]
public void Try_AddElement_Test()
{
var supplierId = Guid.NewGuid().ToString();
var product = CreateModel(Guid.NewGuid().ToString(), supplierId, isDeleted: false);
_productStorageContract.AddElement(product);
AssertElement(GetProductFromDatabaseById(product.Id), product);
}
[Test]
public void Try_AddElement_WhenIsDeletedIsTrue_Test()
{
var supplierId = Guid.NewGuid().ToString();
var product = CreateModel(Guid.NewGuid().ToString(), supplierId, isDeleted: true);
Assert.That(() => _productStorageContract.AddElement(product), Throws.Nothing);
AssertElement(GetProductFromDatabaseById(product.Id), CreateModel(product.Id, supplierId, isDeleted: false));
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var supplierId = Guid.NewGuid().ToString();
var product = CreateModel(Guid.NewGuid().ToString(), supplierId);
InsertProductToDatabaseAndReturn(product.Id, supplierId, productName: "name unique");
Assert.That(() => _productStorageContract.AddElement(product), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
{
var supplierId = Guid.NewGuid().ToString();
var product = CreateModel(Guid.NewGuid().ToString(), supplierId, "name unique", isDeleted: false);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId, productName: product.ProductName, isDeleted: false);
Assert.That(() => _productStorageContract.AddElement(product), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameNameButOneWasDeleted_Test()
{
var supplierId = Guid.NewGuid().ToString();
var product = CreateModel(Guid.NewGuid().ToString(), supplierId, "name unique", isDeleted: false);
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId, productName: product.ProductName, isDeleted: true);
Assert.That(() => _productStorageContract.AddElement(product), Throws.Nothing);
}
[Test]
public void Try_UpdElement_Test()
{
var supplierId = Guid.NewGuid().ToString();
var product = CreateModel(Guid.NewGuid().ToString(), supplierId, isDeleted: false);
InsertProductToDatabaseAndReturn(product.Id, supplierId, isDeleted: false);
_productStorageContract.UpdElement(product);
AssertElement(GetProductFromDatabaseById(product.Id), product);
}
[Test]
public void Try_UpdElement_WhenIsDeletedIsTrue_Test()
{
var supplierId = Guid.NewGuid().ToString();
var product = CreateModel(Guid.NewGuid().ToString(), supplierId, isDeleted: true);
InsertProductToDatabaseAndReturn(product.Id, supplierId, isDeleted: false);
_productStorageContract.UpdElement(product);
AssertElement(GetProductFromDatabaseById(product.Id), CreateModel(product.Id, supplierId, isDeleted: false));
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
var supplierId = Guid.NewGuid().ToString();
Assert.That(() => _productStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString(), supplierId)), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
{
var supplierId = Guid.NewGuid().ToString();
var product = CreateModel(Guid.NewGuid().ToString(), supplierId, "name unique", isDeleted: false);
InsertProductToDatabaseAndReturn(product.Id, supplierId, productName: "name");
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId, productName: product.ProductName);
Assert.That(() => _productStorageContract.UpdElement(product), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_WhenHaveRecordWithSameNameButOneWasDeleted_Test()
{
var supplierId = Guid.NewGuid().ToString();
var product = CreateModel(Guid.NewGuid().ToString(), supplierId, "name unique", isDeleted: false);
InsertProductToDatabaseAndReturn(product.Id, supplierId, productName: "name");
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId, productName: product.ProductName, isDeleted: true);
Assert.That(() => _productStorageContract.UpdElement(product), Throws.Nothing);
}
[Test]
public void Try_UpdElement_WhenRecordWasDeleted_Test()
{
var supplierId = Guid.NewGuid().ToString();
var product = CreateModel(Guid.NewGuid().ToString(), supplierId);
InsertProductToDatabaseAndReturn(product.Id, supplierId, isDeleted: true);
Assert.That(() => _productStorageContract.UpdElement(product), Throws.TypeOf<ElementNotFoundException>());
var sale = CreateModel(Guid.NewGuid().ToString(), _worker.Id, _buyer.Id, 1, false, [_product.Id]);
_saleStorageContract.AddElement(sale);
AssertElement(GetSaleFromDatabaseById(sale.Id), sale);
}
[Test]
public void Try_DelElement_Test()
{
var supplierId = Guid.NewGuid().ToString();
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId, isDeleted: false);
_productStorageContract.DelElement(product.Id);
var element = GetProductFromDatabaseById(product.Id);
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1)], isCancel: false);
_saleStorageContract.DelElement(sale.Id);
var element = GetSaleFromDatabaseById(sale.Id);
Assert.Multiple(() =>
{
Assert.That(element, Is.Not.Null);
Assert.That(element!.IsDeleted);
Assert.That(element!.IsCancel);
});
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _productStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
Assert.That(() => _saleStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_WhenRecordWasDeleted_Test()
public void Try_DelElement_WhenRecordWasCanceled_Test()
{
var supplierId = Guid.NewGuid().ToString();
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), supplierId, isDeleted: true);
Assert.That(() => _productStorageContract.DelElement(product.Id), Throws.TypeOf<ElementNotFoundException>());
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, products: [(_product.Id, 1)], isCancel: true);
Assert.That(() => _saleStorageContract.DelElement(sale.Id), Throws.TypeOf<ElementDeletedException>());
}
private Product InsertProductToDatabaseAndReturn(string id, string supplierId, string productName = "test", ProductType productType = ProductType.Composition, double price = 1, bool isDeleted = false)
private Buyer InsertBuyerToDatabaseAndReturn(string fio = "test", DateTime? birthDate = null, string
phoneNumber = "+7-777-777-77-77", BuyerConfiguration? configuration = null)
{
var product = new Product
var buyer = new Buyer()
{
Id = id,
SupplierId = supplierId,
ProductName = productName,
ProductType = productType,
Price = price,
IsDeleted = isDeleted
Id = Guid.NewGuid().ToString(),
FIO = fio,
PhoneNumber = phoneNumber,
DiscountSize = 10,
Configuration = configuration ?? new BuyerConfiguration()
};
DaisiesDbContext.Buyers.Add(buyer);
DaisiesDbContext.SaveChanges();
return buyer;
}
private Worker InsertWorkerToDatabaseAndReturn(string fio = "test")
{
var worker = new Worker() { Id = Guid.NewGuid().ToString(), FIO = fio, PostId = Guid.NewGuid().ToString() };
DaisiesDbContext.Workers.Add(worker);
DaisiesDbContext.SaveChanges();
return worker;
}
private Product InsertProductToDatabaseAndReturn(string productName = "test", string? supplierId = null, double price = 1, bool isDeleted = false)
{
var product = new Product() { Id = Guid.NewGuid().ToString(), SupplierId = Guid.NewGuid().ToString(), ProductName = productName, Price = price, IsDeleted = isDeleted }; ;
DaisiesDbContext.Products.Add(product);
DaisiesDbContext.SaveChanges();
return product;
}
private ProductHistory InsertProductHistoryToDatabaseAndReturn(string productId, double price, DateTime changeDate)
private Sale InsertSaleToDatabaseAndReturn(string workerId, string? buyerId, DateTime? saleDate = null, double sum = 1, double discount = 0, bool isCancel = false, List<(string, int)>? products = null)
{
var productHistory = new ProductHistory
var sale = new Sale()
{
Id = Guid.NewGuid().ToString(),
ProductId = productId,
OldPrice = price,
ChangeDate = changeDate
WorkerId = workerId,
BuyerId = buyerId,
SaleDate = saleDate ?? DateTime.UtcNow,
Sum = sum,
IsCancel = isCancel,
SaleProducts = []
};
DaisiesDbContext.ProductHistories.Add(productHistory);
if (products is not null)
{
foreach (var elem in products)
{
sale.SaleProducts.Add(new SaleProduct { ProductId = elem.Item1, SaleId = sale.Id, Count = elem.Item2 });
}
}
DaisiesDbContext.Sales.Add(sale);
DaisiesDbContext.SaveChanges();
return productHistory;
return sale;
}
private static void AssertElement(ProductDataModel? actual, Product expected)
private static void AssertElement(SaleDataModel? actual, Sale expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.SupplierId, Is.EqualTo(expected.SupplierId));
Assert.That(actual.ProductName, Is.EqualTo(expected.ProductName));
Assert.That(actual.ProductType, Is.EqualTo(expected.ProductType));
Assert.That(actual.Price, Is.EqualTo(expected.Price));
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
Assert.That(actual.BuyerId, Is.EqualTo(expected.BuyerId));
Assert.That(actual.IsCancel, Is.EqualTo(expected.IsCancel));
});
if (expected.SaleProducts is not null)
{
Assert.That(actual.Products, Is.Not.Null);
Assert.That(actual.Products, Has.Count.EqualTo(expected.SaleProducts.Count));
for (int i = 0; i < actual.Products.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.Products[i].ProductId, Is.EqualTo(expected.SaleProducts[i].ProductId));
Assert.That(actual.Products[i].Count, Is.EqualTo(expected.SaleProducts[i].Count));
});
}
}
else
{
Assert.That(actual.Products, Is.Null);
}
}
private static ProductDataModel CreateModel(string id, string supplierId, string productName = "test", ProductType productType = ProductType.Composition, double price = 1, bool isDeleted = false)
private static SaleDataModel CreateModel(string id, string workerId, string? buyerId, double sum, bool isCancel, List<string> productIds)
{
return new ProductDataModel(
id: id,
productName: productName,
productType: productType,
SupplierId: supplierId,
price: price,
isDeleted: isDeleted
);
var products = productIds.Select(x => new SaleProductDataModel(id, x, 1)).ToList();
return new(id, workerId, buyerId, sum, isCancel, products);
}
private Product? GetProductFromDatabaseById(string id)
{
return DaisiesDbContext.Products.FirstOrDefault(x => x.Id == id);
}
private Sale? GetSaleFromDatabaseById(string id) => DaisiesDbContext.Sales.Include(x => x.SaleProducts).FirstOrDefault(x => x.Id == id);
private static void AssertElement(Product? actual, ProductDataModel expected)
private static void AssertElement(Sale? actual, SaleDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.SupplierId, Is.EqualTo(expected.SupplierId));
Assert.That(actual.ProductName, Is.EqualTo(expected.ProductName));
Assert.That(actual.ProductType, Is.EqualTo(expected.ProductType));
Assert.That(actual.Price, Is.EqualTo(expected.Price));
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
Assert.That(actual.BuyerId, Is.EqualTo(expected.BuyerId));
Assert.That(actual.IsCancel, Is.EqualTo(expected.IsCancel));
});
if (expected.Products is not null)
{
Assert.That(actual.SaleProducts, Is.Not.Null);
Assert.That(actual.SaleProducts, Has.Count.EqualTo(expected.Products.Count));
for (int i = 0; i < actual.SaleProducts.Count; ++i)
{
Assert.Multiple(() =>
{
Assert.That(actual.SaleProducts[i].ProductId, Is.EqualTo(expected.Products[i].ProductId));
Assert.That(actual.SaleProducts[i].Count, Is.EqualTo(expected.Products[i].Count));
});
}
}
else
{
Assert.That(actual.SaleProducts, Is.Null);
}
}
}

View File

@@ -15,13 +15,13 @@ internal class WorkerStorageContractTest : BaseStorageContractTest
[SetUp]
public void SetUp()
{
_workerStorageContract = new WorkerStorageContract(DaisiesDbContext);
_workerStorageContract = new WorkerStorageContract(DaisiesDbContext, StringLocalizerMockCreator.GetStringLocalizerMockObject());
}
[TearDown]
public void TearDown()
{
DaisiesDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Workers\" CASCADE;");
DaisiesDbContext.RemoveWorkersFromDatabase();
}
[Test]
@@ -48,9 +48,9 @@ internal class WorkerStorageContractTest : BaseStorageContractTest
public void Try_GetList_ByPostId_Test()
{
var postId = Guid.NewGuid().ToString();
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", postId);
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", postId);
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3");
DaisiesDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: postId);
DaisiesDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: postId);
DaisiesDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3");
var list = _workerStorageContract.GetList(postId: postId);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
@@ -60,10 +60,10 @@ internal class WorkerStorageContractTest : BaseStorageContractTest
[Test]
public void Try_GetList_ByBirthDate_Test()
{
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", birthDate: DateTime.UtcNow.AddYears(-25));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", birthDate: DateTime.UtcNow.AddYears(-21));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", birthDate: DateTime.UtcNow.AddYears(-20));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", birthDate: DateTime.UtcNow.AddYears(-19));
DaisiesDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", birthDate: DateTime.UtcNow.AddYears(-25));
DaisiesDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", birthDate: DateTime.UtcNow.AddYears(-21));
DaisiesDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", birthDate: DateTime.UtcNow.AddYears(-20));
DaisiesDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", birthDate: DateTime.UtcNow.AddYears(-19));
var list = _workerStorageContract.GetList(fromBirthDate: DateTime.UtcNow.AddYears(-21).AddMinutes(-1), toBirthDate: DateTime.UtcNow.AddYears(-20).AddMinutes(1));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
@@ -72,10 +72,10 @@ internal class WorkerStorageContractTest : BaseStorageContractTest
[Test]
public void Try_GetList_ByEmploymentDate_Test()
{
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", employmentDate: DateTime.UtcNow.AddDays(-2));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", employmentDate: DateTime.UtcNow.AddDays(-1));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", employmentDate: DateTime.UtcNow.AddDays(1));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", employmentDate: DateTime.UtcNow.AddDays(2));
DaisiesDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", employmentDate: DateTime.UtcNow.AddDays(-2));
DaisiesDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", employmentDate: DateTime.UtcNow.AddDays(-1));
DaisiesDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", employmentDate: DateTime.UtcNow.AddDays(1));
DaisiesDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", employmentDate: DateTime.UtcNow.AddDays(2));
var list = _workerStorageContract.GetList(fromEmploymentDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-1), toEmploymentDate: DateTime.UtcNow.AddDays(1).AddMinutes(1));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
@@ -85,10 +85,10 @@ internal class WorkerStorageContractTest : BaseStorageContractTest
public void Try_GetList_ByAllParameters_Test()
{
var postId = Guid.NewGuid().ToString();
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", postId, birthDate: DateTime.UtcNow.AddYears(-25), employmentDate: DateTime.UtcNow.AddDays(-2));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", postId, birthDate: DateTime.UtcNow.AddYears(-22), employmentDate: DateTime.UtcNow.AddDays(-1));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", postId, birthDate: DateTime.UtcNow.AddYears(-21), employmentDate: DateTime.UtcNow.AddDays(-1));
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", birthDate: DateTime.UtcNow.AddYears(-20), employmentDate: DateTime.UtcNow.AddDays(1));
DaisiesDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: postId, birthDate: DateTime.UtcNow.AddYears(-25), employmentDate: DateTime.UtcNow.AddDays(-2));
DaisiesDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: postId, birthDate: DateTime.UtcNow.AddYears(-22), employmentDate: DateTime.UtcNow.AddDays(-1));
DaisiesDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", postId: postId, birthDate: DateTime.UtcNow.AddYears(-21), employmentDate: DateTime.UtcNow.AddDays(-1));
DaisiesDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", birthDate: DateTime.UtcNow.AddYears(-20), employmentDate: DateTime.UtcNow.AddDays(1));
var list = _workerStorageContract.GetList(postId: postId, fromBirthDate: DateTime.UtcNow.AddYears(-21).AddMinutes(-1), toBirthDate: DateTime.UtcNow.AddYears(-20).AddMinutes(1), fromEmploymentDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-1), toEmploymentDate: DateTime.UtcNow.AddDays(1).AddMinutes(1));
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(1));
@@ -97,7 +97,7 @@ internal class WorkerStorageContractTest : BaseStorageContractTest
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
var worker = DaisiesDbContext.InsertWorkerToDatabaseAndReturn();
AssertElement(_workerStorageContract.GetElementById(worker.Id), worker);
}
@@ -110,7 +110,7 @@ internal class WorkerStorageContractTest : BaseStorageContractTest
[Test]
public void Try_GetElementByFIO_WhenHaveRecord_Test()
{
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
var worker = DaisiesDbContext.InsertWorkerToDatabaseAndReturn();
AssertElement(_workerStorageContract.GetElementByFIO(worker.FIO), worker);
}
@@ -125,14 +125,14 @@ internal class WorkerStorageContractTest : BaseStorageContractTest
{
var worker = CreateModel(Guid.NewGuid().ToString());
_workerStorageContract.AddElement(worker);
AssertElement(GetWorkerFromDatabase(worker.Id), worker);
AssertElement(DaisiesDbContext.GetWorkerFromDatabaseById(worker.Id), worker);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var worker = CreateModel(Guid.NewGuid().ToString());
InsertWorkerToDatabaseAndReturn(worker.Id);
DaisiesDbContext.InsertWorkerToDatabaseAndReturn(worker.Id);
Assert.That(() => _workerStorageContract.AddElement(worker), Throws.TypeOf<ElementExistsException>());
}
@@ -140,9 +140,9 @@ internal class WorkerStorageContractTest : BaseStorageContractTest
public void Try_UpdElement_Test()
{
var worker = CreateModel(Guid.NewGuid().ToString(), "New Fio");
InsertWorkerToDatabaseAndReturn(worker.Id);
DaisiesDbContext.InsertWorkerToDatabaseAndReturn(worker.Id);
_workerStorageContract.UpdElement(worker);
AssertElement(GetWorkerFromDatabase(worker.Id), worker);
AssertElement(DaisiesDbContext.GetWorkerFromDatabaseById(worker.Id), worker);
}
[Test]
@@ -155,16 +155,16 @@ internal class WorkerStorageContractTest : BaseStorageContractTest
public void Try_UpdElement_WhenNoRecordWasDeleted_Test()
{
var worker = CreateModel(Guid.NewGuid().ToString());
InsertWorkerToDatabaseAndReturn(worker.Id, isDeleted: true);
DaisiesDbContext.InsertWorkerToDatabaseAndReturn(worker.Id, isDeleted: true);
Assert.That(() => _workerStorageContract.UpdElement(worker), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_Test()
{
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
var worker = DaisiesDbContext.InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
_workerStorageContract.DelElement(worker.Id);
var element = GetWorkerFromDatabase(worker.Id);
var element = DaisiesDbContext.GetWorkerFromDatabaseById(worker.Id);
Assert.That(element, Is.Not.Null);
Assert.That(element.IsDeleted);
}
@@ -179,18 +179,10 @@ internal class WorkerStorageContractTest : BaseStorageContractTest
public void Try_DelElement_WhenNoRecordWasDeleted_Test()
{
var worker = CreateModel(Guid.NewGuid().ToString());
InsertWorkerToDatabaseAndReturn(worker.Id, isDeleted: true);
DaisiesDbContext.InsertWorkerToDatabaseAndReturn(worker.Id, isDeleted: true);
Assert.That(() => _workerStorageContract.DelElement(worker.Id), Throws.TypeOf<ElementNotFoundException>());
}
private Worker InsertWorkerToDatabaseAndReturn(string id, string fio = "test", string? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false)
{
var worker = new Worker() { Id = id, FIO = fio, PostId = postId ?? Guid.NewGuid().ToString(), BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-20), EmploymentDate = employmentDate ?? DateTime.UtcNow, IsDeleted = isDeleted };
DaisiesDbContext.Workers.Add(worker);
DaisiesDbContext.SaveChanges();
return worker;
}
private static void AssertElement(WorkerDataModel? actual, Worker expected)
{
Assert.That(actual, Is.Not.Null);
@@ -208,8 +200,6 @@ internal class WorkerStorageContractTest : BaseStorageContractTest
private static WorkerDataModel CreateModel(string id, string fio = "fio", string? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false) =>
new(id, fio, postId ?? Guid.NewGuid().ToString(), birthDate ?? DateTime.UtcNow.AddYears(-20), employmentDate ?? DateTime.UtcNow, isDeleted);
private Worker? GetWorkerFromDatabase(string id) => DaisiesDbContext.Workers.FirstOrDefault(x => x.Id == id);
private static void AssertElement(Worker? actual, WorkerDataModel expected)
{
Assert.That(actual, Is.Not.Null);

View File

@@ -117,24 +117,6 @@ internal class ProductControllerTests : BaseWebApiControllerTest
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task GetHistoryByProductId_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var product = DaisiesDbContext.InsertProductToDatabaseAndReturn();
DaisiesDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 20, DateTime.UtcNow.AddDays(-1));
DaisiesDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 30, DateTime.UtcNow.AddDays(-1));
var history = DaisiesDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 40, DateTime.UtcNow.AddDays(1));
//Act
var response = await HttpClient.GetAsync($"/api/products/gethistory?id={product.Id}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<ProductHistoryViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(3));
AssertElement(data[0], history);
}
[Test]
public async Task GetHistoryByProductId_WhenNoRecords_ShouldSuccess_Test()
{

View File

@@ -19,7 +19,7 @@ internal class SaleControllerTests : BaseWebApiControllerTest
[SetUp]
public void SetUp()
{
_buyerId = DaisiesDbContext.InsertBuyerToDatabaseAndReturn(phoneNumber: "8-888-888-88-88").Id;
_buyerId = DaisiesDbContext.InsertBuyerToDatabaseAndReturn().Id;
_workerId = DaisiesDbContext.InsertWorkerToDatabaseAndReturn().Id;
_productId = DaisiesDbContext.InsertProductToDatabaseAndReturn(_workerId).Id;
}
@@ -41,7 +41,7 @@ internal class SaleControllerTests : BaseWebApiControllerTest
DaisiesDbContext.InsertSaleToDatabaseAndReturn(_workerId, products: [(_productId, 10, 1.1)]);
DaisiesDbContext.InsertSaleToDatabaseAndReturn(_workerId, products: [(_productId, 10, 1.1)]);
//Act
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.UtcNow.AddDays(-20):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(20):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
@@ -209,52 +209,22 @@ internal class SaleControllerTests : BaseWebApiControllerTest
[Test]
public async Task GetList_ByProductId_ShouldSuccess_Test()
{
// Arrange
var otherProduct = DaisiesDbContext.InsertProductToDatabaseAndReturn(_workerId, productName: "Other product");
// Создаем тестовые данные
var sale1 = DaisiesDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId,
products: [(_productId, 5, 1.1)]); // Должна войти
var sale2 = DaisiesDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId,
products: [(_productId, 1, 1.1), (otherProduct.Id, 4, 1.1)]); // Должна войти
var sale3 = DaisiesDbContext.InsertSaleToDatabaseAndReturn(_workerId, null,
products: [(otherProduct.Id, 1, 1.1)]); // Не должна войти
var sale4 = DaisiesDbContext.InsertSaleToDatabaseAndReturn(_workerId, null,
products: [(otherProduct.Id, 1, 1.1), (_productId, 1, 1.1)]); // Должна войти
// Act
var response = await HttpClient.GetAsync(
$"/api/sales/getproductrecords?id={_productId}" +
$"&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}" +
$"&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
// Assert
//Arrange
var product = DaisiesDbContext.InsertProductToDatabaseAndReturn(_workerId, productName: "Other name");
DaisiesDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, products: [(_productId, 5, 1.1)]);
DaisiesDbContext.InsertSaleToDatabaseAndReturn(_workerId, _buyerId, products: [(_productId, 1, 1.1), (product.Id, 4, 1.1)]);
DaisiesDbContext.InsertSaleToDatabaseAndReturn(_workerId, null, products: [(product.Id, 1, 1.1)]);
var x = DaisiesDbContext.InsertSaleToDatabaseAndReturn(_workerId, null, products: [(product.Id, 1, 1.1), (_productId, 1, 1.1)]);
//Act
var response = await HttpClient.GetAsync($"/api/sales/getproductrecords?id={_productId}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
Assert.That(data, Is.Not.Null);
// Проверяем, что вернулись только нужные продажи
var expectedSaleIds = new[] { sale1.Id, sale2.Id, sale4.Id };
var returnedSaleIds = data.Select(x => x.Id).ToList();
Assert.Multiple(() =>
{
// Проверка количества
Assert.That(data.Count, Is.EqualTo(3),
$"Ожидалось 3 продажи, но получено {data.Count}");
// Проверка конкретных ID
Assert.That(returnedSaleIds, Is.EquivalentTo(expectedSaleIds),
$"Ожидались продажи с ID: {string.Join(", ", expectedSaleIds)}, " +
$"но получены: {string.Join(", ", returnedSaleIds)}");
// Дополнительная проверка продуктов
Assert.That(data.All(x => x.Products?.Any(p => p.ProductId == _productId) ?? false),
"Не все возвращённые продажи содержат указанный продукт");
Assert.That(data, Has.Count.EqualTo(3));
Assert.That(data.All(x => x.Products.Any(y => y.ProductId == _productId)));
});
}
@@ -365,11 +335,11 @@ internal class SaleControllerTests : BaseWebApiControllerTest
{
//Arrange
var saleId = Guid.NewGuid().ToString();
var saleModelWithIdIncorrect = new SaleBindingModel { Id = "Id", WorkerId = _workerId, BuyerId = _buyerId, DiscountType = 1, Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = _productId, Count = 10, Price = 1.1 }] };
var saleModelWithWorkerIdIncorrect = new SaleBindingModel { Id = saleId, WorkerId = "Id", BuyerId = _buyerId, DiscountType = 1, Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = _productId, Count = 10, Price = 1.1 }] };
var saleModelWithBuyerIdIncorrect = new SaleBindingModel { Id = saleId, WorkerId = _workerId, BuyerId = "Id", DiscountType = 1, Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = _productId, Count = 10, Price = 1.1 }] };
var saleModelWithIdIncorrect = new SaleBindingModel { Id = "Id", WorkerId = _workerId, BuyerId = _buyerId, DiscountType = 1, Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = _productId, Count = 10 }] };
var saleModelWithWorkerIdIncorrect = new SaleBindingModel { Id = saleId, WorkerId = "Id", BuyerId = _buyerId, DiscountType = 1, Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = _productId, Count = 10 }] };
var saleModelWithBuyerIdIncorrect = new SaleBindingModel { Id = saleId, WorkerId = _workerId, BuyerId = "Id", DiscountType = 1, Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = _productId, Count = 10 }] };
var saleModelWithProductsIncorrect = new SaleBindingModel { Id = saleId, WorkerId = _workerId, BuyerId = _buyerId, DiscountType = 1, Products = null };
var saleModelWithProductIdIncorrect = new SaleBindingModel { Id = saleId, WorkerId = _workerId, BuyerId = _buyerId, DiscountType = 1, Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = "Id", Count = 10, Price = 1.1 }] };
var saleModelWithProductIdIncorrect = new SaleBindingModel { Id = saleId, WorkerId = _workerId, BuyerId = _buyerId, DiscountType = 1, Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = "Id", Count = 10 }] };
//Act
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithIdIncorrect));
var responseWithWorkerIdIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithWorkerIdIncorrect));
@@ -471,7 +441,7 @@ internal class SaleControllerTests : BaseWebApiControllerTest
{
Assert.Multiple(() =>
{
Assert.That(actual.Products[i].ProductName, Is.EqualTo(expected.SaleProducts[i].Product!.ProductName));
Assert.That(actual.Products[i].ProductId, Is.EqualTo(expected.SaleProducts[i].ProductId));
Assert.That(actual.Products[i].Count, Is.EqualTo(expected.SaleProducts[i].Count));
});
}
@@ -490,7 +460,7 @@ internal class SaleControllerTests : BaseWebApiControllerTest
Id = saleId,
WorkerId = workerId,
BuyerId = buyerId,
Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = productId, Count = count, Price = price }]
Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = productId, Count = count }]
};
}

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