2 Commits
lab_6 ... lab_8

Author SHA1 Message Date
a92013fe91 Лабораторная 8 2025-05-27 20:40:20 +04:00
23db4d2f8d Лабораторная 7 2025-05-27 16:20:42 +04:00
119 changed files with 5763 additions and 2995 deletions

View File

@@ -1,49 +1,38 @@
using AutoMapper;
using DaisiesContracts.AdapterContracts;
using DaisiesContracts.AdapterContracts.OperationResponses;
using DaisiesContracts.AdapterContracts;
using DaisiesContracts.BindingModels;
using DaisiesContracts.BuisnessLogicContracts;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.ViewModels;
using System.Text.Json;
using Microsoft.Extensions.Localization;
using DaisiesContracts.Resources;
using DaisiesContracts.Mapper;
using DaisiesContracts.BuisnessLogicContracts;
namespace DaisiesWebApi.Adapters;
public class BuyerAdapter : IBuyerAdapter
internal class BuyerAdapter(IBuyerBuisnessLogicContract buyerBusinessLogicContract,
ILogger<BuyerAdapter> logger, IStringLocalizer<Messages> localizer) : IBuyerAdapter
{
private readonly IBuyerBuisnessLogicContract _buyerBusinessLogicContract;
private readonly ILogger _logger;
private readonly Mapper _mapper;
private readonly IBuyerBuisnessLogicContract _buyerBusinessLogicContract = buyerBusinessLogicContract;
private readonly ILogger _logger = logger;
private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNameCaseInsensitive = true };
public BuyerAdapter(IBuyerBuisnessLogicContract buyerBusinessLogicContract,
ILogger<BuyerAdapter> logger)
{
_buyerBusinessLogicContract = buyerBusinessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<BuyerBindingModel, BuyerDataModel>();
cfg.CreateMap<BuyerDataModel, BuyerViewModel>()
.ForMember(x => x.Configuration, x => x.MapFrom(src => JsonSerializer.Serialize(src.ConfigurationModel, JsonSerializerOptions)));
});
_mapper = new Mapper(config);
}
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 =>
CustomMapper.MapObject<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)
{
@@ -56,23 +45,23 @@ public class BuyerAdapter : IBuyerAdapter
try
{
return
BuyerOperationResponse.OK(_mapper.Map<BuyerViewModel>(_buyerBusinessLogicContract
BuyerOperationResponse.OK(CustomMapper.MapObject<BuyerViewModel>(_buyerBusinessLogicContract
.GetBuyerByData(data)));
}
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)
{
@@ -84,18 +73,18 @@ public class BuyerAdapter : IBuyerAdapter
{
try
{
_buyerBusinessLogicContract.InsertBuyer(_mapper.Map<BuyerDataModel>(buyerModel));
_buyerBusinessLogicContract.InsertBuyer(CustomMapper.MapObject<BuyerDataModel>(buyerModel));
return BuyerOperationResponse.NoContent();
}
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 +94,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)
{
@@ -117,23 +106,23 @@ public class BuyerAdapter : IBuyerAdapter
{
try
{
_buyerBusinessLogicContract.UpdateBuyer(_mapper.Map<BuyerDataModel>(buyerModel));
_buyerBusinessLogicContract.UpdateBuyer(CustomMapper.MapObject<BuyerDataModel>(buyerModel));
return BuyerOperationResponse.NoContent();
}
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 +132,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 +150,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)
{
@@ -185,3 +174,4 @@ public class BuyerAdapter : IBuyerAdapter
}
}
}

View File

@@ -1,61 +1,53 @@
using AutoMapper;
using DaisiesBuisnessLogic.Implementations;
using DaisiesContracts.AdapterContracts;
using DaisiesContracts.AdapterContracts.OperationResponses;
using DaisiesContracts.AdapterContracts;
using DaisiesContracts.BindingModels;
using DaisiesContracts.BuisnessLogicContracts;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.Mapper;
using DaisiesContracts.Resources;
using DaisiesContracts.ViewModels;
using DaisiesContracts.BuisnessLogicContracts;
using Microsoft.Extensions.Localization;
namespace DaisiesWebApi.Adapters;
public class ClientDiscountAdapter : IClientDiscountAdapter
internal class ClientDiscountAdapter(IClientDiscountBuisnessLogicContract clientDiscountBusinessLogicContrac, ILogger<ClientDiscountAdapter> logger, IStringLocalizer<Messages> localizer) : IClientDiscountAdapter
{
private readonly IClientDiscountBuisnessLogicContract _clientDiscountBusinessLogicContract;
private readonly IClientDiscountBuisnessLogicContract _clientDiscountBusinessLogicContract = clientDiscountBusinessLogicContrac;
private readonly ILogger _logger;
private readonly Mapper _mapper;
private readonly ILogger _logger = logger;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public ClientDiscountAdapter(IClientDiscountBuisnessLogicContract clientDiscountBusinessLogicContrac, ILogger<ClientDiscountAdapter> logger)
{
_clientDiscountBusinessLogicContract = clientDiscountBusinessLogicContrac;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<ClientDiscountBindingModel, ClientDiscountDataModel>();
cfg.CreateMap<ClientDiscountDataModel, ClientDiscountViewModel>();
});
_mapper = new Mapper(config);
}
public ClientDiscountOperationResponse RegisterClientDiscount(ClientDiscountBindingModel
clientDiscountModel)
{
try
{
_clientDiscountBusinessLogicContract.InsertClientDiscount(_mapper.Map<ClientDiscountDataModel>(clientDiscountModel));
_clientDiscountBusinessLogicContract.InsertClientDiscount(CustomMapper.MapObject<ClientDiscountDataModel>(clientDiscountModel));
return ClientDiscountOperationResponse.NoContent();
}
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)
{
@@ -70,27 +62,27 @@ public class ClientDiscountAdapter : IClientDiscountAdapter
try
{
return
ClientDiscountOperationResponse.OK(_mapper.Map<ClientDiscountViewModel>(_clientDiscountBusinessLogicContract.GetClientDiscountByBuyerId(data)));
ClientDiscountOperationResponse.OK(CustomMapper.MapObject<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)
{
@@ -106,17 +98,12 @@ public class ClientDiscountAdapter : IClientDiscountAdapter
{
return ClientDiscountOperationResponse.OK([..
_clientDiscountBusinessLogicContract.GetAllClientDiscounts().Select(x =>
_mapper.Map<ClientDiscountViewModel>(x))]);
}
catch (NullListException)
{
_logger.LogError("NullListException");
return ClientDiscountOperationResponse.NotFound("The list is not initialized");
CustomMapper.MapObject<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,27 +112,28 @@ _mapper.Map<ClientDiscountViewModel>(x))]);
}
}
public ClientDiscountOperationResponse ChangeClientDiscountInfo(ClientDiscountBindingModel clientDiscountModel)
public ClientDiscountOperationResponse ChangeClientDiscountInfo(ClientDiscountBindingModel
clientDiscountModel)
{
try
{
_clientDiscountBusinessLogicContract.UpdateClientDiscount(_mapper.Map<ClientDiscountDataModel>(clientDiscountModel));
_clientDiscountBusinessLogicContract.UpdateClientDiscount(CustomMapper.MapObject<ClientDiscountDataModel>(clientDiscountModel));
return ClientDiscountOperationResponse.NoContent();
}
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 +143,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 +162,34 @@ _mapper.Map<ClientDiscountViewModel>(x))]);
{
try
{
return ClientDiscountOperationResponse.OK(_mapper.Map<ClientDiscountViewModel>(_clientDiscountBusinessLogicContract.GetClientDiscountByBuyerId(data)));
return
ClientDiscountOperationResponse.OK(CustomMapper.MapObject<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

@@ -1,49 +1,34 @@
using AutoMapper;
using DaisiesContracts.AdapterContracts;
using Microsoft.Extensions.Localization;
using DaisiesContracts.AdapterContracts.OperationResponses;
using DaisiesContracts.AdapterContracts;
using DaisiesContracts.BindingModels;
using DaisiesContracts.BuisnessLogicContracts;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.Mapper;
using DaisiesContracts.Resources;
using DaisiesContracts.ViewModels;
using DaisiesContracts.BuisnessLogicContracts;
namespace DaisiesWebApi.Adapters;
public class PostAdapter : IPostAdapter
internal class PostAdapter(IPostBuisnessLogicContract postBusinessLogicContract, ILogger<PostAdapter> logger, IStringLocalizer<Messages> localizer) : IPostAdapter
{
private readonly IPostBuisnessLogicContract _postBusinessLogicContract;
private readonly IPostBuisnessLogicContract _postBusinessLogicContract = postBusinessLogicContract;
private readonly ILogger _logger = logger;
private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly ILogger _logger;
private readonly Mapper _mapper;
public PostAdapter(IPostBuisnessLogicContract postBusinessLogicContract, ILogger<PostAdapter> logger)
{
_postBusinessLogicContract = postBusinessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<PostBindingModel, PostDataModel>();
cfg.CreateMap<PostDataModel, PostViewModel>();
});
_mapper = new Mapper(config);
}
public PostOperationResponse GetList()
{
try
{
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllPosts().Select(x => _mapper.Map<PostViewModel>(x))]);
}
catch (NullListException)
{
_logger.LogError("NullListException");
return PostOperationResponse.NotFound("The list is not initialized");
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllPosts().Select(x => CustomMapper.MapObject<PostViewModel>(x))]);
}
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)
{
@@ -56,22 +41,22 @@ public class PostAdapter : IPostAdapter
{
try
{
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllDataOfPost(id).Select(x => _mapper.Map<PostViewModel>(x))]);
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllDataOfPost(id).Select(x => CustomMapper.MapObject<PostViewModel>(x))]);
}
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)
{
@@ -84,27 +69,27 @@ public class PostAdapter : IPostAdapter
{
try
{
return PostOperationResponse.OK(_mapper.Map<PostViewModel>(_postBusinessLogicContract.GetPostByData(data)));
return PostOperationResponse.OK(CustomMapper.MapObject<PostViewModel>(_postBusinessLogicContract.GetPostByData(data)));
}
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)
{
@@ -117,18 +102,18 @@ public class PostAdapter : IPostAdapter
{
try
{
_postBusinessLogicContract.InsertPost(_mapper.Map<PostDataModel>(postModel));
_postBusinessLogicContract.InsertPost(CustomMapper.MapObject<PostDataModel>(postModel));
return PostOperationResponse.NoContent();
}
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 +123,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)
{
@@ -151,23 +136,23 @@ public class PostAdapter : IPostAdapter
{
try
{
_postBusinessLogicContract.UpdatePost(_mapper.Map<PostDataModel>(postModel));
_postBusinessLogicContract.UpdatePost(CustomMapper.MapObject<PostDataModel>(postModel));
return PostOperationResponse.NoContent();
}
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 +162,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 +186,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 +225,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 +248,4 @@ public class PostAdapter : IPostAdapter
return PostOperationResponse.InternalServerError(ex.Message);
}
}
}
}

View File

@@ -1,48 +1,36 @@
using AutoMapper;
using DaisiesContracts.AdapterContracts;
using Microsoft.Extensions.Localization;
using DaisiesContracts.AdapterContracts.OperationResponses;
using DaisiesContracts.AdapterContracts;
using DaisiesContracts.BindingModels;
using DaisiesContracts.BuisnessLogicContracts;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.Mapper;
using DaisiesContracts.Resources;
using DaisiesContracts.ViewModels;
using DaisiesContracts.BuisnessLogicContracts;
namespace DaisiesWebApi.Adapters;
public class ProductAdapter : IProductAdapter
internal class ProductAdapter(IProductBuisnessLogicContract
productBusinessLogicContract, ILogger<ProductAdapter> logger, IStringLocalizer<Messages> localizer) : IProductAdapter
{
private readonly IProductBuisnessLogicContract
_productBusinessLogicContract;
private readonly ILogger _logger;
private readonly Mapper _mapper;
public ProductAdapter(IProductBuisnessLogicContract
productBusinessLogicContract, ILogger<ProductAdapter> logger)
{
_productBusinessLogicContract = productBusinessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<ProductBindingModel, ProductDataModel>();
cfg.CreateMap<ProductDataModel, ProductViewModel>();
cfg.CreateMap<ProductHistoryDataModel, ProductHistoryViewModel>();
});
_mapper = new Mapper(config);
}
private readonly IProductBuisnessLogicContract _productBusinessLogicContract = productBusinessLogicContract;
private readonly ILogger _logger = logger;
private readonly IStringLocalizer<Messages> _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");
var products = _productBusinessLogicContract.GetAllProducts(!includeDeleted);
return ProductOperationResponse.OK(
products.Select(p => CustomMapper.MapObject<ProductViewModel>(p)).ToList()
);
}
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 +39,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 => CustomMapper.MapObject<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 +70,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 =>
CustomMapper.MapObject<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)
@@ -112,27 +96,27 @@ public class ProductAdapter : IProductAdapter
try
{
return
ProductOperationResponse.OK(_mapper.Map<ProductViewModel>(_productBusinessLogicContract.GetProductByData(data)));
ProductOperationResponse.OK(CustomMapper.MapObject<ProductViewModel>(_productBusinessLogicContract.GetProductByData(data)));
}
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)
{
@@ -146,18 +130,18 @@ public class ProductAdapter : IProductAdapter
{
try
{
_productBusinessLogicContract.InsertProduct(_mapper.Map<ProductDataModel>(productModel));
_productBusinessLogicContract.InsertProduct(CustomMapper.MapObject<ProductDataModel>(productModel));
return ProductOperationResponse.NoContent();
}
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 +151,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)
{
@@ -181,23 +165,23 @@ public class ProductAdapter : IProductAdapter
{
try
{
_productBusinessLogicContract.UpdateProduct(_mapper.Map<ProductDataModel>(productModel));
_productBusinessLogicContract.UpdateProduct(CustomMapper.MapObject<ProductDataModel>(productModel));
return ProductOperationResponse.NoContent();
}
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 +191,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 +215,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

@@ -1,34 +1,18 @@
using AutoMapper;
using DaisiesContracts.AdapterContracts;
using Microsoft.Extensions.Localization;
using DaisiesContracts.AdapterContracts.OperationResponses;
using DaisiesContracts.AdapterContracts;
using DaisiesContracts.BuisnessLogicContracts;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.Mapper;
using DaisiesContracts.Resources;
using DaisiesContracts.ViewModels;
namespace DaisiesWebApi.Adapters;
public class ReportAdapter : IReportAdapter
internal class ReportAdapter(IReportContract reportContract, ILogger logger, IStringLocalizer<Messages> localizer) : IReportAdapter
{
private readonly IReportContract _reportContract;
private readonly ILogger _logger;
private readonly Mapper _mapper;
public ReportAdapter(IReportContract reportContract, ILogger logger)
{
_reportContract = reportContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<ProductProductHistoryDataModel, ProductProductHistoryViewModel>();
cfg.CreateMap<SaleDataModel, SaleViewModel>(); ;
cfg.CreateMap<SaleProductDataModel, SaleProductViewModel>();
cfg.CreateMap<ClientDiscountByPeriodDataModel, ClientDiscountByPeriodViewModel>();
cfg.CreateMap<ClientDiscountDataModel, ClientDiscountByPeriodDataModel>();
});
_mapper = new Mapper(config);
}
private readonly IReportContract _reportContract = reportContract;
private readonly ILogger _logger = logger;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public async Task<ReportOperationResponse> CreateDocumentProductPricesByProductAsync(CancellationToken ct)
{
try
@@ -38,12 +22,12 @@ public class ReportAdapter : IReportAdapter
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "InvalidOperationException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageInvalidOperationException"], ex.InnerException!.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -57,23 +41,23 @@ public class ReportAdapter : IReportAdapter
{
try
{
return SendStream(await _reportContract.CreateDocumentSalesByPeriodAsync(dateStart, dateFinish, ct),
return SendStream(await _reportContract.CreateDocumentSalesByPeriodAsync(dateStart.ToUniversalTime(), dateFinish.ToUniversalTime(), ct),
"sales.xslx");
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
return ReportOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageIncorrectDatesException"], ex.Message));
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "InvalidOperationException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageInvalidOperationException"], ex.InnerException!.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -86,17 +70,17 @@ public class ReportAdapter : IReportAdapter
{
try
{
return ReportOperationResponse.OK([.. (await _reportContract.GetDataProductPricesByProductAsync(ct)).Select(x => _mapper.Map<ProductProductHistoryViewModel>(x))]);
return ReportOperationResponse.OK([.. (await _reportContract.GetDataProductPricesByProductAsync(ct)).Select(x => CustomMapper.MapObject<ProductProductHistoryViewModel>(x))]);
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "InvalidOperationException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message} ");
return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageInvalidOperationException"], ex.InnerException!.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -110,23 +94,23 @@ public class ReportAdapter : IReportAdapter
{
try
{
return ReportOperationResponse.OK((await _reportContract.GetDataSaleByPeriodAsync(dateStart, dateFinish, ct)).Select(x =>
_mapper.Map<SaleViewModel>(x)).ToList());
return ReportOperationResponse.OK((await _reportContract.GetDataSaleByPeriodAsync(dateStart.ToUniversalTime(), dateFinish.ToUniversalTime(), ct)).Select(x =>
CustomMapper.MapObject<SaleViewModel>(x)).ToList());
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
return ReportOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageIncorrectDatesException"], ex.Message));
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "InvalidOperationException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageInvalidOperationException"], ex.InnerException!.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -146,23 +130,23 @@ public class ReportAdapter : IReportAdapter
{
try
{
return ReportOperationResponse.OK((await _reportContract.GetDataDiscountByPeriodAsync(dateStart, dateFinish, ct))
.Select(x => _mapper.Map<ClientDiscountByPeriodViewModel>(x)).ToList());
return ReportOperationResponse.OK((await _reportContract.GetDataDiscountByPeriodAsync(dateStart.ToUniversalTime(), dateFinish.ToUniversalTime(), ct))
.Select(x => CustomMapper.MapObject<ClientDiscountByPeriodViewModel>(x)).ToList());
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
return ReportOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageIncorrectDatesException"], ex.Message));
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "InvalidOperationException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageInvalidOperationException"], ex.InnerException!.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -176,22 +160,22 @@ public class ReportAdapter : IReportAdapter
{
try
{
return SendStream(await _reportContract.CreateDocumentDiscountByPeriodAsync(dateStart, dateFinish, ct), "discount.pdf");
return SendStream(await _reportContract.CreateDocumentDiscountByPeriodAsync(dateStart.ToUniversalTime(), dateFinish.ToUniversalTime(), ct), "discount.pdf");
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message} ");
return ReportOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageIncorrectDatesException"], ex.Message));
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "InvalidOperationException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageInvalidOperationException"], ex.InnerException!.Message));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
@@ -200,4 +184,4 @@ public class ReportAdapter : IReportAdapter
ReportOperationResponse.InternalServerError(ex.Message);
}
}
}
}

View File

@@ -1,57 +1,39 @@
using AutoMapper;
using DaisiesBuisnessLogic.Implementations;
using DaisiesContracts.AdapterContracts.OperationResponses;
using DaisiesContracts.AdapterContracts;
using DaisiesContracts.AdapterContracts.OperationResponses;
using DaisiesContracts.BindingModels;
using DaisiesContracts.BuisnessLogicContracts;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.Mapper;
using DaisiesContracts.Resources;
using DaisiesContracts.ViewModels;
using Microsoft.Extensions.Localization;
using DaisiesContracts.BuisnessLogicContracts;
namespace DaisiesWebApi.Adapters;
public class SaleAdapter : ISaleAdapter
internal class SaleAdapter(ISaleBuisnessLogicContract saleBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<SaleAdapter> logger) : ISaleAdapter
{
private readonly ISaleBuisnessLogicContract _saleBusinessLogicContract;
private readonly ISaleBuisnessLogicContract _saleBusinessLogicContract = saleBusinessLogicContract;
private readonly ILogger _logger;
private readonly ILogger _logger = logger;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public SaleAdapter(ISaleBuisnessLogicContract saleBusinessLogicContract, ILogger<SaleAdapter> logger)
{
_saleBusinessLogicContract = saleBusinessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<SaleBindingModel, SaleDataModel>();
cfg.CreateMap<SaleDataModel, SaleViewModel>();
cfg.CreateMap<SaleProductBindingModel, SaleProductDataModel>();
cfg.CreateMap<SaleProductDataModel, SaleProductViewModel>();
});
_mapper = new Mapper(config);
}
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 => CustomMapper.MapObject<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 +46,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 => CustomMapper.MapObject<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 +74,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 => CustomMapper.MapObject<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 +104,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 => CustomMapper.MapObject<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)
{
@@ -163,27 +132,27 @@ public class SaleAdapter : ISaleAdapter
{
try
{
return SaleOperationResponse.OK(_mapper.Map<SaleViewModel>(_saleBusinessLogicContract.GetSaleByData(id)));
return SaleOperationResponse.OK(CustomMapper.MapObject<SaleViewModel>(_saleBusinessLogicContract.GetSaleByData(id)));
}
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)
{
@@ -196,24 +165,24 @@ public class SaleAdapter : ISaleAdapter
{
try
{
var data = _mapper.Map<SaleDataModel>(saleModel);
_saleBusinessLogicContract.InsertSale(_mapper.Map<SaleDataModel>(saleModel));
var data = CustomMapper.MapObject<SaleDataModel>(saleModel);
_saleBusinessLogicContract.InsertSale(CustomMapper.MapObject<SaleDataModel>(saleModel));
return SaleOperationResponse.NoContent();
}
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 +201,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)
{
@@ -260,4 +229,4 @@ public class SaleAdapter : ISaleAdapter
return SaleOperationResponse.InternalServerError(ex.Message);
}
}
}
}

View File

@@ -1,47 +1,34 @@
using AutoMapper;
using DaisiesBuisnessLogic.Implementations;
using DaisiesContracts.AdapterContracts;
using Microsoft.Extensions.Localization;
using DaisiesContracts.AdapterContracts.OperationResponses;
using DaisiesContracts.AdapterContracts;
using DaisiesContracts.BindingModels;
using DaisiesContracts.BuisnessLogicContracts;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.Mapper;
using DaisiesContracts.Resources;
using DaisiesContracts.ViewModels;
using DaisiesContracts.BuisnessLogicContracts;
namespace DaisiesWebApi.Adapters;
public class WorkerAdapter : IWorkerAdapter
internal class WorkerAdapter(IWorkerBuisnessLogicContract
buyerBusinessLogicContract, ILogger<WorkerAdapter> logger, IStringLocalizer<Messages> localizer) : IWorkerAdapter
{
private readonly IWorkerBuisnessLogicContract _buyerBusinessLogicContract;
private readonly ILogger _logger;
private readonly Mapper _mapper;
public WorkerAdapter(IWorkerBuisnessLogicContract
workerBusinessLogicContract, ILogger<WorkerAdapter> logger)
{
_buyerBusinessLogicContract = workerBusinessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<WorkerBindingModel, WorkerDataModel>();
cfg.CreateMap<WorkerDataModel, WorkerViewModel>();
});
_mapper = new Mapper(config);
}
private readonly IWorkerBuisnessLogicContract _buyerBusinessLogicContract = buyerBusinessLogicContract;
private readonly ILogger _logger = logger;
private readonly IStringLocalizer<Messages> _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");
return WorkerOperationResponse.OK([..
_buyerBusinessLogicContract.GetAllWorkers(!includeDeleted).Select(x =>
CustomMapper.MapObject<WorkerViewModel>(x))]);
}
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)
{
@@ -54,22 +41,19 @@ public class WorkerAdapter : IWorkerAdapter
{
try
{
return WorkerOperationResponse.OK([.._buyerBusinessLogicContract.GetAllWorkersByPost(id, !includeDeleted).Select(x =>_mapper.Map<WorkerViewModel>(x))]);
return WorkerOperationResponse.OK([..
_buyerBusinessLogicContract.GetAllWorkersByPost(id, !includeDeleted).Select(x =>
CustomMapper.MapObject<WorkerViewModel>(x))]);
}
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 +67,21 @@ 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 => CustomMapper.MapObject<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 +95,21 @@ 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 => CustomMapper.MapObject<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)
{
@@ -141,27 +123,27 @@ public class WorkerAdapter : IWorkerAdapter
try
{
return
WorkerOperationResponse.OK(_mapper.Map<WorkerViewModel>(_buyerBusinessLogicContract.GetWorkerByData(data)));
WorkerOperationResponse.OK(CustomMapper.MapObjectWithNull<WorkerViewModel>(_buyerBusinessLogicContract.GetWorkerByData(data)));
}
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)
{
@@ -170,22 +152,23 @@ public class WorkerAdapter : IWorkerAdapter
WorkerOperationResponse.InternalServerError(ex.Message);
}
}
public WorkerOperationResponse RegisterWorker(WorkerBindingModel workerModel)
public WorkerOperationResponse RegisterWorker(WorkerBindingModel
workerModel)
{
try
{
_buyerBusinessLogicContract.InsertWorker(_mapper.Map<WorkerDataModel>(workerModel));
_buyerBusinessLogicContract.InsertWorker(CustomMapper.MapObject<WorkerDataModel>(workerModel));
return WorkerOperationResponse.NoContent();
}
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 +178,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)
{
@@ -204,27 +187,28 @@ public class WorkerAdapter : IWorkerAdapter
WorkerOperationResponse.InternalServerError(ex.Message);
}
}
public WorkerOperationResponse ChangeWorkerInfo(WorkerBindingModel workerModel)
public WorkerOperationResponse ChangeWorkerInfo(WorkerBindingModel
workerModel)
{
try
{
_buyerBusinessLogicContract.UpdateWorker(_mapper.Map<WorkerDataModel>(workerModel));
_buyerBusinessLogicContract.UpdateWorker(CustomMapper.MapObject<WorkerDataModel>(workerModel));
return WorkerOperationResponse.NoContent();
}
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 +218,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 +237,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

@@ -1,22 +1,26 @@
using DaisiesContracts.BuisnessLogicContracts;
using DaisiesContracts.DataModels;
using DaisiesContracts.Enum;
using DaisiesContracts.Enums;
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

@@ -1,4 +1,7 @@
namespace DaisiesContracts.BindingModels;
using System.ComponentModel.DataAnnotations;
namespace DaisiesContracts.BindingModels;
public class PostBindingModel
{

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,29 @@ public class ClientDiscountDataModel(string buyerId, double totalSum, double per
_buyer = buyer;
}
public void Validate()
public ClientDiscountDataModel() : this(string.Empty, 0, 0) { }
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

@@ -1,13 +1,17 @@
using DaisiesContracts.Enum;
using DaisiesContracts.Enums;
using DaisiesContracts.Exceptions;
using DaisiesContracts.Extensions;
using DaisiesContracts.Infrastructure;
using DaisiesContracts.Resources;
using Microsoft.Extensions.Localization;
using DaisiesContracts.Mapper;
namespace DaisiesContracts.DataModels;
public class PostDataModel(string postId, string postName, PostType postType, double salary) : IValidation
internal class PostDataModel(string id, string postName, PostType postType, double salary) : IValidation
{
public string Id { get; private set; } = postId;
[AlternativeName("PostId")]
public string Id { get; private set; } = id;
public string PostName { get; private set; } = postName;
@@ -15,21 +19,23 @@ public class PostDataModel(string postId, string postName, PostType postType, do
public double Salary { get; private set; } = salary;
public void Validate()
public PostDataModel() : this(string.Empty, string.Empty, PostType.None, 0) { }
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

@@ -1,11 +1,13 @@
using DaisiesContracts.Enum;
using DaisiesContracts.Enums;
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; }
@@ -13,11 +15,6 @@ public class ProductDataModel : IValidation
public string SupplierId { get; private set; }
public double Price { get; private set; }
public bool IsDeleted { get; private set; }
public ProductDataModel()
{
}
public ProductDataModel(string id, string productName, ProductType productType, string SupplierId, double price, bool isDeleted)
{
Id = id;
@@ -28,20 +25,22 @@ public class ProductDataModel : IValidation
IsDeleted = isDeleted;
}
public void Validate()
public ProductDataModel() : this(string.Empty, string.Empty, ProductType.None, string.Empty, 0, false) { }
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,18 +1,20 @@
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 string ProductName => _product?.ProductName ?? string.Empty;
public DateTime ChangeDate { get; private set; } = DateTime.UtcNow.ToUniversalTime();
public string ProductName => Product?.ProductName ?? string.Empty;
public ProductHistoryDataModel(
string productId,
@@ -20,16 +22,19 @@ public class ProductHistoryDataModel(string productId, double oldPrice) : IValid
DateTime changeDate,
ProductDataModel product) : this(productId, oldPrice)
{
ChangeDate = changeDate;
_product = product;
ChangeDate = changeDate.ToUniversalTime();
Product = product;
}
public void Validate()
public ProductDataModel? Product;
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,11 @@
using DaisiesContracts.Exceptions;
using DaisiesContracts.Extensions;
using DaisiesContracts.Infrastructure;
using DaisiesContracts.Resources;
using Microsoft.Extensions.Localization;
using DaisiesContracts.Mapper;
public class SaleDataModel: IValidation
internal class SaleDataModel: IValidation
{
public string Id { get; private set; }
@@ -17,6 +20,7 @@ public class SaleDataModel: IValidation
public bool IsCancel { get; private set; }
[AlternativeName("SaleProducts")]
public List<SaleProductDataModel> Products { get; private set; }
private readonly BuyerDataModel? _buyer;
@@ -28,13 +32,16 @@ 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;
}
public SaleDataModel(string id, string workerId, string? buyerId, List<SaleProductDataModel> products) : this(id, workerId, buyerId, 1, false, products) { }
public SaleDataModel()
{
}
public SaleDataModel(string id, string workerId, string? buyerId, double sum, bool isCancel, List<SaleProductDataModel> products)
{
@@ -47,27 +54,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,18 @@ public class SaleProductDataModel(string saleId, string productId, int count) :
_product = product;
}
public void Validate()
public SaleProductDataModel() : this(string.Empty, string.Empty, 0) { }
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,22 +1,28 @@
using DaisiesContracts.Exceptions;
using DaisiesContracts.Extensions;
using DaisiesContracts.Infrastructure;
using DaisiesContracts.Resources;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Localization;
using System.Text.RegularExpressions;
using DaisiesContracts.Mapper;
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
{
[AlternativeName("Post")]
public PostDataModel? _post;
public string Id { get; private set; } = id;
public string FIO { get; private set; } = fio;
public string PostId { get; private set; } = postId;
public DateTime BirthDate { get; private set; } = birthDate;
public DateTime EmploymentDate { get; private set; } = employmentDate;
public 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;
public string PostName => _post?.PostName ?? string.Empty;
public WorkerDataModel() : this(string.Empty, string.Empty, string.Empty, DateTime.UtcNow, DateTime.UtcNow, false) { }
public WorkerDataModel(string id, string fio, string postId, DateTime
birthDate, DateTime employmentDate, bool isDeleted, PostDataModel post) :
this(id, fio, postId, birthDate, employmentDate, isDeleted)
@@ -29,22 +35,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,4 +1,4 @@
namespace DaisiesContracts.Enum;
namespace DaisiesContracts.Enums;
[Flags]
public enum DiscountType

View File

@@ -1,4 +1,4 @@
namespace DaisiesContracts.Enum;
namespace DaisiesContracts.Enums;
public enum PostType
{

View File

@@ -1,4 +1,4 @@
namespace DaisiesContracts.Enum;
namespace DaisiesContracts.Enums;
public enum ProductType
{

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,6 @@
namespace DaisiesContracts.Mapper;
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)]
class AlternativeNameAttribute(string alternativeName) : Attribute
{
public string AlternativeName { get; set; } = alternativeName;
}

View File

@@ -0,0 +1,293 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
namespace DaisiesContracts.Mapper
{
internal static class CustomMapper
{
public static To MapObject<To>(object obj, To newObject)
{
ArgumentNullException.ThrowIfNull(obj);
ArgumentNullException.ThrowIfNull(newObject);
var typeFrom = obj.GetType();
var typeTo = newObject.GetType();
var propertiesFrom = typeFrom.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(x => x.CanRead)
.ToArray();
// Обработка свойств
foreach (var property in typeTo.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(x => x.CanWrite))
{
if (property.GetCustomAttribute<IgnoreMappingAttribute>() is not null)
continue;
var propertyFrom = TryGetPropertyFrom(property, propertiesFrom);
if (propertyFrom is null)
{
FindAndMapDefaultValue(property, newObject);
continue;
}
var fromValue = propertyFrom.GetValue(obj);
var postProcessingAttribute = property.GetCustomAttribute<PostProcessingAttribute>();
if (postProcessingAttribute is not null)
{
var value = PostProcessing(fromValue, postProcessingAttribute, newObject);
if (value is not null)
{
property.SetValue(newObject, value);
}
continue;
}
// Обработка коллекций
if (propertyFrom.PropertyType.IsGenericType &&
propertyFrom.PropertyType.GetGenericTypeDefinition() == typeof(List<>) &&
fromValue is not null)
{
fromValue = MapListOfObjects(property, fromValue);
}
// Обработка перечислений
if (propertyFrom.PropertyType.IsEnum && property.PropertyType.IsEnum)
{
if (fromValue != null && property.PropertyType != propertyFrom.PropertyType)
{
fromValue = Enum.ToObject(property.PropertyType, Convert.ChangeType(fromValue, Enum.GetUnderlyingType(propertyFrom.PropertyType)));
}
property.SetValue(newObject, fromValue);
continue;
}
// enum -> string
if (propertyFrom.PropertyType.IsEnum && property.PropertyType == typeof(string) && fromValue != null)
{
fromValue = fromValue.ToString();
}
// string -> enum
else if (!propertyFrom.PropertyType.IsEnum && property.PropertyType.IsEnum && fromValue is not null)
{
if (fromValue is string stringValue)
fromValue = Enum.Parse(property.PropertyType, stringValue);
else
fromValue = Enum.ToObject(property.PropertyType, fromValue);
}
// Вложенные объекты
if (fromValue is not null)
{
if (propertyFrom.PropertyType.IsClass
&& property.PropertyType.IsClass
&& propertyFrom.PropertyType != typeof(string)
&& property.PropertyType != typeof(string)
&& !property.PropertyType.IsAssignableFrom(propertyFrom.PropertyType))
{
try
{
var nestedInstance = Activator.CreateInstance(property.PropertyType);
if (nestedInstance != null)
{
var nestedMapped = MapObject(fromValue, nestedInstance);
property.SetValue(newObject, nestedMapped);
continue;
}
}
catch
{
// ignore
}
}
property.SetValue(newObject, fromValue);
}
}
// Обработка полей
var fieldsTo = typeTo.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
var fieldsFrom = typeFrom.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
foreach (var field in fieldsTo)
{
if (field.Name.Contains("k__BackingField"))
continue;
if (field.GetCustomAttribute<IgnoreMappingAttribute>() is not null)
continue;
var sourceField = fieldsFrom.FirstOrDefault(f => f.Name == field.Name);
object? fromValue = null;
if (sourceField is not null)
{
fromValue = sourceField.GetValue(obj);
}
else
{
var propertyName = field.Name.TrimStart('_');
var sourceProperty = typeFrom.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (sourceProperty is not null && sourceProperty.CanRead)
{
fromValue = sourceProperty.GetValue(obj);
}
}
if (fromValue is null)
continue;
if (field.FieldType.IsClass && field.FieldType != typeof(string))
{
try
{
var nested = Activator.CreateInstance(field.FieldType)!;
var mapped = MapObject(fromValue, nested);
RemoveReadOnly(field);
field.SetValue(newObject, mapped);
continue;
}
catch (MissingMethodException)
{
Console.WriteLine($"Нет конструктора по умолчанию для {field.FieldType}");
}
catch (Exception ex)
{
Console.WriteLine($"Ошибка маппинга для {field.Name}: {ex.Message}");
}
}
RemoveReadOnly(field);
field.SetValue(newObject, fromValue);
}
// Обработка пост-обработки класса
var classPostProcessing = typeTo.GetCustomAttribute<PostProcessingAttribute>();
if (classPostProcessing is not null && classPostProcessing.MappingCallMethodName is not null)
{
var methodInfo = typeTo.GetMethod(classPostProcessing.MappingCallMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
methodInfo?.Invoke(newObject, []);
}
return newObject;
}
private static void RemoveReadOnly(FieldInfo field)
{
if (!field.IsInitOnly)
return;
var attr = typeof(FieldInfo).GetField("m_fieldAttributes", BindingFlags.Instance | BindingFlags.NonPublic);
if (attr != null)
{
var current = (FieldAttributes)attr.GetValue(field)!;
attr.SetValue(field, current & ~FieldAttributes.InitOnly);
}
}
public static To MapObject<To>(object obj) => MapObject(obj, Activator.CreateInstance<To>()!);
public static To? MapObjectWithNull<To>(object? obj) => obj is null ? default : MapObject(obj, Activator.CreateInstance<To>());
private static PropertyInfo? TryGetPropertyFrom(PropertyInfo propertyTo, PropertyInfo[] propertiesFrom)
{
var customAttribute = propertyTo.GetCustomAttributes<AlternativeNameAttribute>()?
.ToArray()
.FirstOrDefault(x => propertiesFrom.Any(y => y.Name == x.AlternativeName));
if (customAttribute is not null)
{
return propertiesFrom.FirstOrDefault(x => x.Name == customAttribute.AlternativeName);
}
return propertiesFrom.FirstOrDefault(x => x.Name == propertyTo.Name);
}
private static object? PostProcessing<T>(object? value, PostProcessingAttribute postProcessingAttribute, T newObject)
{
if (value is null || newObject is null)
{
return null;
}
if (!string.IsNullOrEmpty(postProcessingAttribute.MappingCallMethodName))
{
var methodInfo =
newObject.GetType().GetMethod(postProcessingAttribute.MappingCallMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
if (methodInfo is not null)
{
return methodInfo.Invoke(newObject, [value]);
}
}
else if (postProcessingAttribute.ActionType != PostProcessingType.None)
{
switch (postProcessingAttribute.ActionType)
{
case PostProcessingType.ToUniversalTime:
return ToUniversalTime(value);
case PostProcessingType.ToLocalTime:
return ToLocalTime(value);
}
}
return null;
}
private static object? ToLocalTime(object? obj)
{
if (obj is DateTime date)
return date.ToLocalTime();
return obj;
}
private static object? ToUniversalTime(object? obj)
{
if (obj is DateTime date)
return date.ToUniversalTime();
return obj;
}
private static void FindAndMapDefaultValue<T>(PropertyInfo property, T newObject)
{
var defaultValueAttribute = property.GetCustomAttribute<DefaultValueAttribute>();
if (defaultValueAttribute is null)
{
return;
}
if (defaultValueAttribute.DefaultValue is not null)
{
property.SetValue(newObject, defaultValueAttribute.DefaultValue);
return;
}
var value = defaultValueAttribute.Func switch
{
DefaultValueFunc.UtcNow => DateTime.UtcNow,
_ => (object?)null,
};
if (value is not null)
{
property.SetValue(newObject, value);
}
}
private static object? MapListOfObjects(PropertyInfo propertyTo, object list)
{
var listResult = Activator.CreateInstance(propertyTo.PropertyType);
var genericType = propertyTo.PropertyType.GenericTypeArguments[0];
var addMethod = propertyTo.PropertyType.GetMethod("Add", new[] { genericType });
foreach (var elem in (IEnumerable)list)
{
var newElem = MapObject(elem, Activator.CreateInstance(genericType)!);
if (newElem is not null)
{
addMethod?.Invoke(listResult, [newElem]);
}
}
return listResult;
}
}
}

View File

@@ -0,0 +1,12 @@
namespace DaisiesContracts.Mapper;
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class)]
class DefaultValueAttribute : Attribute
{
public object? DefaultValue { get; set; }
public DefaultValueFunc Func { get; set; } = DefaultValueFunc.None;
[Obsolete("Use Func instead")]
public string? FuncName { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace DaisiesContracts.Mapper
{
public enum DefaultValueFunc
{
None = 0,
UtcNow = 1
}
}

View File

@@ -0,0 +1,5 @@
namespace DaisiesContracts.Mapper;
[AttributeUsage(AttributeTargets.Property)]
class IgnoreMappingAttribute : Attribute
{
}

View File

@@ -0,0 +1,8 @@
namespace DaisiesContracts.Mapper;
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class | AttributeTargets.Field)]
class PostProcessingAttribute : Attribute
{
public string? MappingCallMethodName { get; set; }
public PostProcessingType ActionType { get; set; } = PostProcessingType.None;
}

View File

@@ -0,0 +1,9 @@
namespace DaisiesContracts.Mapper;
enum PostProcessingType
{
None = -1,
ToUniversalTime = 1,
ToLocalTime = 2
}

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

@@ -1,9 +1,15 @@
namespace DaisiesContracts.ViewModels;
using DaisiesContracts.Mapper;
namespace DaisiesContracts.ViewModels;
public class ClientDiscountByPeriodViewModel
{
public required string BuyerFIO { get; set; }
public double TotalDiscount { get; set; }
[PostProcessing(ActionType = PostProcessingType.ToLocalTime)]
public DateTime FromPeriod { get; set; }
[PostProcessing(ActionType = PostProcessingType.ToLocalTime)]
public DateTime ToPeriod { get; set; }
}

View File

@@ -1,7 +1,10 @@
namespace DaisiesContracts.ViewModels;
using DaisiesContracts.Mapper;
namespace DaisiesContracts.ViewModels;
public class PostViewModel
{
[AlternativeName("PostId")]
public required string Id { get; set; }
public required string PostName { get; set; }

View File

@@ -1,7 +1,10 @@
namespace DaisiesContracts.ViewModels;
using DaisiesContracts.Mapper;
namespace DaisiesContracts.ViewModels;
public class ProductHistoryViewModel
{
[AlternativeName("ProductName")]
public required string ProductName { get; set; }
public double OldPrice { get; set; }

View File

@@ -1,4 +1,6 @@
namespace DaisiesContracts.ViewModels;
using DaisiesContracts.Mapper;
namespace DaisiesContracts.ViewModels;
public class SaleViewModel
{
@@ -12,6 +14,7 @@ public class SaleViewModel
public string? BuyerFIO { get; set; }
[PostProcessing(ActionType = PostProcessingType.ToLocalTime)]
public DateTime SaleDate { get; set; }
public double Sum { get; set; }

View File

@@ -1,7 +1,10 @@
namespace DaisiesContracts.ViewModels;
using DaisiesContracts.Mapper;
namespace DaisiesContracts.ViewModels;
public class WorkerViewModel
{
[AlternativeName("WorkerId")]
public required string Id { get; set; }
public required string FIO { get; set; }

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,16 +51,21 @@ 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)
.WithMany(p => p.ProductHistories)
.HasForeignKey(ph => ph.ProductId);
modelBuilder.Entity<ProductHistory>()
.HasOne(ph => ph.Product)
.WithMany()
.HasForeignKey(ph => ph.ProductId);
modelBuilder.Entity<Buyer>()
.Property(x => x.Configuration)
.HasColumnType("jsonb")

View File

@@ -7,7 +7,6 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.3">
<PrivateAssets>all</PrivateAssets>
@@ -16,8 +15,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,61 +1,43 @@
using AutoMapper;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using DaisiesContracts.Mapper;
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(DaisiesDbContext dbContext, IStringLocalizer<Messages> localizer) : IBuyerStorageContract
{
private readonly DaisiesDbContext _dbContext = dbContext;
private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly DaisiesDbContext _dbContext;
private readonly Mapper _mapper;
public BuyerStorageContract(DaisiesDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Buyer, BuyerDataModel>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id))
.ForMember(dest => dest.PhoneNumber, opt => opt.MapFrom(src => src.PhoneNumber))
.ForMember(dest => dest.DiscountSize, opt => opt.MapFrom(src => src.DiscountSize))
.ForMember(dest => dest.FIO, opt => opt.MapFrom(src => src.FIO))
.ForMember(dest => dest.ConfigurationModel, opt => opt.MapFrom(src => src.Configuration));
cfg.CreateMap<BuyerDataModel, Buyer>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id))
.ForMember(dest => dest.PhoneNumber, opt => opt.MapFrom(src => src.PhoneNumber))
.ForMember(dest => dest.DiscountSize, opt => opt.MapFrom(src => src.DiscountSize))
.ForMember(dest => dest.FIO, opt => opt.MapFrom(src => src.FIO))
.ForMember(dest => dest.Configuration, opt => opt.MapFrom(src => src.ConfigurationModel));
});
_mapper = new Mapper(config);
}
public List<BuyerDataModel> GetList()
{
try
{
return [.. _dbContext.Buyers.Select(x => _mapper.Map<BuyerDataModel>(x))];
return [.. _dbContext.Buyers.Select(x => CustomMapper.MapObject<BuyerDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public BuyerDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<BuyerDataModel>(GetBuyerById(id));
return CustomMapper.MapObjectWithNull<BuyerDataModel>(GetBuyerById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public BuyerDataModel? GetElementByFIO(string fio)
@@ -63,57 +45,57 @@ public class BuyerStorageContract : IBuyerStorageContract
try
{
return
_mapper.Map<BuyerDataModel>(_dbContext.Buyers.FirstOrDefault(x => x.FIO == fio));
CustomMapper.MapObjectWithNull<BuyerDataModel>(_dbContext.Buyers.FirstOrDefault(x => x.FIO == fio));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public BuyerDataModel? GetElementByPhoneNumber(string phoneNumber)
{
try
{
return _mapper.Map<BuyerDataModel>(_dbContext.Buyers.FirstOrDefault(x => x.PhoneNumber == phoneNumber));
return CustomMapper.MapObjectWithNull<BuyerDataModel>(_dbContext.Buyers.FirstOrDefault(x => x.PhoneNumber == phoneNumber));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public void AddElement(BuyerDataModel buyerDataModel)
{
try
{
_dbContext.Buyers.Add(_mapper.Map<Buyer>(buyerDataModel));
_dbContext.Buyers.Add(CustomMapper.MapObject<Buyer>(buyerDataModel));
_dbContext.SaveChanges();
}
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);
_dbContext.Buyers.Update(_mapper.Map(buyerDataModel,
var element = GetBuyerById(buyerDataModel.Id) ??
throw new ElementNotFoundException(buyerDataModel.Id, _localizer);
_dbContext.Buyers.Update(CustomMapper.MapObject(buyerDataModel,
element));
_dbContext.SaveChanges();
}
@@ -126,12 +108,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 +121,7 @@ public class BuyerStorageContract : IBuyerStorageContract
try
{
var element = GetBuyerById(id) ?? throw new
ElementNotFoundException(id);
ElementNotFoundException(id, _localizer);
_dbContext.Buyers.Remove(element);
_dbContext.SaveChanges();
}
@@ -151,8 +133,9 @@ 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,50 +1,34 @@
using AutoMapper;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using DaisiesContracts.Mapper;
using DaisiesContracts.Resources.StoragesContracts;
using DaisiesContracts.Resources;
using DaisiesDatabase.Models;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using Microsoft.Extensions.Localization;
namespace DaisiesDatabase.Implementations;
public class ClientDiscountStorageContract : IClientDiscountStorageContract
internal class ClientDiscountStorageContract(DaisiesDbContext dbContext, IStringLocalizer<Messages> localizer) : IClientDiscountStorageContract
{
private readonly DaisiesDbContext _dbContext;
private readonly IMapper _mapper;
private readonly DaisiesDbContext _dbContext = dbContext;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public ClientDiscountStorageContract(DaisiesDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<ClientDiscount, ClientDiscountDataModel>()
.ConstructUsing((src, ctx) => new ClientDiscountDataModel(
src.BuyerId,
src.TotalSum,
src.PersonalDiscount,
ctx.Mapper.Map<BuyerDataModel>(src.Buyers),
src.DiscountDate));
cfg.CreateMap<ClientDiscountDataModel, ClientDiscount>();
cfg.CreateMap<Buyer, BuyerDataModel>();
cfg.CreateMap<BuyerDataModel, Buyer>();
});
_mapper = new Mapper(config);
}
public void AddElement(ClientDiscountDataModel clientDiscountDataModel)
{
try
{
clientDiscountDataModel.Validate();
_dbContext.ClientDiscounts.Add(_mapper.Map<ClientDiscount>(clientDiscountDataModel));
clientDiscountDataModel.Validate(_localizer);
_dbContext.ClientDiscounts.Add(CustomMapper.MapObject<ClientDiscount>(clientDiscountDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -52,7 +36,7 @@ public class ClientDiscountStorageContract : IClientDiscountStorageContract
{
try
{
var element = _dbContext.ClientDiscounts.FirstOrDefault(x => x.BuyerId == id) ?? throw new ElementNotFoundException(id);
var element = _dbContext.ClientDiscounts.FirstOrDefault(x => x.BuyerId == id) ?? throw new ElementNotFoundException(id, _localizer);
_dbContext.Remove(element);
_dbContext.SaveChanges();
}
@@ -64,7 +48,7 @@ public class ClientDiscountStorageContract : IClientDiscountStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -73,12 +57,12 @@ public class ClientDiscountStorageContract : IClientDiscountStorageContract
try
{
var entity = _dbContext.ClientDiscounts.FirstOrDefault(x => x.BuyerId == id);
return entity != null ? _mapper.Map<ClientDiscountDataModel>(entity) : null;
return entity != null ? CustomMapper.MapObject<ClientDiscountDataModel>(entity) : null;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -90,12 +74,12 @@ public class ClientDiscountStorageContract : IClientDiscountStorageContract
.Include(cd => cd.Buyers)
.FirstOrDefault(cd => cd.Buyers.FIO == data);
return entity != null ? _mapper.Map<ClientDiscountDataModel>(entity) : null;
return entity != null ? CustomMapper.MapObject<ClientDiscountDataModel>(entity) : null;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -103,13 +87,13 @@ public class ClientDiscountStorageContract : IClientDiscountStorageContract
{
try
{
List<ClientDiscountDataModel> x = _dbContext.ClientDiscounts.Select(x => _mapper.Map<ClientDiscountDataModel>(x)).ToList();
List<ClientDiscountDataModel> x = _dbContext.ClientDiscounts.Select(x => CustomMapper.MapObject<ClientDiscountDataModel>(x)).ToList();
return x;
}
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)
@@ -119,14 +103,14 @@ public class ClientDiscountStorageContract : IClientDiscountStorageContract
List<ClientDiscountDataModel> x = [.. await _dbContext.ClientDiscounts
.Include(x => x.Buyers)
.Where(x => x.DiscountDate >= startDate && x.DiscountDate <= endDate)
.Select(x => _mapper.Map<ClientDiscountDataModel>(x))
.Select(x => CustomMapper.MapObject<ClientDiscountDataModel>(x))
.ToListAsync(ct)];
return x;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -134,22 +118,22 @@ public class ClientDiscountStorageContract : IClientDiscountStorageContract
{
try
{
clientDiscountDataModel.Validate();
clientDiscountDataModel.Validate(_localizer);
var entity = _dbContext.ClientDiscounts.FirstOrDefault(x => x.BuyerId == clientDiscountDataModel.BuyerId);
if (entity != null)
{
_mapper.Map(clientDiscountDataModel, entity);
CustomMapper.MapObject(clientDiscountDataModel, entity);
_dbContext.SaveChanges();
}
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,46 +1,31 @@
using AutoMapper;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using DaisiesContracts.Mapper;
using DaisiesContracts.Resources.StoragesContracts;
using DaisiesContracts.Resources;
using DaisiesDatabase.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
namespace DaisiesDatabase.Implementations;
public class PostStorageContract : IPostStorageContract
internal class PostStorageContract(DaisiesDbContext dbContext, IStringLocalizer<Messages> localizer) : IPostStorageContract
{
private readonly DaisiesDbContext _dbContext;
private readonly Mapper _mapper;
public PostStorageContract(DaisiesDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Post, PostDataModel>()
.ForMember(x => x.Id, x => x.MapFrom(src =>
src.PostId));
cfg.CreateMap<PostDataModel, Post>()
.ForMember(x => x.Id, x => x.Ignore())
.ForMember(x => x.PostId, x => x.MapFrom(src => src.Id))
.ForMember(x => x.IsActual, x => x.MapFrom(src => true))
.ForMember(x => x.ChangeDate, x => x.MapFrom(src => DateTime.UtcNow));
});
_mapper = new Mapper(config);
}
private readonly DaisiesDbContext _dbContext = dbContext;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<PostDataModel> GetList()
{
try
{
var query = _dbContext.Posts.AsQueryable();
return [.. _dbContext.Posts.Select(x => _mapper.Map<PostDataModel>(x))];
return [.. _dbContext.Posts.Select(x => CustomMapper.MapObject<PostDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -49,12 +34,12 @@ public class PostStorageContract : IPostStorageContract
{
try
{
return _mapper.Map<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostId == id && x.IsActual));
return CustomMapper.MapObjectWithNull<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostId == id && x.IsActual));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -62,12 +47,12 @@ public class PostStorageContract : IPostStorageContract
{
try
{
return _mapper.Map<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostName == name && x.IsActual));
return CustomMapper.MapObjectWithNull<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostName == name && x.IsActual));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -75,12 +60,12 @@ public class PostStorageContract : IPostStorageContract
{
try
{
return [.. _dbContext.Posts.Where(x => x.PostId == postId).Select(x => _mapper.Map<PostDataModel>(x))];
return [.. _dbContext.Posts.Where(x => x.PostId == postId).Select(x => CustomMapper.MapObject<PostDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -88,23 +73,23 @@ public class PostStorageContract : IPostStorageContract
{
try
{
_dbContext.Posts.Add(_mapper.Map<Post>(postDataModel));
_dbContext.Posts.Add(CustomMapper.MapObject<Post>(postDataModel));
_dbContext.SaveChanges();
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostName", postDataModel.PostName);
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,14 +100,14 @@ public class PostStorageContract : IPostStorageContract
var transaction = _dbContext.Database.BeginTransaction();
try
{
var element = GetPostById(postDataModel.Id) ?? throw new ElementNotFoundException(postDataModel.Id);
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();
var newElement = _mapper.Map<Post>(postDataModel);
var newElement = CustomMapper.MapObject<Post>(postDataModel);
_dbContext.Posts.Add(newElement);
_dbContext.SaveChanges();
transaction.Commit();
@@ -136,7 +121,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 +131,7 @@ public class PostStorageContract : IPostStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -154,10 +139,10 @@ public class PostStorageContract : IPostStorageContract
{
try
{
var element = GetPostById(id) ?? throw new ElementNotFoundException(id);
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 +158,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();
}
@@ -184,8 +169,5 @@ public class PostStorageContract : IPostStorageContract
}
}
private Post? GetPostById(string id)
{
return _dbContext.Posts.Where(x => x.PostId == id).OrderByDescending(x => x.ChangeDate).FirstOrDefault();
}
}
private Post? GetPostById(string id) => _dbContext.Posts.Where(x => x.PostId == id).OrderByDescending(x => x.ChangeDate).FirstOrDefault();
}

View File

@@ -1,33 +1,18 @@
using AutoMapper;
using DaisiesContracts.DataModels;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using DaisiesContracts.ViewModels;
using DaisiesContracts.Mapper;
using DaisiesContracts.Resources.StoragesContracts;
using DaisiesContracts.Resources;
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(DaisiesDbContext dbContext, IStringLocalizer<Messages> localizer) : IProductStorageContract
{
private readonly DaisiesDbContext _dbContext;
private readonly Mapper _mapper;
public ProductStorageContract(DaisiesDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Product, ProductDataModel>();
cfg.CreateMap<ProductDataModel, Product>()
.ForMember(x => x.IsDeleted, x => x.MapFrom(src => false));
cfg.CreateMap<ProductHistory, ProductHistoryDataModel>();
});
_mapper = new Mapper(config);
}
private readonly DaisiesDbContext _dbContext = dbContext;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<ProductDataModel> GetList(bool onlyActive = true, string?
SupplierId = null)
{
@@ -43,54 +28,97 @@ public class ProductStorageContract : IProductStorageContract
query = query.Where(x => x.SupplierId ==
SupplierId);
}
return [.. query.Select(x => _mapper.Map<ProductDataModel>(x))];
return [.. query.Select(x => CustomMapper.MapObject<ProductDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public List<ProductHistoryDataModel> GetHistoryByProductId(string productId)
public List<ProductHistoryDataModel> GetHistoryByProductId(string
productId)
{
try
{
return[.._dbContext.ProductHistories.Include(x => x.Product).Where(x => x.ProductId == productId).OrderByDescending(x =>x.ChangeDate).Select(x => _mapper.Map<ProductHistoryDataModel>(x))];
return _dbContext.ProductHistories
.Include(x => x.Product)
.Where(x => x.ProductId == productId)
.OrderByDescending(x => x.ChangeDate)
.Select(x => CustomMapper.MapObject<ProductHistoryDataModel>(x))
.ToList();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
}
public ProductDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<ProductDataModel>(GetProductById(id));
return CustomMapper.MapObjectWithNull<ProductDataModel>(GetProductById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public ProductDataModel? GetElementByName(string name)
{
try
{
return _mapper.Map<ProductDataModel>(_dbContext.Products.FirstOrDefault(x => x.ProductName == name && !x.IsDeleted));
return
CustomMapper.MapObjectWithNull<ProductDataModel>(_dbContext.Products.FirstOrDefault(x =>
x.ProductName == name && !x.IsDeleted));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public async Task<List<ProductHistoryDataModel>> GetListAsync(CancellationToken ct)
{
try
{
return [.. await _dbContext.ProductHistories.Include(x => x.Product).Select(x => CustomMapper.MapObject<ProductHistoryDataModel>(x)).ToListAsync(ct)];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
}
}
public void AddElement(ProductDataModel productDataModel)
{
try
{
_dbContext.Products.Add(CustomMapper.MapObject<Product>(productDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name ==
"ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
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, _localizer);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
}
}
public void UpdElement(ProductDataModel productDataModel)
{
try
@@ -98,13 +126,17 @@ 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 });
_dbContext.ProductHistories.Add(new
ProductHistory()
{ ProductId = element.Id, OldPrice = element.Price });
_dbContext.SaveChanges();
}
_dbContext.Products.Update(_mapper.Map(productDataModel, element));
_dbContext.Products.Update(CustomMapper.MapObject(productDataModel,
element));
_dbContext.SaveChanges();
transaction.Commit();
}
@@ -114,12 +146,15 @@ public class ProductStorageContract : IProductStorageContract
throw;
}
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Products_ProductName_IsDeleted" })
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)
catch (Exception ex) when (ex is ElementDeletedException || ex is
ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
@@ -127,15 +162,15 @@ public class ProductStorageContract : IProductStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public void DelElement(string id)
{
try
{
var element = GetProductById(id) ?? throw new ElementNotFoundException(id);
var element = GetProductById(id) ?? throw new
ElementNotFoundException(id, _localizer);
element.IsDeleted = true;
_dbContext.SaveChanges();
}
@@ -147,46 +182,14 @@ public class ProductStorageContract : IProductStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
private Product? GetProductById(string id) => _dbContext.Products.FirstOrDefault(x => x.Id == id && !x.IsDeleted);
public async Task<List<ProductHistoryDataModel>> GetListAsync(CancellationToken ct)
private ProductHistoryDataModel MapToDataModel(ProductHistory product)
{
try
{
return [.. await _dbContext.ProductHistories.Include(x => x.Product).Select(x => _mapper.Map<ProductHistoryDataModel>(x)).ToListAsync(ct)];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
var dataModel = CustomMapper.MapObject<ProductHistoryDataModel>(product);
dataModel.Product = CustomMapper.MapObject<ProductDataModel>(product.Product);
return dataModel;
}
public void AddElement(ProductDataModel productDataModel)
{
try
{
_dbContext.Products.Add(_mapper.Map<Product>(productDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", productDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Products_ProductName_IsDeleted" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("ProductName", productDataModel.ProductName);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
}
}

View File

@@ -1,34 +1,17 @@
using AutoMapper;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using DaisiesContracts.Mapper;
using DaisiesContracts.Resources.StoragesContracts;
using DaisiesContracts.Resources;
using DaisiesDatabase.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
namespace DaisiesDatabase.Implementations;
public class SaleStorageContract : ISaleStorageContract
internal class SaleStorageContract(DaisiesDbContext DaisiesDbContext, IStringLocalizer<Messages> localizer) : ISaleStorageContract
{
private readonly DaisiesDbContext _DaisiesDbContext;
private readonly Mapper _mapper;
public SaleStorageContract(DaisiesDbContext DaisiesDbContext)
{
_DaisiesDbContext = DaisiesDbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Buyer, BuyerDataModel>();
cfg.CreateMap<Product, ProductDataModel>();
cfg.CreateMap<Worker, WorkerDataModel>();
cfg.CreateMap<SaleProduct, SaleProductDataModel>();
cfg.CreateMap<SaleProductDataModel, SaleProduct>();
cfg.CreateMap<Sale, SaleDataModel>();
cfg.CreateMap<SaleDataModel, Sale>()
.ForMember(x => x.IsCancel, x => x.MapFrom(src => false))
.ForMember(x => x.SaleProducts, x => x.MapFrom(src => src.Products));
});
_mapper = new Mapper(config);
}
private readonly DaisiesDbContext _DaisiesDbContext = DaisiesDbContext;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<SaleDataModel> GetList(DateTime? startDate = null, DateTime?
endDate = null, string? workerId = null, string? buyerId = null, string?
@@ -37,13 +20,13 @@ public class SaleStorageContract : ISaleStorageContract
try
{
var query = _DaisiesDbContext.Sales
.Include(x => x.SaleProducts)
.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)
{
@@ -57,12 +40,32 @@ public class SaleStorageContract : ISaleStorageContract
{
query = query.Where(x => x.SaleProducts!.Any(y => y.ProductId == productId));
}
return [.. query.Select(x => _mapper.Map<SaleDataModel>(x))];
return [.. query.Select(x => CustomMapper.MapObject<SaleDataModel>(x))];
}
catch (Exception ex)
{
_DaisiesDbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public async Task<List<SaleDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct)
{
try
{
List<SaleDataModel> x = [.. await _DaisiesDbContext.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 => CustomMapper.MapObject<SaleDataModel>(x))
.ToListAsync(ct)];
return x;
}
catch (Exception ex)
{
_DaisiesDbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
}
}
@@ -70,12 +73,12 @@ public class SaleStorageContract : ISaleStorageContract
{
try
{
return _mapper.Map<SaleDataModel>(GetSaleById(id));
return CustomMapper.MapObjectWithNull<SaleDataModel>(GetSaleById(id));
}
catch (Exception ex)
{
_DaisiesDbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -83,7 +86,7 @@ public class SaleStorageContract : ISaleStorageContract
{
try
{
_DaisiesDbContext.Sales.Add(_mapper.Map<Sale>(saleDataModel));
_DaisiesDbContext.Sales.Add(CustomMapper.MapObject<Sale>(saleDataModel));
_DaisiesDbContext.SaveChanges();
@@ -91,7 +94,7 @@ public class SaleStorageContract : ISaleStorageContract
catch (Exception ex)
{
_DaisiesDbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -100,10 +103,10 @@ 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();
@@ -117,27 +120,14 @@ public class SaleStorageContract : ISaleStorageContract
catch (Exception ex)
{
_DaisiesDbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
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);
throw new StorageException(ex, _localizer);
}
}
private Sale? GetSaleById(string id) => _DaisiesDbContext.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,22 @@
using AutoMapper;
using DaisiesContracts.DataModels;
using DaisiesContracts.Exceptions;
using DaisiesContracts.StoragesContracts;
using DaisiesContracts.Mapper;
using DaisiesContracts.Resources.StoragesContracts;
using DaisiesContracts.Resources;
using DaisiesDatabase.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
namespace DaisiesDatabase.Implementations;
public class WorkerStorageContract : IWorkerStorageContract
internal class WorkerStorageContract(DaisiesDbContext dbContext, IStringLocalizer<Messages> localizer) : IWorkerStorageContract
{
private readonly DaisiesDbContext _dbContext;
private readonly Mapper _mapper;
private readonly DaisiesDbContext _dbContext = dbContext;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public WorkerStorageContract(DaisiesDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Post, PostDataModel>()
.ForMember(x => x.Id, x => x.MapFrom(src => src.PostId));
cfg.CreateMap<Worker, WorkerDataModel>();
cfg.CreateMap<WorkerDataModel, Worker>();
});
_mapper = new Mapper(config);
}
public List<WorkerDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null)
public List<WorkerDataModel> GetList(bool onlyActive = true, string? postId
= null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime?
fromEmploymentDate = null, DateTime? toEmploymentDate = null)
{
try
{
@@ -39,72 +31,82 @@ 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))];
var workers = JoinPost(query).ToList();
return workers.Select(MapToDataModel).ToList();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public WorkerDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<WorkerDataModel>(GetWorkerById(id));
var worker = GetWorkerById(id);
return worker != null ? MapToDataModel(worker) : null;
}
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)));
var worker = AddPost(_dbContext.Workers.FirstOrDefault(x => x.FIO == fio && !x.IsDeleted));
return worker != null ? MapToDataModel(worker) : null;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public void AddElement(WorkerDataModel workerDataModel)
{
try
{
_dbContext.Workers.Add(_mapper.Map<Worker>(workerDataModel));
_dbContext.Workers.Add(CustomMapper.MapObject<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(CustomMapper.MapObject(workerDataModel,
element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
@@ -115,15 +117,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 +137,34 @@ 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));
private WorkerDataModel MapToDataModel(Worker worker)
{
var dataModel = CustomMapper.MapObjectWithNull<WorkerDataModel>(worker);
dataModel._post = CustomMapper.MapObjectWithNull<PostDataModel>(worker.Post);
return dataModel;
}
private Worker MapToEntity(WorkerDataModel dataModel)
{
var worker = CustomMapper.MapObject<Worker>(dataModel);
worker.Post = CustomMapper.MapObject<Post>(dataModel._post);
worker.IsDeleted = false;
return worker;
}
}

View File

@@ -1,14 +1,13 @@
using AutoMapper;
using DaisiesContracts.DataModels;
using DaisiesContracts.Infrastructure.BuyerConfigurations;
using DaisiesContracts.Mapper;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DaisiesDatabase.Models;
[AutoMap(typeof(BuyerDataModel), ReverseMap = true)]
public class Buyer
internal class Buyer
{
[Key]
public required string Id { get; set; }
@@ -17,6 +16,7 @@ public class Buyer
[Required]
public required string PhoneNumber { get; set; }
[AlternativeName("ConfigurationModel")]
public required BuyerConfiguration Configuration { get; set; }
public double DiscountSize { 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

@@ -1,18 +1,25 @@
using AutoMapper;
using DaisiesContracts.DataModels;
using DaisiesContracts.Enum;
using DaisiesContracts.Enums;
using DaisiesContracts.Mapper;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DaisiesDatabase.Models;
[AutoMap(typeof(PostDataModel), ReverseMap = true)]
public class Post
internal class Post
{
[Key]
public string Id { get; set; } = Guid.NewGuid().ToString();
[Required]
[AlternativeName("Id")]
public required string PostId { get; set; }
[Required]
public required string PostName { get; set; }
public PostType PostType { get; set; }
public double Salary { get; set; }
[DefaultValue(DefaultValue = true)]
public bool IsActual { get; set; }
[DefaultValue(FuncName = "UtcNow")]
public DateTime ChangeDate { get; set; }
}

View File

@@ -1,6 +1,6 @@
using AutoMapper;
using DaisiesContracts.DataModels;
using DaisiesContracts.Enum;
using DaisiesContracts.Enums;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics;
@@ -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

@@ -1,12 +1,14 @@
using AutoMapper;
using DaisiesContracts.DataModels;
using System.ComponentModel.DataAnnotations;
namespace DaisiesDatabase.Models;
[AutoMap(typeof(ProductHistoryDataModel), ReverseMap = true)]
public class ProductHistory
internal class ProductHistory
{
[Key]
public string Id { get; set; } = Guid.NewGuid().ToString();
[Required]
public required string ProductId { get; set; }
public double OldPrice { get; set; }
public DateTime ChangeDate { get; set; } = DateTime.UtcNow;

View File

@@ -1,12 +1,13 @@
using DaisiesContracts.DataModels;
using DaisiesContracts.Enum;
using DaisiesContracts.Enums;
using DaisiesContracts.Mapper;
using System.ComponentModel.DataAnnotations.Schema;
namespace DaisiesDatabase.Models;
public class Sale
internal class Sale
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public string Id { get; set; }
public required string WorkerId { get; set; }
public string? BuyerId { get; set; }
public DateTime SaleDate { get; set; }
@@ -18,5 +19,6 @@ public class Sale
public Buyer? Buyer { get; set; }
[ForeignKey("SaleId")]
[AlternativeName("Products")]
public List<SaleProduct>? SaleProducts { 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

@@ -1,11 +1,13 @@
using AutoMapper;
using DaisiesContracts.DataModels;
using DaisiesContracts.Mapper;
using System.ComponentModel.DataAnnotations.Schema;
namespace DaisiesDatabase.Models;
public class Worker
internal class Worker
{
[AlternativeName("WorkerId")]
public required string Id { get; set; }
public required string FIO { 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.Enums;
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.Enums;
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

@@ -1,10 +1,11 @@
using DaisiesBuisnessLogic.Implementations;
using DaisiesBuisnessLogic.OfficePackage;
using DaisiesContracts.DataModels;
using DaisiesContracts.Enum;
using DaisiesContracts.Enums;
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.Enums;
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 DaisiesContracts.Enums;
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);
}

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