Compare commits
9 Commits
Task3_Stor
...
Task5_Sala
| Author | SHA1 | Date | |
|---|---|---|---|
| 1099d8c922 | |||
| 5ef0ef450f | |||
| 5c4f82e7b2 | |||
| 44ec32fe0f | |||
| 8a3c00c94b | |||
| e700a45762 | |||
| 54bac20e18 | |||
| 30bde774a0 | |||
| d36e722101 |
@@ -13,10 +13,10 @@ internal class PostBuisnessLogicContract(IPostStorageContract postStorageContrac
|
||||
private readonly ILogger _logger = logger;
|
||||
private readonly IPostStorageContract _postStorageContract = postStorageContract;
|
||||
|
||||
public List<PostDataModel> GetAllPosts(bool onlyActive)
|
||||
public List<PostDataModel> GetAllPosts()
|
||||
{
|
||||
_logger.LogInformation("GetAllPosts params: {onlyActive}", onlyActive);
|
||||
return _postStorageContract.GetList(onlyActive) ?? throw new NullListException();
|
||||
_logger.LogInformation("GetAllPosts");
|
||||
return _postStorageContract.GetList() ?? throw new NullListException();
|
||||
}
|
||||
|
||||
public List<PostDataModel> GetAllDataOfPost(string postId)
|
||||
|
||||
@@ -3,18 +3,22 @@ using SPiluSZharuContracts.DataModels;
|
||||
using SPiluSZharuContracts.Exceptions;
|
||||
using SPiluSZharuContracts.Extensions;
|
||||
using SPiluSZharuContracts.StorageContracts;
|
||||
using SPiluSZharuContracts.Infrastructure;
|
||||
using SPiluSZharuContracts.Infrastructure.PostConfiguration;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace SPiluSZharuBuisnessLogic.Implementations;
|
||||
|
||||
internal class SalaryBuisnessLogicContract(ISalaryStorageContract salaryStorageContract, ISaleStorageContract saleStorageContract,
|
||||
IPostStorageContract postStorageContract, IWorkerStorageContract workerStorageContract, ILogger logger) : ISalaryBuisnessLogicContract
|
||||
IPostStorageContract postStorageContract, IWorkerStorageContract workerStorageContract, ILogger logger, IConfigurationSalary сonfiguration) : ISalaryBuisnessLogicContract
|
||||
{
|
||||
private readonly ILogger _logger = logger;
|
||||
private readonly ISalaryStorageContract _salaryStorageContract = salaryStorageContract;
|
||||
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
|
||||
private readonly IPostStorageContract _postStorageContract = postStorageContract;
|
||||
private readonly IWorkerStorageContract _workerStorageContract = workerStorageContract;
|
||||
private readonly IConfigurationSalary _salaryConfiguration = сonfiguration;
|
||||
private readonly Lock _lockObject = new();
|
||||
|
||||
public List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
@@ -52,13 +56,68 @@ internal class SalaryBuisnessLogicContract(ISalaryStorageContract salaryStorageC
|
||||
var workers = _workerStorageContract.GetList() ?? throw new NullListException();
|
||||
foreach (var worker in workers)
|
||||
{
|
||||
var sales = _saleStorageContract.GetList(startDate, finishDate, workerId: worker.Id)?.Sum(x => x.Sum) ??
|
||||
throw new NullListException();
|
||||
var post = _postStorageContract.GetElementById(worker.PostId) ??
|
||||
throw new NullListException();
|
||||
var salary = post.Salary + sales * 0.1;
|
||||
var sales = _saleStorageContract.GetList(startDate, finishDate, workerId: worker.Id) ?? throw new NullListException();
|
||||
var post = _postStorageContract.GetElementById(worker.PostId) ?? throw new NullListException();
|
||||
var salary = post.ConfigurationModel switch
|
||||
{
|
||||
null => 0,
|
||||
DeliveryManPostConfiguration dpc => CalculateSalaryForDeliveryMan(sales, startDate, finishDate, dpc),
|
||||
OperatorPostConfiguration opc => CalculateSalaryForOperator(startDate, finishDate, opc),
|
||||
PostConfiguration pc => pc.Rate,
|
||||
};
|
||||
_logger.LogDebug("The employee {workerId} was paid a salary of {salary}", worker.Id, salary);
|
||||
_salaryStorageContract.AddElement(new SalaryDataModel(worker.Id, finishDate, salary));
|
||||
}
|
||||
}
|
||||
|
||||
private double CalculateSalaryForDeliveryMan(List<SaleDataModel> sales, DateTime startDate, DateTime finishDate, DeliveryManPostConfiguration config)
|
||||
{
|
||||
var calcPercent = 0.0;
|
||||
var dates = new List<DateTime>();
|
||||
for (var date = startDate; date < finishDate; date = date.AddDays(1))
|
||||
{
|
||||
dates.Add(date);
|
||||
}
|
||||
|
||||
var parallelOptions = new ParallelOptions
|
||||
{
|
||||
MaxDegreeOfParallelism = _salaryConfiguration.MaxConcurrentThreads
|
||||
};
|
||||
|
||||
Parallel.ForEach(dates, parallelOptions, date =>
|
||||
{
|
||||
var salesInDay = sales.Where(x => x.SaleDate.Date == date.Date).ToArray();
|
||||
if (salesInDay.Length > 0)
|
||||
{
|
||||
lock (_lockObject)
|
||||
{
|
||||
calcPercent += (salesInDay.Sum(x => x.Sum) / salesInDay.Length) * config.SalePercent;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
double calcBonusTask = 0;
|
||||
try
|
||||
{
|
||||
calcBonusTask = sales.Where(x => x.Sum > _salaryConfiguration.ExtraSaleSum).Sum(x => x.Sum) * config.BonusForExtraSales;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error in bonus calculation");
|
||||
}
|
||||
return config.Rate + calcPercent + calcBonusTask;
|
||||
}
|
||||
|
||||
private double CalculateSalaryForOperator(DateTime startDate, DateTime finishDate, OperatorPostConfiguration config)
|
||||
{
|
||||
try
|
||||
{
|
||||
return config.Rate + config.PersonalCountTrendPremium * _workerStorageContract.GetWorkerTrend(startDate, finishDate);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error in the operator payroll process");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="SPiluSZharuTests" />
|
||||
<InternalsVisibleTo Include="SPiluSZharuWebApi" />
|
||||
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
using SPiluSZharuContracts.AdapterContracts.OperationResponses;
|
||||
using SPiluSZharuContracts.BindingModels;
|
||||
|
||||
namespace SPiluSZharuContracts.AdapterContracts;
|
||||
|
||||
public interface IPostAdapter
|
||||
{
|
||||
PostOperationResponse GetList();
|
||||
|
||||
PostOperationResponse GetHistory(string id);
|
||||
|
||||
PostOperationResponse GetElement(string data);
|
||||
|
||||
PostOperationResponse RegisterPost(PostBindingModel postModel);
|
||||
|
||||
PostOperationResponse ChangePostInfo(PostBindingModel postModel);
|
||||
|
||||
PostOperationResponse RemovePost(string id);
|
||||
|
||||
PostOperationResponse RestorePost(string id);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using SPiluSZharuContracts.AdapterContracts.OperationResponses;
|
||||
using SPiluSZharuContracts.BindingModels;
|
||||
|
||||
namespace SPiluSZharuContracts.AdapterContracts;
|
||||
|
||||
public interface IProductAdapter
|
||||
{
|
||||
ProductOperationResponse GetList(bool includeDeleted);
|
||||
|
||||
ProductOperationResponse GetHistory(string id);
|
||||
|
||||
ProductOperationResponse GetElement(string data);
|
||||
|
||||
ProductOperationResponse RegisterProduct(ProductBindingModel productModel);
|
||||
|
||||
ProductOperationResponse ChangeProductInfo(ProductBindingModel productModel);
|
||||
|
||||
ProductOperationResponse RemoveProduct(string id);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using SPiluSZharuContracts.AdapterContracts.OperationResponses;
|
||||
using SPiluSZharuContracts.BindingModels;
|
||||
|
||||
namespace SPiluSZharuContracts.AdapterContracts;
|
||||
|
||||
public interface IRestaurantAdapter
|
||||
{
|
||||
RestaurantOperationResponse GetList();
|
||||
|
||||
RestaurantOperationResponse GetElement(string data);
|
||||
|
||||
RestaurantOperationResponse RegisterRestaurant(RestaurantBindingModel restaurantModel);
|
||||
|
||||
RestaurantOperationResponse ChangeRestaurantInfo(RestaurantBindingModel restaurantModel);
|
||||
|
||||
RestaurantOperationResponse RemoveRestaurant(string id);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using SPiluSZharuContracts.AdapterContracts.OperationResponses;
|
||||
using SPiluSZharuContracts.DataModels;
|
||||
|
||||
namespace SPiluSZharuContracts.AdapterContracts;
|
||||
|
||||
public interface ISalaryAdapter
|
||||
{
|
||||
SalaryOperationResponse GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate);
|
||||
|
||||
SalaryOperationResponse GetAllSalariesByPeriodByWorker(DateTime fromDate, DateTime toDate, string workerId);
|
||||
|
||||
SalaryOperationResponse CalculateSalaryByMounth(DateTime date);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using SPiluSZharuContracts.AdapterContracts.OperationResponses;
|
||||
using SPiluSZharuContracts.BindingModels;
|
||||
|
||||
namespace SPiluSZharuContracts.AdapterContracts;
|
||||
|
||||
public interface ISaleAdapter
|
||||
{
|
||||
SaleOperationResponse GetList(DateTime fromDate, DateTime toDate);
|
||||
|
||||
SaleOperationResponse GetWorkerList(string id, DateTime fromDate, DateTime toDate);
|
||||
|
||||
SaleOperationResponse GetRestaurantList(string id, DateTime fromDate, DateTime toDate);
|
||||
|
||||
SaleOperationResponse GetProductList(string id, DateTime fromDate, DateTime toDate);
|
||||
|
||||
SaleOperationResponse GetElement(string id);
|
||||
|
||||
SaleOperationResponse MakeSale(SaleBindingModel saleModel);
|
||||
|
||||
SaleOperationResponse CancelSale(string id);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using SPiluSZharuContracts.AdapterContracts.OperationResponses;
|
||||
using SPiluSZharuContracts.BindingModels;
|
||||
|
||||
namespace SPiluSZharuContracts.AdapterContracts;
|
||||
|
||||
public interface IWorkerAdapter
|
||||
{
|
||||
WorkerOperationResponse GetList(bool includeDeleted);
|
||||
|
||||
WorkerOperationResponse GetPostList(string id, bool includeDeleted);
|
||||
|
||||
WorkerOperationResponse GetListByBirthDate(DateTime fromDate, DateTime toDate, bool includeDeleted);
|
||||
|
||||
WorkerOperationResponse GetListByEmploymentDate(DateTime fromDate, DateTime toDate, bool includeDeleted);
|
||||
|
||||
WorkerOperationResponse GetElement(string data);
|
||||
|
||||
WorkerOperationResponse RegisterWorker(WorkerBindingModel workerModel);
|
||||
|
||||
WorkerOperationResponse ChangeWorkerInfo(WorkerBindingModel workerModel);
|
||||
|
||||
WorkerOperationResponse RemoveWorker(string id);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using SPiluSZharuContracts.Infrastructure;
|
||||
using SPiluSZharuContracts.ViewModels;
|
||||
|
||||
namespace SPiluSZharuContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class PostOperationResponse : OperationResponse
|
||||
{
|
||||
public static PostOperationResponse OK(List<PostViewModel> data) => OK<PostOperationResponse, List<PostViewModel>>(data);
|
||||
|
||||
public static PostOperationResponse OK(PostViewModel data) => OK<PostOperationResponse, PostViewModel>(data);
|
||||
|
||||
public static PostOperationResponse NoContent() => NoContent<PostOperationResponse>();
|
||||
|
||||
public static PostOperationResponse NotFound(string message) => NotFound<PostOperationResponse>(message);
|
||||
|
||||
public static PostOperationResponse BadRequest(string message) => BadRequest<PostOperationResponse>(message);
|
||||
|
||||
public static PostOperationResponse InternalServerError(string message) => InternalServerError<PostOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using SPiluSZharuContracts.Infrastructure;
|
||||
using SPiluSZharuContracts.ViewModels;
|
||||
|
||||
namespace SPiluSZharuContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class ProductOperationResponse : OperationResponse
|
||||
{
|
||||
public static ProductOperationResponse OK(List<ProductViewModel> data) => OK<ProductOperationResponse, List<ProductViewModel>>(data);
|
||||
|
||||
public static ProductOperationResponse OK(List<ProductHistoryViewModel> data) => OK<ProductOperationResponse, List<ProductHistoryViewModel>>(data);
|
||||
|
||||
public static ProductOperationResponse OK(ProductViewModel data) => OK<ProductOperationResponse, ProductViewModel>(data);
|
||||
|
||||
public static ProductOperationResponse NoContent() => NoContent<ProductOperationResponse>();
|
||||
|
||||
public static ProductOperationResponse NotFound(string message) => NotFound<ProductOperationResponse>(message);
|
||||
|
||||
public static ProductOperationResponse BadRequest(string message) => BadRequest<ProductOperationResponse>(message);
|
||||
|
||||
public static ProductOperationResponse InternalServerError(string message) => InternalServerError<ProductOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using SPiluSZharuContracts.Infrastructure;
|
||||
using SPiluSZharuContracts.ViewModels;
|
||||
|
||||
namespace SPiluSZharuContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class RestaurantOperationResponse : OperationResponse
|
||||
{
|
||||
public static RestaurantOperationResponse OK(List<RestaurantViewModel> data) => OK<RestaurantOperationResponse, List<RestaurantViewModel>>(data);
|
||||
|
||||
public static RestaurantOperationResponse OK(RestaurantViewModel data) => OK<RestaurantOperationResponse, RestaurantViewModel>(data);
|
||||
|
||||
public static RestaurantOperationResponse NoContent() => NoContent<RestaurantOperationResponse>();
|
||||
|
||||
public static RestaurantOperationResponse NotFound(string message) => NotFound<RestaurantOperationResponse>(message);
|
||||
|
||||
public static RestaurantOperationResponse BadRequest(string message) => BadRequest<RestaurantOperationResponse>(message);
|
||||
|
||||
public static RestaurantOperationResponse InternalServerError(string message) => InternalServerError<RestaurantOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using SPiluSZharuContracts.Infrastructure;
|
||||
using SPiluSZharuContracts.ViewModels;
|
||||
|
||||
namespace SPiluSZharuContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class SalaryOperationResponse : OperationResponse
|
||||
{
|
||||
public static SalaryOperationResponse OK(List<SalaryViewModel> data) => OK<SalaryOperationResponse, List<SalaryViewModel>>(data);
|
||||
|
||||
public static SalaryOperationResponse NoContent() => NoContent<SalaryOperationResponse>();
|
||||
|
||||
public static SalaryOperationResponse NotFound(string message) => NotFound<SalaryOperationResponse>(message);
|
||||
|
||||
public static SalaryOperationResponse BadRequest(string message) => BadRequest<SalaryOperationResponse>(message);
|
||||
|
||||
public static SalaryOperationResponse InternalServerError(string message) => InternalServerError<SalaryOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using SPiluSZharuContracts.Infrastructure;
|
||||
using SPiluSZharuContracts.ViewModels;
|
||||
|
||||
namespace SPiluSZharuContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class SaleOperationResponse : OperationResponse
|
||||
{
|
||||
public static SaleOperationResponse OK(List<SaleViewModel> data) => OK<SaleOperationResponse, List<SaleViewModel>>(data);
|
||||
|
||||
public static SaleOperationResponse OK(SaleViewModel data) => OK<SaleOperationResponse, SaleViewModel>(data);
|
||||
|
||||
public static SaleOperationResponse NoContent() => NoContent<SaleOperationResponse>();
|
||||
|
||||
public static SaleOperationResponse NotFound(string message) => NotFound<SaleOperationResponse>(message);
|
||||
|
||||
public static SaleOperationResponse BadRequest(string message) => BadRequest<SaleOperationResponse>(message);
|
||||
|
||||
public static SaleOperationResponse InternalServerError(string message) => InternalServerError<SaleOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using SPiluSZharuContracts.Infrastructure;
|
||||
using SPiluSZharuContracts.ViewModels;
|
||||
|
||||
namespace SPiluSZharuContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class WorkerOperationResponse : OperationResponse
|
||||
{
|
||||
public static WorkerOperationResponse OK(List<WorkerViewModel> data) => OK<WorkerOperationResponse, List<WorkerViewModel>>(data);
|
||||
|
||||
public static WorkerOperationResponse OK(WorkerViewModel data) => OK<WorkerOperationResponse, WorkerViewModel>(data);
|
||||
|
||||
public static WorkerOperationResponse NoContent() => NoContent<WorkerOperationResponse>();
|
||||
|
||||
public static WorkerOperationResponse NotFound(string message) => NotFound<WorkerOperationResponse>(message);
|
||||
|
||||
public static WorkerOperationResponse BadRequest(string message) => BadRequest<WorkerOperationResponse>(message);
|
||||
|
||||
public static WorkerOperationResponse InternalServerError(string message) => InternalServerError<WorkerOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace SPiluSZharuContracts.BindingModels;
|
||||
|
||||
public class PostBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public string? PostId => Id;
|
||||
|
||||
public string? PostName { get; set; }
|
||||
|
||||
public string? PostType { get; set; }
|
||||
|
||||
public string? ConfigurationJson { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace SPiluSZharuContracts.BindingModels;
|
||||
|
||||
public class ProductBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public string? ProductName { get; set; }
|
||||
|
||||
public string? ProductType { get; set; }
|
||||
|
||||
public double Price { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace SPiluSZharuContracts.BindingModels;
|
||||
|
||||
public class RestaurantBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public string? RestaurantName { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace SPiluSZharuContracts.BindingModels;
|
||||
|
||||
public class SaleBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public string? WorkerId { get; set; }
|
||||
|
||||
public string? RestaurantId { get; set; }
|
||||
|
||||
public List<SaleProductBindingModel>? Products { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace SPiluSZharuContracts.BindingModels;
|
||||
|
||||
public class SaleProductBindingModel
|
||||
{
|
||||
public string? SaleId { get; set; }
|
||||
|
||||
public string? ProductId { get; set; }
|
||||
|
||||
public int Count { get; set; }
|
||||
|
||||
public double Price { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
namespace SPiluSZharuContracts.BindingModels;
|
||||
|
||||
public class WorkerBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public string? FIO { get; set; }
|
||||
|
||||
public string? PostId { get; set; }
|
||||
|
||||
public string? PhoneNumber { get; set; }
|
||||
|
||||
public DateTime BirthDate { get; set; }
|
||||
|
||||
public DateTime EmploymentDate { get; set; }
|
||||
}
|
||||
@@ -4,7 +4,7 @@ namespace SPiluSZharuContracts.BuisnessLogicContracts;
|
||||
|
||||
public interface IPostBuisnessLogicContract
|
||||
{
|
||||
List<PostDataModel> GetAllPosts(bool onlyActive);
|
||||
List<PostDataModel> GetAllPosts();
|
||||
|
||||
List<PostDataModel> GetAllDataOfPost(string postId);
|
||||
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
using SPiluSZharuContracts.Enums;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json;
|
||||
using SPiluSZharuContracts.Enums;
|
||||
using SPiluSZharuContracts.Exceptions;
|
||||
using SPiluSZharuContracts.Extensions;
|
||||
using SPiluSZharuContracts.Infrastructure;
|
||||
using SPiluSZharuContracts.Infrastructure.PostConfiguration;
|
||||
|
||||
namespace SPiluSZharuContracts.DataModels;
|
||||
|
||||
public class PostDataModel(string postId, string postName, PostType postType, double salary, bool isActual, DateTime changeDate) : IValidation
|
||||
public class PostDataModel(string postId, string postName, PostType postType, PostConfiguration configuration) : IValidation
|
||||
{
|
||||
public string Id { get; private set; } = postId;
|
||||
|
||||
@@ -13,11 +16,21 @@ public class PostDataModel(string postId, string postName, PostType postType, do
|
||||
|
||||
public PostType PostType { get; private set; } = postType;
|
||||
|
||||
public double Salary { get; private set; } = salary;
|
||||
public PostConfiguration ConfigurationModel { get; private set; } = configuration;
|
||||
|
||||
public bool IsActual { get; private set; } = isActual;
|
||||
|
||||
public DateTime ChangeDate { get; private set; } = changeDate;
|
||||
public PostDataModel(string postId, string postName, PostType postType, string configurationJson) : this(postId, postName, postType, (PostConfiguration)null)
|
||||
{
|
||||
var obj = JToken.Parse(configurationJson);
|
||||
if (obj is not null)
|
||||
{
|
||||
ConfigurationModel = obj.Value<string>("Type") switch
|
||||
{
|
||||
nameof(OperatorPostConfiguration) => JsonConvert.DeserializeObject<OperatorPostConfiguration>(configurationJson)!,
|
||||
nameof(DeliveryManPostConfiguration) => JsonConvert.DeserializeObject<DeliveryManPostConfiguration>(configurationJson)!,
|
||||
_ => JsonConvert.DeserializeObject<PostConfiguration>(configurationJson)!,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
@@ -33,7 +46,10 @@ public class PostDataModel(string postId, string postName, PostType postType, do
|
||||
if (PostType == PostType.None)
|
||||
throw new ValidationException("Field PostType is empty");
|
||||
|
||||
if (Salary <= 0)
|
||||
throw new ValidationException("Field Salary is empty");
|
||||
if (ConfigurationModel is null)
|
||||
throw new ValidationException("Field ConfigurationModel is not initialized");
|
||||
|
||||
if (ConfigurationModel!.Rate <= 0)
|
||||
throw new ValidationException("Field Rate is less or equal zero");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,8 @@ public class ProductDataModel(string id, string productName, ProductType product
|
||||
|
||||
public bool IsDeleted { get; private set; } = isDeleted;
|
||||
|
||||
public ProductDataModel(string id, string productName, ProductType productType, double price) : this(id, productName, productType, price, false) { }
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (Id.IsEmpty())
|
||||
|
||||
@@ -6,12 +6,22 @@ namespace SPiluSZharuContracts.DataModels;
|
||||
|
||||
public class ProductHistoryDataModel(string productId, double oldPrice) : IValidation
|
||||
{
|
||||
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 ProductHistoryDataModel(string productId, double oldPrice, DateTime changeDate, ProductDataModel product) : this(productId, oldPrice)
|
||||
{
|
||||
ChangeDate = changeDate;
|
||||
_product = product;
|
||||
}
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (ProductId.IsEmpty())
|
||||
|
||||
@@ -14,6 +14,8 @@ public class RestaurantDataModel(string id, string restaurantName, string? prevR
|
||||
|
||||
public string? PrevPrevRestaurantName { get; private set; } = prevPrevRestaurantName;
|
||||
|
||||
public RestaurantDataModel(string id, string restaurantName) : this(id, restaurantName, null, null) { }
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (Id.IsEmpty())
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using SPiluSZharuContracts.Exceptions;
|
||||
using SPiluSZharuContracts.Enums;
|
||||
using SPiluSZharuContracts.Exceptions;
|
||||
using SPiluSZharuContracts.Extensions;
|
||||
using SPiluSZharuContracts.Infrastructure;
|
||||
|
||||
@@ -6,12 +7,21 @@ namespace SPiluSZharuContracts.DataModels;
|
||||
|
||||
public class SalaryDataModel(string workerId, DateTime salaryDate, double workerSalary) : IValidation
|
||||
{
|
||||
private readonly WorkerDataModel? _worker;
|
||||
|
||||
public string WorkerId { get; private set; } = workerId;
|
||||
|
||||
public DateTime SalaryDate { get; private set; } = salaryDate;
|
||||
|
||||
public double Salary { get; private set; } = workerSalary;
|
||||
|
||||
public string WorkerName => _worker?.FIO ?? string.Empty;
|
||||
|
||||
public SalaryDataModel(string workerId, DateTime salaryDate, double workerSalary, WorkerDataModel worker) : this(workerId, salaryDate, workerSalary)
|
||||
{
|
||||
_worker = worker;
|
||||
}
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (WorkerId.IsEmpty())
|
||||
|
||||
@@ -4,21 +4,48 @@ using SPiluSZharuContracts.Infrastructure;
|
||||
|
||||
namespace SPiluSZharuContracts.DataModels;
|
||||
|
||||
public class SaleDataModel(string id, string workerId, string? restaurantId, double sum, bool isCancel, List<SaleProductDataModel> saleProducts) : IValidation
|
||||
public class SaleDataModel : IValidation
|
||||
{
|
||||
public string Id { get; private set; } = id;
|
||||
private readonly RestaurantDataModel? _restaurant;
|
||||
|
||||
public string WorkerId { get; private set; } = workerId;
|
||||
private readonly WorkerDataModel? _worker;
|
||||
|
||||
public string? RestaurantId { get; private set; } = restaurantId;
|
||||
public string Id { get; private set; }
|
||||
|
||||
public string WorkerId { get; private set; }
|
||||
|
||||
public string? RestaurantId { get; private set; }
|
||||
|
||||
public DateTime SaleDate { get; private set; } = DateTime.UtcNow;
|
||||
|
||||
public double Sum { get; private set; } = sum;
|
||||
public double Sum { get; private set; }
|
||||
|
||||
public bool IsCancel { get; private set; } = isCancel;
|
||||
public bool IsCancel { get; private set; }
|
||||
|
||||
public List<SaleProductDataModel> Products { get; private set; } = saleProducts;
|
||||
public List<SaleProductDataModel>? Products { get; private set; }
|
||||
|
||||
public string RestaurantName => _restaurant?.RestaurantName ?? string.Empty;
|
||||
|
||||
public string WorkerFIO => _worker?.FIO ?? string.Empty;
|
||||
|
||||
public SaleDataModel(string id, string workerId, string? restaurantId, bool isCancel, List<SaleProductDataModel> saleProducts)
|
||||
{
|
||||
Id = id;
|
||||
WorkerId = workerId;
|
||||
RestaurantId = restaurantId;
|
||||
IsCancel = isCancel;
|
||||
Products = saleProducts;
|
||||
Sum = Products?.Sum(x => x.Price * x.Count) ?? 0;
|
||||
}
|
||||
|
||||
public SaleDataModel(string id, string workerId, string? restaurantId, double sum, bool isCancel, List<SaleProductDataModel> saleProducts, WorkerDataModel worker, RestaurantDataModel? restaurant) : this(id, workerId, restaurantId, isCancel, saleProducts)
|
||||
{
|
||||
Sum = sum;
|
||||
_worker = worker;
|
||||
_restaurant = restaurant;
|
||||
}
|
||||
|
||||
public SaleDataModel(string id, string workerId, string? restaurantId, List<SaleProductDataModel> products) : this(id, workerId, restaurantId, false, products) { }
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
|
||||
@@ -4,14 +4,25 @@ using SPiluSZharuContracts.Infrastructure;
|
||||
|
||||
namespace SPiluSZharuContracts.DataModels;
|
||||
|
||||
public class SaleProductDataModel(string saleId, string productId, int count) : IValidation
|
||||
public class SaleProductDataModel(string saleId, string productId, int count, double price) : IValidation
|
||||
{
|
||||
private readonly ProductDataModel? _product;
|
||||
|
||||
public string SaleId { get; private set; } = saleId;
|
||||
|
||||
public string ProductId { get; private set; } = productId;
|
||||
|
||||
public int Count { get; private set; } = count;
|
||||
|
||||
public double Price { get; private set; } = price;
|
||||
|
||||
public string ProductName => _product?.ProductName ?? string.Empty;
|
||||
|
||||
public SaleProductDataModel(string saleId, string productId, int count, double price, ProductDataModel product) : this(saleId, productId, count, price)
|
||||
{
|
||||
_product = product;
|
||||
}
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (SaleId.IsEmpty())
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using SPiluSZharuContracts.Exceptions;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using SPiluSZharuContracts.Exceptions;
|
||||
using SPiluSZharuContracts.Extensions;
|
||||
using SPiluSZharuContracts.Infrastructure;
|
||||
using System.Text.RegularExpressions;
|
||||
@@ -7,6 +8,8 @@ namespace SPiluSZharuContracts.DataModels;
|
||||
|
||||
public class WorkerDataModel(string id, string fio, string postId, string phoneNumber, DateTime birthDate, DateTime employmentDate, bool isDeleted) : IValidation
|
||||
{
|
||||
private readonly PostDataModel? _post;
|
||||
|
||||
public string Id { get; private set; } = id;
|
||||
|
||||
public string FIO { get; private set; } = fio;
|
||||
@@ -21,6 +24,15 @@ public class WorkerDataModel(string id, string fio, string postId, string phoneN
|
||||
|
||||
public bool IsDeleted { get; private set; } = isDeleted;
|
||||
|
||||
public string PostName => _post?.PostName ?? string.Empty;
|
||||
|
||||
public WorkerDataModel(string id, string fio, string postId, string phoneNumber, DateTime birthDate, DateTime employmentDate, bool isDeleted, PostDataModel post) : this(id, fio, postId, phoneNumber, birthDate, employmentDate, isDeleted)
|
||||
{
|
||||
_post = post;
|
||||
}
|
||||
|
||||
public WorkerDataModel(string id, string fio, string postId, string phoneNumber, DateTime birthDate, DateTime employmentDate) : this(id, fio, postId, phoneNumber, birthDate, employmentDate, false) { }
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (Id.IsEmpty())
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
namespace SPiluSZharuContratcs.Infrastructure;
|
||||
namespace SPiluSZharuContracts.Infrastructure;
|
||||
|
||||
public interface IConfigurationDatabase
|
||||
{
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace SPiluSZharuContracts.Infrastructure;
|
||||
|
||||
public interface IConfigurationSalary
|
||||
{
|
||||
double ExtraSaleSum { get; }
|
||||
|
||||
int MaxConcurrentThreads { get; }
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Net;
|
||||
|
||||
namespace SPiluSZharuContracts.Infrastructure;
|
||||
|
||||
public class OperationResponse
|
||||
{
|
||||
protected HttpStatusCode StatusCode { get; set; }
|
||||
|
||||
protected object? Result { get; set; }
|
||||
|
||||
public IActionResult GetResponse(HttpRequest request, HttpResponse response)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
ArgumentNullException.ThrowIfNull(response);
|
||||
|
||||
response.StatusCode = (int)StatusCode;
|
||||
|
||||
if (Result is null)
|
||||
{
|
||||
return new StatusCodeResult((int)StatusCode);
|
||||
}
|
||||
|
||||
return new ObjectResult(Result);
|
||||
}
|
||||
|
||||
protected static TResult OK<TResult, TData>(TData data) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.OK, Result = data };
|
||||
|
||||
protected static TResult NoContent<TResult>() where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.NoContent };
|
||||
|
||||
protected static TResult BadRequest<TResult>(string? errorMessage = null) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.BadRequest, Result = errorMessage };
|
||||
|
||||
protected static TResult NotFound<TResult>(string? errorMessage = null) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.NotFound, Result = errorMessage };
|
||||
|
||||
protected static TResult InternalServerError<TResult>(string? errorMessage = null) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.InternalServerError, Result = errorMessage };
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace SPiluSZharuContracts.Infrastructure.PostConfiguration;
|
||||
|
||||
public class DeliveryManPostConfiguration : PostConfiguration
|
||||
{
|
||||
public override string Type => nameof(DeliveryManPostConfiguration);
|
||||
|
||||
public double SalePercent { get; set; }
|
||||
|
||||
public double BonusForExtraSales { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace SPiluSZharuContracts.Infrastructure.PostConfiguration;
|
||||
|
||||
public class OperatorPostConfiguration : PostConfiguration
|
||||
{
|
||||
public override string Type => nameof(OperatorPostConfiguration);
|
||||
|
||||
public double PersonalCountTrendPremium { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace SPiluSZharuContracts.Infrastructure.PostConfiguration;
|
||||
|
||||
public class PostConfiguration
|
||||
{
|
||||
public virtual string Type => nameof(PostConfiguration);
|
||||
|
||||
public double Rate { get; set; }
|
||||
}
|
||||
@@ -7,6 +7,8 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.3.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.3.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.2" />
|
||||
<PackageReference Include="Moq" Version="4.20.72" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -4,7 +4,7 @@ namespace SPiluSZharuContracts.StorageContracts;
|
||||
|
||||
public interface IPostStorageContract
|
||||
{
|
||||
List<PostDataModel> GetList(bool onlyActual = true);
|
||||
List<PostDataModel> GetList();
|
||||
|
||||
List<PostDataModel> GetPostWithHistory(string postId);
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ namespace SPiluSZharuContracts.StorageContracts;
|
||||
|
||||
public interface ISalaryStorageContract
|
||||
{
|
||||
List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? workerId = null);
|
||||
List<SalaryDataModel> GetList(DateTime? startDate, DateTime? endDate, string? workerId = null);
|
||||
|
||||
void AddElement(SalaryDataModel salaryDataModel);
|
||||
}
|
||||
|
||||
@@ -18,4 +18,6 @@ public interface IWorkerStorageContract
|
||||
void UpdElement(WorkerDataModel workerDataModel);
|
||||
|
||||
void DelElement(string id);
|
||||
|
||||
int GetWorkerTrend(DateTime fromPeriod, DateTime toPeriod);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace SPiluSZharuContracts.ViewModels;
|
||||
|
||||
public class PostViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string PostName { get; set; }
|
||||
|
||||
public required string PostType { get; set; }
|
||||
|
||||
public required string Configuration { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace SPiluSZharuContracts.ViewModels;
|
||||
|
||||
public class ProductHistoryViewModel
|
||||
{
|
||||
public required string ProductName { get; set; }
|
||||
|
||||
public double OldPrice { get; set; }
|
||||
|
||||
public DateTime ChangeDate { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace SPiluSZharuContracts.ViewModels;
|
||||
|
||||
public class ProductViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string ProductName { get; set; }
|
||||
|
||||
public required string ProductType { get; set; }
|
||||
|
||||
public double Price { get; set; }
|
||||
|
||||
public bool IsDeleted { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace SPiluSZharuContracts.ViewModels;
|
||||
|
||||
public class RestaurantViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string RestaurantName { get; set; }
|
||||
|
||||
public string? PrevRestaurantName { get; set; }
|
||||
|
||||
public string? PrevPrevRestaurantName { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace SPiluSZharuContracts.ViewModels;
|
||||
|
||||
public class SalaryViewModel
|
||||
{
|
||||
public required string WorkerId { get; set; }
|
||||
|
||||
public required string WorkerFIO { get; set; }
|
||||
|
||||
public DateTime SalaryDate { get; set; }
|
||||
|
||||
public double Salary { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace SPiluSZharuContracts.ViewModels;
|
||||
|
||||
public class SaleProductViewModel
|
||||
{
|
||||
public required string ProductId { get; set; }
|
||||
|
||||
public required string ProductName { get; set; }
|
||||
|
||||
public int Count { get; set; }
|
||||
|
||||
public double Price { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
namespace SPiluSZharuContracts.ViewModels;
|
||||
|
||||
public class SaleViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string WorkerId { get; set; }
|
||||
|
||||
public required string WorkerFIO { get; set; }
|
||||
|
||||
public string? RestaurantId { get; set; }
|
||||
|
||||
public string? RestaurantName { get; set; }
|
||||
|
||||
public DateTime SaleDate { get; set; }
|
||||
|
||||
public double Sum { get; set; }
|
||||
|
||||
public bool IsCancel { get; set; }
|
||||
|
||||
public required List<SaleProductViewModel> Products { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
namespace SPiluSZharuContracts.ViewModels;
|
||||
|
||||
public class WorkerViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string FIO { get; set; }
|
||||
|
||||
public required string PostId { get; set; }
|
||||
|
||||
public required string PostName { get; set; }
|
||||
|
||||
public required string PhoneNumber { get; set; }
|
||||
|
||||
public bool IsDeleted { get; set; }
|
||||
|
||||
public DateTime BirthDate { get; set; }
|
||||
|
||||
public DateTime EmploymentDate { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using SPiluSZharuContracts.Infrastructure;
|
||||
|
||||
namespace SPiluSZharuDatabase;
|
||||
|
||||
class DefaultConfigurationDatabase : IConfigurationDatabase
|
||||
{
|
||||
public string ConnectionString => "";
|
||||
}
|
||||
@@ -24,21 +24,17 @@ internal class PostStorageContract : IPostStorageContract
|
||||
.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));
|
||||
.ForMember(x => x.ChangeDate, x => x.MapFrom(src => DateTime.UtcNow))
|
||||
.ForMember(x => x.Configuration, x => x.MapFrom(src => src.ConfigurationModel));
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<PostDataModel> GetList(bool onlyActual = true)
|
||||
public List<PostDataModel> GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
var query = _dbContext.Posts.AsQueryable();
|
||||
if (onlyActual)
|
||||
{
|
||||
query = query.Where(x => x.IsActual);
|
||||
}
|
||||
return [.. query.Select(x => _mapper.Map<PostDataModel>(x))];
|
||||
return [.. _dbContext.Posts.Select(x => _mapper.Map<PostDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
@@ -48,7 +48,7 @@ internal class ProductStorageContract : IProductStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
return [.. _dbContext.ProductHistories.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 => _mapper.Map<ProductHistoryDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using AutoMapper;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SPiluSZharuContracts.DataModels;
|
||||
using SPiluSZharuContracts.Exceptions;
|
||||
using SPiluSZharuContracts.StorageContracts;
|
||||
@@ -16,6 +17,7 @@ internal class SalaryStorageContract : ISalaryStorageContract
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Worker, WorkerDataModel>();
|
||||
cfg.CreateMap<Salary, SalaryDataModel>();
|
||||
cfg.CreateMap<SalaryDataModel, Salary>()
|
||||
.ForMember(dest => dest.WorkerSalary, opt => opt.MapFrom(src => src.Salary));
|
||||
@@ -23,15 +25,17 @@ internal class SalaryStorageContract : ISalaryStorageContract
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? workerId = null)
|
||||
public List<SalaryDataModel> GetList(DateTime? startDate, DateTime? endDate, string? workerId = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var query = _dbContext.Salaries.Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate);
|
||||
if (workerId is not null)
|
||||
{
|
||||
var query = _dbContext.Salaries.Include(x => x.Worker).AsQueryable();
|
||||
if (startDate.HasValue)
|
||||
query = query.Where(x => x.SalaryDate >= DateTime.SpecifyKind(startDate ?? DateTime.UtcNow, DateTimeKind.Utc));
|
||||
if (endDate.HasValue)
|
||||
query = query.Where(x => x.SalaryDate <= DateTime.SpecifyKind(endDate ?? DateTime.UtcNow, DateTimeKind.Utc));
|
||||
if (workerId != null)
|
||||
query = query.Where(x => x.WorkerId == workerId);
|
||||
}
|
||||
return [.. query.Select(x => _mapper.Map<SalaryDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -4,6 +4,7 @@ using SPiluSZharuContracts.DataModels;
|
||||
using SPiluSZharuContracts.Exceptions;
|
||||
using SPiluSZharuContracts.StorageContracts;
|
||||
using SPiluSZharuDatabase.Models;
|
||||
using System;
|
||||
|
||||
namespace SPiluSZharuDatabase.Implementations;
|
||||
|
||||
@@ -17,6 +18,9 @@ internal class SaleStorageContract : ISaleStorageContract
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Restaurant, RestaurantDataModel>();
|
||||
cfg.CreateMap<Product, ProductDataModel>();
|
||||
cfg.CreateMap<Worker, WorkerDataModel>();
|
||||
cfg.CreateMap<SaleProduct, SaleProductDataModel>();
|
||||
cfg.CreateMap<SaleProductDataModel, SaleProduct>();
|
||||
cfg.CreateMap<Sale, SaleDataModel>();
|
||||
@@ -31,7 +35,7 @@ internal class SaleStorageContract : ISaleStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
var query = _dbContext.Sales.Include(x => x.SaleProducts).AsQueryable();
|
||||
var query = _dbContext.Sales.Include(x => x.Restaurant).Include(x => x.Worker).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);
|
||||
@@ -108,5 +112,5 @@ internal class SaleStorageContract : ISaleStorageContract
|
||||
}
|
||||
}
|
||||
|
||||
private Sale? GetSaleById(string id) => _dbContext.Sales.FirstOrDefault(x => x.Id == id);
|
||||
private Sale? GetSaleById(string id) => _dbContext.Sales.Include(x => x.Restaurant).Include(x => x.Worker).Include(x => x.SaleProducts)!.ThenInclude(x => x.Product).FirstOrDefault(x => x.Id == id);
|
||||
}
|
||||
|
||||
@@ -16,6 +16,8 @@ internal class WorkerStorageContract : IWorkerStorageContract
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Post, PostDataModel>()
|
||||
.ForMember(x => x.Id, x => x.MapFrom(src => src.PostId));
|
||||
cfg.AddMaps(typeof(SPiluSZharuDbContext).Assembly);
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
@@ -42,7 +44,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
|
||||
{
|
||||
query = query.Where(x => x.EmploymentDate >= fromEmploymentDate && x.EmploymentDate <= toEmploymentDate);
|
||||
}
|
||||
return [.. query.Select(x => _mapper.Map<WorkerDataModel>(x))];
|
||||
return [.. JoinPost(query).Select(x => _mapper.Map<WorkerDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -68,7 +70,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<WorkerDataModel>(_dbContext.Workers.FirstOrDefault(x => x.FIO == fio));
|
||||
return _mapper.Map<WorkerDataModel>(AddPost(_dbContext.Workers.FirstOrDefault(x => x.FIO == fio && !x.IsDeleted)));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -81,7 +83,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<WorkerDataModel>(_dbContext.Workers.FirstOrDefault(x => x.PhoneNumber == phoneNumber));
|
||||
return _mapper.Map<WorkerDataModel>(AddPost(_dbContext.Workers.FirstOrDefault(x => x.PhoneNumber == phoneNumber && !x.IsDeleted)));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -135,6 +137,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
|
||||
{
|
||||
var element = GetWorkerById(id) ?? throw new ElementNotFoundException(id);
|
||||
element.IsDeleted = true;
|
||||
element.DateOfDelete = DateTime.UtcNow;
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (ElementNotFoundException)
|
||||
@@ -149,5 +152,27 @@ internal class WorkerStorageContract : IWorkerStorageContract
|
||||
}
|
||||
}
|
||||
|
||||
private Worker? GetWorkerById(string id) => _dbContext.Workers.FirstOrDefault(x => x.Id == id && !x.IsDeleted);
|
||||
public int GetWorkerTrend(DateTime fromPeriod, DateTime toPeriod)
|
||||
{
|
||||
try
|
||||
{
|
||||
var countWorkersOnBegining = _dbContext.Workers.Count(x => x.EmploymentDate < fromPeriod && (!x.IsDeleted || x.DateOfDelete > fromPeriod));
|
||||
var countWorkersOnEnding = _dbContext.Workers.Count(x => x.EmploymentDate < toPeriod && (!x.IsDeleted || x.DateOfDelete > toPeriod));
|
||||
return countWorkersOnEnding - countWorkersOnBegining;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private Worker? GetWorkerById(string id) => AddPost(_dbContext.Workers.FirstOrDefault(x => x.Id == id && !x.IsDeleted));
|
||||
|
||||
private IQueryable<Worker> JoinPost(IQueryable<Worker> query)
|
||||
=> query.GroupJoin(_dbContext.Posts.Where(x => x.IsActual), x => x.PostId, y => y.PostId, (x, y) => new { Worker = x, Post = y })
|
||||
.SelectMany(xy => xy.Post.DefaultIfEmpty(), (x, y) => x.Worker.AddPost(y));
|
||||
|
||||
private Worker? AddPost(Worker? worker)
|
||||
=> worker?.AddPost(_dbContext.Posts.FirstOrDefault(x => x.PostId == worker.PostId && x.IsActual));
|
||||
}
|
||||
|
||||
324
SPiluSZharuProject/SPiluSZharuDatabase/Migrations/20250422183326_FirstMigration.Designer.cs
generated
Normal file
324
SPiluSZharuProject/SPiluSZharuDatabase/Migrations/20250422183326_FirstMigration.Designer.cs
generated
Normal file
@@ -0,0 +1,324 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
using SPiluSZharuDatabase;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SPiluSZharuDatabase.Migrations
|
||||
{
|
||||
[DbContext(typeof(SPiluSZharuDbContext))]
|
||||
[Migration("20250422183326_FirstMigration")]
|
||||
partial class FirstMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "9.0.3")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Post", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("ChangeDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<bool>("IsActual")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("PostId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PostName")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("PostType")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<double>("Salary")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PostId", "IsActual")
|
||||
.IsUnique()
|
||||
.HasFilter("\"IsActual\" = TRUE");
|
||||
|
||||
b.HasIndex("PostName", "IsActual")
|
||||
.IsUnique()
|
||||
.HasFilter("\"IsActual\" = TRUE");
|
||||
|
||||
b.ToTable("Posts");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Product", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("IsDeleted")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<double>("Price")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<string>("ProductName")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("ProductType")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ProductName", "IsDeleted")
|
||||
.IsUnique()
|
||||
.HasFilter("\"IsDeleted\" = FALSE");
|
||||
|
||||
b.ToTable("Products");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.ProductHistory", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("ChangeDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<double>("OldPrice")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<string>("ProductId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ProductId");
|
||||
|
||||
b.ToTable("ProductHistories");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Restaurant", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PrevPrevRestaurantName")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PrevRestaurantName")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("RestaurantName")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("RestaurantName")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Restaurants");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Salary", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("SalaryDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<string>("WorkerId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<double>("WorkerSalary")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("WorkerId");
|
||||
|
||||
b.ToTable("Salaries");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Sale", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("IsCancel")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("RestaurantId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("SaleDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<double>("Sum")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<string>("WorkerId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("RestaurantId");
|
||||
|
||||
b.HasIndex("WorkerId");
|
||||
|
||||
b.ToTable("Sales");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.SaleProduct", b =>
|
||||
{
|
||||
b.Property<string>("SaleId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ProductId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Count")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<double>("Price")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.HasKey("SaleId", "ProductId");
|
||||
|
||||
b.HasIndex("ProductId");
|
||||
|
||||
b.ToTable("SaleProducts");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Worker", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("BirthDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<DateTime>("EmploymentDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<string>("FIO")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("IsDeleted")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("PhoneNumber")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PostId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PhoneNumber")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Workers");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.ProductHistory", b =>
|
||||
{
|
||||
b.HasOne("SPiluSZharuDatabase.Models.Product", "Product")
|
||||
.WithMany("ProductHistories")
|
||||
.HasForeignKey("ProductId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Product");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Salary", b =>
|
||||
{
|
||||
b.HasOne("SPiluSZharuDatabase.Models.Worker", "Worker")
|
||||
.WithMany("Salaries")
|
||||
.HasForeignKey("WorkerId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Worker");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Sale", b =>
|
||||
{
|
||||
b.HasOne("SPiluSZharuDatabase.Models.Restaurant", "Restaurant")
|
||||
.WithMany()
|
||||
.HasForeignKey("RestaurantId");
|
||||
|
||||
b.HasOne("SPiluSZharuDatabase.Models.Worker", "Worker")
|
||||
.WithMany("Sales")
|
||||
.HasForeignKey("WorkerId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Restaurant");
|
||||
|
||||
b.Navigation("Worker");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.SaleProduct", b =>
|
||||
{
|
||||
b.HasOne("SPiluSZharuDatabase.Models.Product", "Product")
|
||||
.WithMany("SaleProducts")
|
||||
.HasForeignKey("ProductId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("SPiluSZharuDatabase.Models.Sale", "Sale")
|
||||
.WithMany("SaleProducts")
|
||||
.HasForeignKey("SaleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Product");
|
||||
|
||||
b.Navigation("Sale");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Product", b =>
|
||||
{
|
||||
b.Navigation("ProductHistories");
|
||||
|
||||
b.Navigation("SaleProducts");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Sale", b =>
|
||||
{
|
||||
b.Navigation("SaleProducts");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Worker", b =>
|
||||
{
|
||||
b.Navigation("Salaries");
|
||||
|
||||
b.Navigation("Sales");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SPiluSZharuDatabase.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class FirstMigration : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Posts",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<string>(type: "text", nullable: false),
|
||||
PostId = table.Column<string>(type: "text", nullable: false),
|
||||
PostName = table.Column<string>(type: "text", nullable: false),
|
||||
PostType = table.Column<int>(type: "integer", nullable: false),
|
||||
Salary = table.Column<double>(type: "double precision", nullable: false),
|
||||
IsActual = table.Column<bool>(type: "boolean", nullable: false),
|
||||
ChangeDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Posts", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Products",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<string>(type: "text", nullable: false),
|
||||
ProductName = table.Column<string>(type: "text", nullable: false),
|
||||
ProductType = table.Column<int>(type: "integer", nullable: false),
|
||||
Price = table.Column<double>(type: "double precision", nullable: false),
|
||||
IsDeleted = table.Column<bool>(type: "boolean", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Products", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Restaurants",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<string>(type: "text", nullable: false),
|
||||
RestaurantName = table.Column<string>(type: "text", nullable: false),
|
||||
PrevRestaurantName = table.Column<string>(type: "text", nullable: true),
|
||||
PrevPrevRestaurantName = table.Column<string>(type: "text", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Restaurants", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Workers",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<string>(type: "text", nullable: false),
|
||||
FIO = table.Column<string>(type: "text", nullable: false),
|
||||
PostId = table.Column<string>(type: "text", nullable: false),
|
||||
PhoneNumber = table.Column<string>(type: "text", nullable: false),
|
||||
BirthDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
|
||||
EmploymentDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
|
||||
IsDeleted = table.Column<bool>(type: "boolean", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Workers", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "ProductHistories",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<string>(type: "text", nullable: false),
|
||||
ProductId = table.Column<string>(type: "text", nullable: false),
|
||||
OldPrice = table.Column<double>(type: "double precision", nullable: false),
|
||||
ChangeDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_ProductHistories", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_ProductHistories_Products_ProductId",
|
||||
column: x => x.ProductId,
|
||||
principalTable: "Products",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Salaries",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<string>(type: "text", nullable: false),
|
||||
WorkerId = table.Column<string>(type: "text", nullable: false),
|
||||
SalaryDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
|
||||
WorkerSalary = table.Column<double>(type: "double precision", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Salaries", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_Salaries_Workers_WorkerId",
|
||||
column: x => x.WorkerId,
|
||||
principalTable: "Workers",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Sales",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<string>(type: "text", nullable: false),
|
||||
WorkerId = table.Column<string>(type: "text", nullable: false),
|
||||
RestaurantId = table.Column<string>(type: "text", nullable: true),
|
||||
SaleDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
|
||||
Sum = table.Column<double>(type: "double precision", nullable: false),
|
||||
IsCancel = table.Column<bool>(type: "boolean", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Sales", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_Sales_Restaurants_RestaurantId",
|
||||
column: x => x.RestaurantId,
|
||||
principalTable: "Restaurants",
|
||||
principalColumn: "Id");
|
||||
table.ForeignKey(
|
||||
name: "FK_Sales_Workers_WorkerId",
|
||||
column: x => x.WorkerId,
|
||||
principalTable: "Workers",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "SaleProducts",
|
||||
columns: table => new
|
||||
{
|
||||
SaleId = table.Column<string>(type: "text", nullable: false),
|
||||
ProductId = table.Column<string>(type: "text", nullable: false),
|
||||
Count = table.Column<int>(type: "integer", nullable: false),
|
||||
Price = table.Column<double>(type: "double precision", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_SaleProducts", x => new { x.SaleId, x.ProductId });
|
||||
table.ForeignKey(
|
||||
name: "FK_SaleProducts_Products_ProductId",
|
||||
column: x => x.ProductId,
|
||||
principalTable: "Products",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
table.ForeignKey(
|
||||
name: "FK_SaleProducts_Sales_SaleId",
|
||||
column: x => x.SaleId,
|
||||
principalTable: "Sales",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Posts_PostId_IsActual",
|
||||
table: "Posts",
|
||||
columns: new[] { "PostId", "IsActual" },
|
||||
unique: true,
|
||||
filter: "\"IsActual\" = TRUE");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Posts_PostName_IsActual",
|
||||
table: "Posts",
|
||||
columns: new[] { "PostName", "IsActual" },
|
||||
unique: true,
|
||||
filter: "\"IsActual\" = TRUE");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_ProductHistories_ProductId",
|
||||
table: "ProductHistories",
|
||||
column: "ProductId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Products_ProductName_IsDeleted",
|
||||
table: "Products",
|
||||
columns: new[] { "ProductName", "IsDeleted" },
|
||||
unique: true,
|
||||
filter: "\"IsDeleted\" = FALSE");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Restaurants_RestaurantName",
|
||||
table: "Restaurants",
|
||||
column: "RestaurantName",
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Salaries_WorkerId",
|
||||
table: "Salaries",
|
||||
column: "WorkerId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_SaleProducts_ProductId",
|
||||
table: "SaleProducts",
|
||||
column: "ProductId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Sales_RestaurantId",
|
||||
table: "Sales",
|
||||
column: "RestaurantId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Sales_WorkerId",
|
||||
table: "Sales",
|
||||
column: "WorkerId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Workers_PhoneNumber",
|
||||
table: "Workers",
|
||||
column: "PhoneNumber",
|
||||
unique: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "Posts");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "ProductHistories");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Salaries");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "SaleProducts");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Products");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Sales");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Restaurants");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Workers");
|
||||
}
|
||||
}
|
||||
}
|
||||
325
SPiluSZharuProject/SPiluSZharuDatabase/Migrations/20250423150347_ChangeFieldsInPost.Designer.cs
generated
Normal file
325
SPiluSZharuProject/SPiluSZharuDatabase/Migrations/20250423150347_ChangeFieldsInPost.Designer.cs
generated
Normal file
@@ -0,0 +1,325 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
using SPiluSZharuDatabase;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SPiluSZharuDatabase.Migrations
|
||||
{
|
||||
[DbContext(typeof(SPiluSZharuDbContext))]
|
||||
[Migration("20250423150347_ChangeFieldsInPost")]
|
||||
partial class ChangeFieldsInPost
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "9.0.3")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Post", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("ChangeDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<string>("Configuration")
|
||||
.IsRequired()
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
b.Property<bool>("IsActual")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("PostId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PostName")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("PostType")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PostId", "IsActual")
|
||||
.IsUnique()
|
||||
.HasFilter("\"IsActual\" = TRUE");
|
||||
|
||||
b.HasIndex("PostName", "IsActual")
|
||||
.IsUnique()
|
||||
.HasFilter("\"IsActual\" = TRUE");
|
||||
|
||||
b.ToTable("Posts");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Product", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("IsDeleted")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<double>("Price")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<string>("ProductName")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("ProductType")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ProductName", "IsDeleted")
|
||||
.IsUnique()
|
||||
.HasFilter("\"IsDeleted\" = FALSE");
|
||||
|
||||
b.ToTable("Products");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.ProductHistory", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("ChangeDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<double>("OldPrice")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<string>("ProductId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ProductId");
|
||||
|
||||
b.ToTable("ProductHistories");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Restaurant", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PrevPrevRestaurantName")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PrevRestaurantName")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("RestaurantName")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("RestaurantName")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Restaurants");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Salary", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("SalaryDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<string>("WorkerId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<double>("WorkerSalary")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("WorkerId");
|
||||
|
||||
b.ToTable("Salaries");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Sale", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("IsCancel")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("RestaurantId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("SaleDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<double>("Sum")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<string>("WorkerId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("RestaurantId");
|
||||
|
||||
b.HasIndex("WorkerId");
|
||||
|
||||
b.ToTable("Sales");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.SaleProduct", b =>
|
||||
{
|
||||
b.Property<string>("SaleId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ProductId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Count")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<double>("Price")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.HasKey("SaleId", "ProductId");
|
||||
|
||||
b.HasIndex("ProductId");
|
||||
|
||||
b.ToTable("SaleProducts");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Worker", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("BirthDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<DateTime>("EmploymentDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<string>("FIO")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("IsDeleted")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("PhoneNumber")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PostId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PhoneNumber")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Workers");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.ProductHistory", b =>
|
||||
{
|
||||
b.HasOne("SPiluSZharuDatabase.Models.Product", "Product")
|
||||
.WithMany("ProductHistories")
|
||||
.HasForeignKey("ProductId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Product");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Salary", b =>
|
||||
{
|
||||
b.HasOne("SPiluSZharuDatabase.Models.Worker", "Worker")
|
||||
.WithMany("Salaries")
|
||||
.HasForeignKey("WorkerId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Worker");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Sale", b =>
|
||||
{
|
||||
b.HasOne("SPiluSZharuDatabase.Models.Restaurant", "Restaurant")
|
||||
.WithMany()
|
||||
.HasForeignKey("RestaurantId");
|
||||
|
||||
b.HasOne("SPiluSZharuDatabase.Models.Worker", "Worker")
|
||||
.WithMany("Sales")
|
||||
.HasForeignKey("WorkerId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Restaurant");
|
||||
|
||||
b.Navigation("Worker");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.SaleProduct", b =>
|
||||
{
|
||||
b.HasOne("SPiluSZharuDatabase.Models.Product", "Product")
|
||||
.WithMany("SaleProducts")
|
||||
.HasForeignKey("ProductId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("SPiluSZharuDatabase.Models.Sale", "Sale")
|
||||
.WithMany("SaleProducts")
|
||||
.HasForeignKey("SaleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Product");
|
||||
|
||||
b.Navigation("Sale");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Product", b =>
|
||||
{
|
||||
b.Navigation("ProductHistories");
|
||||
|
||||
b.Navigation("SaleProducts");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Sale", b =>
|
||||
{
|
||||
b.Navigation("SaleProducts");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Worker", b =>
|
||||
{
|
||||
b.Navigation("Salaries");
|
||||
|
||||
b.Navigation("Sales");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SPiluSZharuDatabase.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class ChangeFieldsInPost : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "Salary",
|
||||
table: "Posts");
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "Configuration",
|
||||
table: "Posts",
|
||||
type: "jsonb",
|
||||
nullable: false,
|
||||
defaultValue: "{\"Rate\": 0, \"Type\": \"PostConfiguration\"}");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "Configuration",
|
||||
table: "Posts");
|
||||
|
||||
migrationBuilder.AddColumn<double>(
|
||||
name: "Salary",
|
||||
table: "Posts",
|
||||
type: "double precision",
|
||||
nullable: false,
|
||||
defaultValue: 0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
328
SPiluSZharuProject/SPiluSZharuDatabase/Migrations/20250423193249_AddDateOfDeleteInWorker.Designer.cs
generated
Normal file
328
SPiluSZharuProject/SPiluSZharuDatabase/Migrations/20250423193249_AddDateOfDeleteInWorker.Designer.cs
generated
Normal file
@@ -0,0 +1,328 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
using SPiluSZharuDatabase;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SPiluSZharuDatabase.Migrations
|
||||
{
|
||||
[DbContext(typeof(SPiluSZharuDbContext))]
|
||||
[Migration("20250423193249_AddDateOfDeleteInWorker")]
|
||||
partial class AddDateOfDeleteInWorker
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "9.0.3")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Post", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("ChangeDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<string>("Configuration")
|
||||
.IsRequired()
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
b.Property<bool>("IsActual")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("PostId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PostName")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("PostType")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PostId", "IsActual")
|
||||
.IsUnique()
|
||||
.HasFilter("\"IsActual\" = TRUE");
|
||||
|
||||
b.HasIndex("PostName", "IsActual")
|
||||
.IsUnique()
|
||||
.HasFilter("\"IsActual\" = TRUE");
|
||||
|
||||
b.ToTable("Posts");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Product", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("IsDeleted")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<double>("Price")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<string>("ProductName")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("ProductType")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ProductName", "IsDeleted")
|
||||
.IsUnique()
|
||||
.HasFilter("\"IsDeleted\" = FALSE");
|
||||
|
||||
b.ToTable("Products");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.ProductHistory", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("ChangeDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<double>("OldPrice")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<string>("ProductId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ProductId");
|
||||
|
||||
b.ToTable("ProductHistories");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Restaurant", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PrevPrevRestaurantName")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PrevRestaurantName")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("RestaurantName")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("RestaurantName")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Restaurants");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Salary", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("SalaryDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<string>("WorkerId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<double>("WorkerSalary")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("WorkerId");
|
||||
|
||||
b.ToTable("Salaries");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Sale", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("IsCancel")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("RestaurantId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("SaleDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<double>("Sum")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<string>("WorkerId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("RestaurantId");
|
||||
|
||||
b.HasIndex("WorkerId");
|
||||
|
||||
b.ToTable("Sales");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.SaleProduct", b =>
|
||||
{
|
||||
b.Property<string>("SaleId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ProductId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Count")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<double>("Price")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.HasKey("SaleId", "ProductId");
|
||||
|
||||
b.HasIndex("ProductId");
|
||||
|
||||
b.ToTable("SaleProducts");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Worker", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("BirthDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<DateTime?>("DateOfDelete")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<DateTime>("EmploymentDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<string>("FIO")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("IsDeleted")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("PhoneNumber")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PostId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PhoneNumber")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Workers");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.ProductHistory", b =>
|
||||
{
|
||||
b.HasOne("SPiluSZharuDatabase.Models.Product", "Product")
|
||||
.WithMany("ProductHistories")
|
||||
.HasForeignKey("ProductId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Product");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Salary", b =>
|
||||
{
|
||||
b.HasOne("SPiluSZharuDatabase.Models.Worker", "Worker")
|
||||
.WithMany("Salaries")
|
||||
.HasForeignKey("WorkerId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Worker");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Sale", b =>
|
||||
{
|
||||
b.HasOne("SPiluSZharuDatabase.Models.Restaurant", "Restaurant")
|
||||
.WithMany()
|
||||
.HasForeignKey("RestaurantId");
|
||||
|
||||
b.HasOne("SPiluSZharuDatabase.Models.Worker", "Worker")
|
||||
.WithMany("Sales")
|
||||
.HasForeignKey("WorkerId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Restaurant");
|
||||
|
||||
b.Navigation("Worker");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.SaleProduct", b =>
|
||||
{
|
||||
b.HasOne("SPiluSZharuDatabase.Models.Product", "Product")
|
||||
.WithMany("SaleProducts")
|
||||
.HasForeignKey("ProductId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("SPiluSZharuDatabase.Models.Sale", "Sale")
|
||||
.WithMany("SaleProducts")
|
||||
.HasForeignKey("SaleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Product");
|
||||
|
||||
b.Navigation("Sale");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Product", b =>
|
||||
{
|
||||
b.Navigation("ProductHistories");
|
||||
|
||||
b.Navigation("SaleProducts");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Sale", b =>
|
||||
{
|
||||
b.Navigation("SaleProducts");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Worker", b =>
|
||||
{
|
||||
b.Navigation("Salaries");
|
||||
|
||||
b.Navigation("Sales");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SPiluSZharuDatabase.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddDateOfDeleteInWorker : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<DateTime>(
|
||||
name: "DateOfDelete",
|
||||
table: "Workers",
|
||||
type: "timestamp without time zone",
|
||||
nullable: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "DateOfDelete",
|
||||
table: "Workers");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
using SPiluSZharuDatabase;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SPiluSZharuDatabase.Migrations
|
||||
{
|
||||
[DbContext(typeof(SPiluSZharuDbContext))]
|
||||
partial class SPiluSZharuDbContextModelSnapshot : ModelSnapshot
|
||||
{
|
||||
protected override void BuildModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "9.0.3")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Post", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("ChangeDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<string>("Configuration")
|
||||
.IsRequired()
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
b.Property<bool>("IsActual")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("PostId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PostName")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("PostType")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PostId", "IsActual")
|
||||
.IsUnique()
|
||||
.HasFilter("\"IsActual\" = TRUE");
|
||||
|
||||
b.HasIndex("PostName", "IsActual")
|
||||
.IsUnique()
|
||||
.HasFilter("\"IsActual\" = TRUE");
|
||||
|
||||
b.ToTable("Posts");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Product", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("IsDeleted")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<double>("Price")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<string>("ProductName")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("ProductType")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ProductName", "IsDeleted")
|
||||
.IsUnique()
|
||||
.HasFilter("\"IsDeleted\" = FALSE");
|
||||
|
||||
b.ToTable("Products");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.ProductHistory", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("ChangeDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<double>("OldPrice")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<string>("ProductId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ProductId");
|
||||
|
||||
b.ToTable("ProductHistories");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Restaurant", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PrevPrevRestaurantName")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PrevRestaurantName")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("RestaurantName")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("RestaurantName")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Restaurants");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Salary", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("SalaryDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<string>("WorkerId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<double>("WorkerSalary")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("WorkerId");
|
||||
|
||||
b.ToTable("Salaries");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Sale", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("IsCancel")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("RestaurantId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("SaleDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<double>("Sum")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<string>("WorkerId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("RestaurantId");
|
||||
|
||||
b.HasIndex("WorkerId");
|
||||
|
||||
b.ToTable("Sales");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.SaleProduct", b =>
|
||||
{
|
||||
b.Property<string>("SaleId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ProductId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Count")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<double>("Price")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.HasKey("SaleId", "ProductId");
|
||||
|
||||
b.HasIndex("ProductId");
|
||||
|
||||
b.ToTable("SaleProducts");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Worker", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("BirthDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<DateTime?>("DateOfDelete")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<DateTime>("EmploymentDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<string>("FIO")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("IsDeleted")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("PhoneNumber")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PostId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PhoneNumber")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Workers");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.ProductHistory", b =>
|
||||
{
|
||||
b.HasOne("SPiluSZharuDatabase.Models.Product", "Product")
|
||||
.WithMany("ProductHistories")
|
||||
.HasForeignKey("ProductId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Product");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Salary", b =>
|
||||
{
|
||||
b.HasOne("SPiluSZharuDatabase.Models.Worker", "Worker")
|
||||
.WithMany("Salaries")
|
||||
.HasForeignKey("WorkerId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Worker");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Sale", b =>
|
||||
{
|
||||
b.HasOne("SPiluSZharuDatabase.Models.Restaurant", "Restaurant")
|
||||
.WithMany()
|
||||
.HasForeignKey("RestaurantId");
|
||||
|
||||
b.HasOne("SPiluSZharuDatabase.Models.Worker", "Worker")
|
||||
.WithMany("Sales")
|
||||
.HasForeignKey("WorkerId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Restaurant");
|
||||
|
||||
b.Navigation("Worker");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.SaleProduct", b =>
|
||||
{
|
||||
b.HasOne("SPiluSZharuDatabase.Models.Product", "Product")
|
||||
.WithMany("SaleProducts")
|
||||
.HasForeignKey("ProductId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("SPiluSZharuDatabase.Models.Sale", "Sale")
|
||||
.WithMany("SaleProducts")
|
||||
.HasForeignKey("SaleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Product");
|
||||
|
||||
b.Navigation("Sale");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Product", b =>
|
||||
{
|
||||
b.Navigation("ProductHistories");
|
||||
|
||||
b.Navigation("SaleProducts");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Sale", b =>
|
||||
{
|
||||
b.Navigation("SaleProducts");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SPiluSZharuDatabase.Models.Worker", b =>
|
||||
{
|
||||
b.Navigation("Salaries");
|
||||
|
||||
b.Navigation("Sales");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using SPiluSZharuContracts.Enums;
|
||||
using SPiluSZharuContracts.Infrastructure.PostConfiguration;
|
||||
|
||||
namespace SPiluSZharuDatabase.Models;
|
||||
|
||||
@@ -12,7 +13,7 @@ internal class Post
|
||||
|
||||
public PostType PostType { get; set; }
|
||||
|
||||
public double Salary { get; set; }
|
||||
public required PostConfiguration Configuration { get; set; }
|
||||
|
||||
public bool IsActual { get; set; }
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@ internal class SaleProduct
|
||||
|
||||
public int Count { get; set; }
|
||||
|
||||
public double Price { get; set; }
|
||||
|
||||
public Sale? Sale { get; set; }
|
||||
|
||||
public Product? Product { get; set; }
|
||||
|
||||
@@ -20,9 +20,20 @@ internal class Worker
|
||||
|
||||
public bool IsDeleted { get; set; }
|
||||
|
||||
public DateTime? DateOfDelete { get; set; }
|
||||
|
||||
[NotMapped]
|
||||
public Post? Post { get; set; }
|
||||
|
||||
[ForeignKey("WorkerId")]
|
||||
public List<Salary>? Salaries { get; set; }
|
||||
|
||||
[ForeignKey("WorkerId")]
|
||||
public List<Sale>? Sales { get; set; }
|
||||
|
||||
public Worker AddPost(Post? post)
|
||||
{
|
||||
Post = post;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,11 @@
|
||||
<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>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -18,6 +23,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="SPiluSZharuTests" />
|
||||
<InternalsVisibleTo Include="SPiluSZharuWebApi" />
|
||||
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -1,13 +1,22 @@
|
||||
using SPiluSZharuContratcs.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SPiluSZharuContracts.Infrastructure;
|
||||
using SPiluSZharuDatabase.Models;
|
||||
using System;
|
||||
using SPiluSZharuContracts.Infrastructure.PostConfiguration;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace SPiluSZharuDatabase;
|
||||
|
||||
internal class SPiluSZharuDbContext(IConfigurationDatabase configurationDatabase) : DbContext
|
||||
internal class SPiluSZharuDbContext : DbContext
|
||||
{
|
||||
private readonly IConfigurationDatabase? _configurationDatabase = configurationDatabase;
|
||||
private readonly IConfigurationDatabase? _configurationDatabase;
|
||||
|
||||
public SPiluSZharuDbContext(IConfigurationDatabase configurationDatabase)
|
||||
{
|
||||
_configurationDatabase = configurationDatabase;
|
||||
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
|
||||
AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);
|
||||
}
|
||||
|
||||
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
||||
{
|
||||
@@ -39,6 +48,14 @@ internal class SPiluSZharuDbContext(IConfigurationDatabase configurationDatabase
|
||||
modelBuilder.Entity<SaleProduct>().HasKey(x => new { x.SaleId, x.ProductId });
|
||||
|
||||
modelBuilder.Entity<Worker>().HasIndex(x => x.PhoneNumber).IsUnique();
|
||||
|
||||
modelBuilder.Entity<Post>()
|
||||
.Property(x => x.Configuration)
|
||||
.HasColumnType("jsonb")
|
||||
.HasConversion(
|
||||
x => SerializePostConfiguration(x),
|
||||
x => DeserialzePostConfiguration(x)
|
||||
);
|
||||
}
|
||||
|
||||
public DbSet<Restaurant> Restaurants { get; set; }
|
||||
@@ -56,4 +73,13 @@ internal class SPiluSZharuDbContext(IConfigurationDatabase configurationDatabase
|
||||
public DbSet<SaleProduct> SaleProducts { get; set; }
|
||||
|
||||
public DbSet<Worker> Workers { get; set; }
|
||||
|
||||
private static string SerializePostConfiguration(PostConfiguration postConfiguration) => JsonConvert.SerializeObject(postConfiguration);
|
||||
|
||||
private static PostConfiguration DeserialzePostConfiguration(string jsonString) => JToken.Parse(jsonString).Value<string>("Type") switch
|
||||
{
|
||||
nameof(OperatorPostConfiguration) => JsonConvert.DeserializeObject<OperatorPostConfiguration>(jsonString)!,
|
||||
nameof(DeliveryManPostConfiguration) => JsonConvert.DeserializeObject<DeliveryManPostConfiguration>(jsonString)!,
|
||||
_ => JsonConvert.DeserializeObject<PostConfiguration>(jsonString)!,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
using Microsoft.EntityFrameworkCore.Design;
|
||||
|
||||
namespace SPiluSZharuDatabase;
|
||||
|
||||
internal class SampleContextFactory : IDesignTimeDbContextFactory<SPiluSZharuDbContext>
|
||||
{
|
||||
public SPiluSZharuDbContext CreateDbContext(string[] args)
|
||||
{
|
||||
return new SPiluSZharuDbContext(new DefaultConfigurationDatabase());
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SPiluSZharuBuisnessLogic",
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SPiluSZharuDatabase", "SPiluSZharuDatabase\SPiluSZharuDatabase.csproj", "{BCE267DF-2D6F-44B2-AC99-0070B7C5A4BC}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SPiluSZharuWebApi", "SPiluSZharuWebApi\SPiluSZharuWebApi.csproj", "{49B8F5F0-785D-46B7-8862-2E9196C71AD6}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -33,8 +35,15 @@ Global
|
||||
{BCE267DF-2D6F-44B2-AC99-0070B7C5A4BC}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{BCE267DF-2D6F-44B2-AC99-0070B7C5A4BC}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{BCE267DF-2D6F-44B2-AC99-0070B7C5A4BC}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{49B8F5F0-785D-46B7-8862-2E9196C71AD6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{49B8F5F0-785D-46B7-8862-2E9196C71AD6}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{49B8F5F0-785D-46B7-8862-2E9196C71AD6}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{49B8F5F0-785D-46B7-8862-2E9196C71AD6}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {D896DDE9-E491-47AD-AE9E-5B263B71E4C1}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
|
||||
@@ -5,6 +5,7 @@ using SPiluSZharuContracts.Exceptions;
|
||||
using SPiluSZharuContracts.StorageContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
using SPiluSZharuContracts.Infrastructure.PostConfiguration;
|
||||
|
||||
namespace SPiluSZharuTests.BuisnessLogicContractsTests;
|
||||
|
||||
@@ -33,61 +34,53 @@ internal class PostBuisnessLogicContractTests
|
||||
//Arrange
|
||||
var listOriginal = new List<PostDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(),"name 1", PostType.Operator, 10, true, DateTime.UtcNow),
|
||||
new(Guid.NewGuid().ToString(), "name 2", PostType.Operator, 10, false, DateTime.UtcNow),
|
||||
new(Guid.NewGuid().ToString(), "name 3", PostType.Operator, 10, true, DateTime.UtcNow),
|
||||
new(Guid.NewGuid().ToString(),"name 1", PostType.Operator, new PostConfiguration() { Rate = 10 }),
|
||||
new(Guid.NewGuid().ToString(), "name 2", PostType.Operator, new PostConfiguration() { Rate = 10 }),
|
||||
new(Guid.NewGuid().ToString(), "name 3", PostType.Operator, new PostConfiguration() { Rate = 10 }),
|
||||
};
|
||||
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Returns(listOriginal);
|
||||
_postStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
|
||||
//Act
|
||||
var listOnlyActive = _postBuisnessLogicContract.GetAllPosts(true);
|
||||
var listAll = _postBuisnessLogicContract.GetAllPosts(false);
|
||||
var list = _postBuisnessLogicContract.GetAllPosts();
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(listOnlyActive, Is.Not.Null);
|
||||
Assert.That(listAll, Is.Not.Null);
|
||||
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
|
||||
Assert.That(listAll, Is.EquivalentTo(listOriginal));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.EquivalentTo(listOriginal));
|
||||
});
|
||||
_postStorageContract.Verify(x => x.GetList(true), Times.Once);
|
||||
_postStorageContract.Verify(x => x.GetList(false), Times.Once);
|
||||
_postStorageContract.Verify(x => x.GetList(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllPosts_ReturnEmptyList_Test()
|
||||
{
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Returns([]);
|
||||
_postStorageContract.Setup(x => x.GetList()).Returns([]);
|
||||
//Act
|
||||
var listOnlyActive = _postBuisnessLogicContract.GetAllPosts(true);
|
||||
var listAll = _postBuisnessLogicContract.GetAllPosts(false);
|
||||
var list = _postBuisnessLogicContract.GetAllPosts();
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(listOnlyActive, Is.Not.Null);
|
||||
Assert.That(listAll, Is.Not.Null);
|
||||
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
|
||||
Assert.That(listAll, Has.Count.EqualTo(0));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(0));
|
||||
});
|
||||
_postStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Exactly(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllPosts_ReturnNull_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBuisnessLogicContract.GetAllPosts(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
|
||||
_postStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Once);
|
||||
Assert.That(() => _postBuisnessLogicContract.GetAllPosts(), Throws.TypeOf<NullListException>());
|
||||
_postStorageContract.Verify(x => x.GetList(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllPosts_StorageThrowError_ThrowException_Test()
|
||||
{
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
_postStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBuisnessLogicContract.GetAllPosts(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
|
||||
_postStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Once);
|
||||
Assert.That(() => _postBuisnessLogicContract.GetAllPosts(), Throws.TypeOf<StorageException>());
|
||||
_postStorageContract.Verify(x => x.GetList(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -97,8 +90,8 @@ internal class PostBuisnessLogicContractTests
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
var listOriginal = new List<PostDataModel>()
|
||||
{
|
||||
new(postId, "name 1", PostType.Operator, 10, true, DateTime.UtcNow),
|
||||
new(postId, "name 2", PostType.Operator, 10, false, DateTime.UtcNow)
|
||||
new(postId, "name 1", PostType.Operator, new PostConfiguration() { Rate = 10 }),
|
||||
new(postId, "name 2", PostType.Operator, new PostConfiguration() { Rate = 10 })
|
||||
};
|
||||
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -162,7 +155,7 @@ internal class PostBuisnessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var id = Guid.NewGuid().ToString();
|
||||
var record = new PostDataModel(id, "name", PostType.Operator, 10, true, DateTime.UtcNow);
|
||||
var record = new PostDataModel(id, "name", PostType.Operator, new PostConfiguration() { Rate = 10 });
|
||||
_postStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
|
||||
//Act
|
||||
var element = _postBuisnessLogicContract.GetPostByData(id);
|
||||
@@ -177,7 +170,7 @@ internal class PostBuisnessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var postName = "name";
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.Operator, 10, true, DateTime.UtcNow);
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.Operator, new PostConfiguration() { Rate = 10 });
|
||||
_postStorageContract.Setup(x => x.GetElementByName(postName)).Returns(record);
|
||||
//Act
|
||||
var element = _postBuisnessLogicContract.GetPostByData(postName);
|
||||
@@ -233,12 +226,11 @@ internal class PostBuisnessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var flag = false;
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.OrderPicker, 10, true, DateTime.UtcNow.AddDays(-1));
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.OrderPicker, new PostConfiguration() { Rate = 10 });
|
||||
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>()))
|
||||
.Callback((PostDataModel x) =>
|
||||
{
|
||||
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary &&
|
||||
x.ChangeDate == record.ChangeDate;
|
||||
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.ConfigurationModel.Rate == record.ConfigurationModel.Rate;
|
||||
});
|
||||
//Act
|
||||
_postBuisnessLogicContract.InsertPost(record);
|
||||
@@ -253,7 +245,7 @@ internal class PostBuisnessLogicContractTests
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBuisnessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.OrderPicker, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementExistsException>());
|
||||
Assert.That(() => _postBuisnessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.OrderPicker, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementExistsException>());
|
||||
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -269,7 +261,7 @@ internal class PostBuisnessLogicContractTests
|
||||
public void InsertPost_InvalidRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBuisnessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.OrderPicker, 10, true, DateTime.UtcNow)), Throws.TypeOf<ValidationException>());
|
||||
Assert.That(() => _postBuisnessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.OrderPicker, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ValidationException>());
|
||||
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
@@ -279,7 +271,7 @@ internal class PostBuisnessLogicContractTests
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBuisnessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.OrderPicker, 10, true, DateTime.UtcNow)), Throws.TypeOf<StorageException>());
|
||||
Assert.That(() => _postBuisnessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.OrderPicker, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<StorageException>());
|
||||
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -288,12 +280,11 @@ internal class PostBuisnessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var flag = false;
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.OrderPicker, 10, true, DateTime.UtcNow.AddDays(-1));
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.OrderPicker, new PostConfiguration() { Rate = 10 });
|
||||
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>()))
|
||||
.Callback((PostDataModel x) =>
|
||||
{
|
||||
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary &&
|
||||
x.ChangeDate == record.ChangeDate;
|
||||
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.ConfigurationModel.Rate == record.ConfigurationModel.Rate;
|
||||
});
|
||||
//Act
|
||||
_postBuisnessLogicContract.UpdatePost(record);
|
||||
@@ -308,7 +299,7 @@ internal class PostBuisnessLogicContractTests
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementNotFoundException(""));
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBuisnessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.OrderPicker, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementNotFoundException>());
|
||||
Assert.That(() => _postBuisnessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.OrderPicker, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementNotFoundException>());
|
||||
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -318,7 +309,7 @@ internal class PostBuisnessLogicContractTests
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBuisnessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.OrderPicker, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementExistsException>());
|
||||
Assert.That(() => _postBuisnessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.OrderPicker, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementExistsException>());
|
||||
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -334,7 +325,7 @@ internal class PostBuisnessLogicContractTests
|
||||
public void UpdatePost_InvalidRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBuisnessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.OrderPicker, 10, true, DateTime.UtcNow)), Throws.TypeOf<ValidationException>());
|
||||
Assert.That(() => _postBuisnessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.OrderPicker, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ValidationException>());
|
||||
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
@@ -344,7 +335,7 @@ internal class PostBuisnessLogicContractTests
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBuisnessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.OrderPicker, 10, true, DateTime.UtcNow)), Throws.TypeOf<StorageException>());
|
||||
Assert.That(() => _postBuisnessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.OrderPicker, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<StorageException>());
|
||||
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
using SPiluSZharuBuisnessLogic.Implementations;
|
||||
using SPiluSZharuContracts.DataModels;
|
||||
using SPiluSZharuContracts.Enums;
|
||||
using SPiluSZharuContracts.Exceptions;
|
||||
using SPiluSZharuContracts.StorageContracts;
|
||||
using SPiluSZharuTests.Infrastructure;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
using SPiluSZharuContracts.Infrastructure.PostConfiguration;
|
||||
using SPiluSZharuContracts.Enums;
|
||||
using SPiluSZharuContracts.BuisnessLogicContracts;
|
||||
|
||||
namespace SPiluSZharuTests.BuisnessLogicContractsTests;
|
||||
|
||||
@@ -16,6 +19,7 @@ internal class SalaryBuisnessLogicContractTests
|
||||
private Mock<ISaleStorageContract> _saleStorageContract;
|
||||
private Mock<IPostStorageContract> _postStorageContract;
|
||||
private Mock<IWorkerStorageContract> _workerStorageContract;
|
||||
private readonly ConfigurationSalaryTest _salaryConfigurationTest = new();
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
@@ -25,7 +29,7 @@ internal class SalaryBuisnessLogicContractTests
|
||||
_postStorageContract = new Mock<IPostStorageContract>();
|
||||
_workerStorageContract = new Mock<IWorkerStorageContract>();
|
||||
_salaryBuisnessLogicContract = new SalaryBuisnessLogicContract(_salaryStorageContract.Object,
|
||||
_saleStorageContract.Object, _postStorageContract.Object, _workerStorageContract.Object, new Mock<ILogger>().Object);
|
||||
_saleStorageContract.Object, _postStorageContract.Object, _workerStorageContract.Object, new Mock<ILogger>().Object, _salaryConfigurationTest);
|
||||
}
|
||||
|
||||
[SetUp]
|
||||
@@ -186,16 +190,14 @@ internal class SalaryBuisnessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
var saleSum = 200.0;
|
||||
var postSalary = 2000.0;
|
||||
var rate = 2000.0;
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, saleSum, false, [])]);
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.DeliveryMan, postSalary, true, DateTime.UtcNow));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.OrderPicker, new PostConfiguration() { Rate = rate }));
|
||||
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), "+7(777)777-77-77", DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
var sum = 0.0;
|
||||
var expectedSum = postSalary + saleSum * 0.1;
|
||||
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
|
||||
.Callback((SalaryDataModel x) =>
|
||||
{
|
||||
@@ -204,7 +206,7 @@ internal class SalaryBuisnessLogicContractTests
|
||||
//Act
|
||||
_salaryBuisnessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
|
||||
//Assert
|
||||
Assert.That(sum, Is.EqualTo(expectedSum));
|
||||
Assert.That(sum, Is.EqualTo(rate));
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -220,13 +222,13 @@ internal class SalaryBuisnessLogicContractTests
|
||||
new(worker3Id, "Test", Guid.NewGuid().ToString(), "+7(333)333-33-33", DateTime.UtcNow, DateTime.UtcNow, false)
|
||||
};
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), worker1Id, null, 1, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), worker1Id, null, 1, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), worker2Id, null, 1, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), worker3Id, null, 1, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), worker3Id, null, 1, false, [])]);
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), worker1Id, null, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), worker1Id, null, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), worker2Id, null, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), worker3Id, null, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), worker3Id, null, false, [])]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.DeliveryMan, 2000, true, DateTime.UtcNow));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.OrderPicker, new PostConfiguration() { Rate = 100 }));
|
||||
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
.Returns(list);
|
||||
//Act
|
||||
@@ -236,19 +238,18 @@ internal class SalaryBuisnessLogicContractTests
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CalculateSalaryByMounth_WithoitSalesByWorker_Test()
|
||||
public void CalculateSalaryByMounth_WithoutSalesByWorker_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postSalary = 2000.0;
|
||||
var rate = 2000.0;
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns([]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.DeliveryMan, postSalary, true, DateTime.UtcNow));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.OrderPicker, new PostConfiguration() { Rate = rate }));
|
||||
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), "+7(777)777-77-77", DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
var sum = 0.0;
|
||||
var expectedSum = postSalary;
|
||||
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
|
||||
.Callback((SalaryDataModel x) =>
|
||||
{
|
||||
@@ -257,7 +258,7 @@ internal class SalaryBuisnessLogicContractTests
|
||||
//Act
|
||||
_salaryBuisnessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
|
||||
//Assert
|
||||
Assert.That(sum, Is.EqualTo(expectedSum));
|
||||
Assert.That(sum, Is.EqualTo(rate));
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -266,7 +267,7 @@ internal class SalaryBuisnessLogicContractTests
|
||||
//Arrange
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.DeliveryMan, 2000, true, DateTime.UtcNow));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.OrderPicker, new PostConfiguration() { Rate = 100 }));
|
||||
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), "+7(777)777-77-77", DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
//Act&Assert
|
||||
@@ -279,7 +280,7 @@ internal class SalaryBuisnessLogicContractTests
|
||||
//Arrange
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, 200, false, [])]);
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, 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([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), "+7(777)777-77-77", DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
//Act&Assert
|
||||
@@ -292,9 +293,9 @@ internal class SalaryBuisnessLogicContractTests
|
||||
//Arrange
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, 200, false, [])]);
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, false, [])]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.DeliveryMan, 2000, true, DateTime.UtcNow));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.OrderPicker, new PostConfiguration() { Rate = 100 }));
|
||||
//Act&Assert
|
||||
Assert.That(() => _salaryBuisnessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
|
||||
}
|
||||
@@ -307,7 +308,7 @@ internal class SalaryBuisnessLogicContractTests
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Throws(new StorageException(new InvalidOperationException()));
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.DeliveryMan, 2000, true, DateTime.UtcNow));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.OrderPicker, new PostConfiguration() { Rate = 100 }));
|
||||
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), "+7(777)777-77-77", DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
//Act&Assert
|
||||
@@ -320,7 +321,7 @@ internal class SalaryBuisnessLogicContractTests
|
||||
//Arrange
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, 200, false, [])]);
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, false, [])]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.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?>()))
|
||||
@@ -335,12 +336,74 @@ internal class SalaryBuisnessLogicContractTests
|
||||
//Arrange
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, 200, false, [])]);
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, false, [])]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.DeliveryMan, 2000, true, DateTime.UtcNow));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.OrderPicker, new PostConfiguration() { Rate = 100 }));
|
||||
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
.Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _salaryBuisnessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CalculateSalaryByMounth_WithDeliveryManPostConfiguration_CalculateSalary_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
var rate = 2000.0;
|
||||
var percent = 0.1;
|
||||
var bonus = 0.5;
|
||||
var sales = new List<SaleDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), workerId, null, false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]),
|
||||
new(Guid.NewGuid().ToString(), workerId, null, false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]),
|
||||
new(Guid.NewGuid().ToString(), workerId, null, false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5000, 12)])
|
||||
};
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(sales);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.DeliveryMan, new DeliveryManPostConfiguration() { Rate = rate, SalePercent = percent, BonusForExtraSales = bonus }));
|
||||
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), "+7(777)777-77-77", DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
var sum = 0.0;
|
||||
var expectedSum = rate + percent * (sales.Sum(x => x.Sum) / sales.Count) + sales.Where(x => x.Sum > _salaryConfigurationTest.ExtraSaleSum).Sum(x => x.Sum) * bonus;
|
||||
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
|
||||
.Callback((SalaryDataModel x) =>
|
||||
{
|
||||
sum = x.Salary;
|
||||
});
|
||||
//Act
|
||||
_salaryBuisnessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
|
||||
//Assert
|
||||
Assert.That(sum, Is.EqualTo(expectedSum));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CalculateSalaryByMounth_WithOperatorPostConfiguration_CalculateSalary_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
var rate = 2000.0;
|
||||
var trend = 3;
|
||||
var bonus = 100;
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), workerId, null, false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Operator, new OperatorPostConfiguration() { Rate = rate, PersonalCountTrendPremium = bonus }));
|
||||
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), "+7(777)777-77-77", DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
_workerStorageContract.Setup(x => x.GetWorkerTrend(It.IsAny<DateTime>(), It.IsAny<DateTime>()))
|
||||
.Returns(trend);
|
||||
var sum = 0.0;
|
||||
var expectedSum = rate + trend * bonus;
|
||||
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
|
||||
.Callback((SalaryDataModel x) =>
|
||||
{
|
||||
sum = x.Salary;
|
||||
});
|
||||
//Act
|
||||
_salaryBuisnessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
|
||||
//Assert
|
||||
Assert.That(sum, Is.EqualTo(expectedSum));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ using SPiluSZharuContracts.Exceptions;
|
||||
using SPiluSZharuContracts.StorageContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
using SPiluSZharuContracts.BuisnessLogicContracts;
|
||||
using SPiluSZharuDatabase.Implementations;
|
||||
|
||||
namespace SPiluSZharuTests.BuisnessLogicContractsTests;
|
||||
|
||||
@@ -33,10 +35,10 @@ internal class SaleBuisnessLogicContractTests
|
||||
var date = DateTime.UtcNow;
|
||||
var listOriginal = new List<SaleDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, false,
|
||||
[new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, false,
|
||||
[new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, false, []),
|
||||
};
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -97,10 +99,10 @@ internal class SaleBuisnessLogicContractTests
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
var listOriginal = new List<SaleDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, false,
|
||||
[new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, false,
|
||||
[new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, false, []),
|
||||
};
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -178,10 +180,10 @@ internal class SaleBuisnessLogicContractTests
|
||||
var restaurantId = Guid.NewGuid().ToString();
|
||||
var listOriginal = new List<SaleDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, false,
|
||||
[new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, false,
|
||||
[new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, false, []),
|
||||
};
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -259,10 +261,10 @@ internal class SaleBuisnessLogicContractTests
|
||||
var productId = Guid.NewGuid().ToString();
|
||||
var listOriginal = new List<SaleDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, false,
|
||||
[new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, false,
|
||||
[new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, false, []),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, false, []),
|
||||
};
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -337,8 +339,8 @@ internal class SaleBuisnessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var id = Guid.NewGuid().ToString();
|
||||
var record = new SaleDataModel(id, Guid.NewGuid().ToString(), null, 10, false,
|
||||
[new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
|
||||
var record = new SaleDataModel(id, Guid.NewGuid().ToString(), null, false,
|
||||
[new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]);
|
||||
_saleStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
|
||||
//Act
|
||||
var element = _saleBuisnessLogicContract.GetSaleByData(id);
|
||||
@@ -388,8 +390,8 @@ internal class SaleBuisnessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var flag = false;
|
||||
var record = new SaleDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10,
|
||||
false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
|
||||
var record = new SaleDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
|
||||
false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]);
|
||||
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>()))
|
||||
.Callback((SaleDataModel x) =>
|
||||
{
|
||||
@@ -413,7 +415,7 @@ internal class SaleBuisnessLogicContractTests
|
||||
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new ElementExistsException("Data", "Data"));
|
||||
//Act&Assert
|
||||
Assert.That(() => _saleBuisnessLogicContract.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>());
|
||||
Guid.NewGuid().ToString(), false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])), Throws.TypeOf<ElementExistsException>());
|
||||
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -429,7 +431,7 @@ internal class SaleBuisnessLogicContractTests
|
||||
public void InsertSale_InvalidRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _saleBuisnessLogicContract.InsertSale(new SaleDataModel("id", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, false, [])), Throws.TypeOf<ValidationException>());
|
||||
Assert.That(() => _saleBuisnessLogicContract.InsertSale(new SaleDataModel("id", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), false, [])), Throws.TypeOf<ValidationException>());
|
||||
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
@@ -440,7 +442,7 @@ internal class SaleBuisnessLogicContractTests
|
||||
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _saleBuisnessLogicContract.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(), false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])), Throws.TypeOf<StorageException>());
|
||||
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using SPiluSZharuContracts.DataModels;
|
||||
using SPiluSZharuContracts.Exceptions;
|
||||
using SPiluSZharuContracts.Enums;
|
||||
using SPiluSZharuContracts.Infrastructure.PostConfiguration;
|
||||
|
||||
namespace SPiluSZharuTests.DataModelTests;
|
||||
|
||||
@@ -10,41 +11,48 @@ internal class PostDataModelTests
|
||||
[Test]
|
||||
public void IdIsNullOrEmptyTest()
|
||||
{
|
||||
var post = CreateDataModel(null, "name", PostType.Operator, 10, true, DateTime.UtcNow);
|
||||
var post = CreateDataModel(null, "name", PostType.Operator, new PostConfiguration() { Rate = 10 });
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
post = CreateDataModel(string.Empty, "name", PostType.Operator, 10, true, DateTime.UtcNow);
|
||||
post = CreateDataModel(string.Empty, "name", PostType.Operator, new PostConfiguration() { Rate = 10 });
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void IdIsNotGuidTest()
|
||||
{
|
||||
var post = CreateDataModel("id", "name", PostType.Operator, 10, true, DateTime.UtcNow);
|
||||
var post = CreateDataModel("id", "name", PostType.Operator, new PostConfiguration() { Rate = 10 });
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PostNameIsEmptyTest()
|
||||
{
|
||||
var restaurant = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Operator, 10, true, DateTime.UtcNow);
|
||||
var restaurant = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Operator, new PostConfiguration() { Rate = 10 });
|
||||
Assert.That(() => restaurant.Validate(), Throws.TypeOf<ValidationException>());
|
||||
restaurant = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Operator, 10, true, DateTime.UtcNow);
|
||||
restaurant = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Operator, new PostConfiguration() { Rate = 10 });
|
||||
Assert.That(() => restaurant.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PostTypeIsNoneTest()
|
||||
{
|
||||
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.None, 10, true, DateTime.UtcNow);
|
||||
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.None, new PostConfiguration() { Rate = 10 });
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SalaryIsLessOrZeroTest()
|
||||
public void ConfigurationModelIsNullTest()
|
||||
{
|
||||
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Operator, 0, true, DateTime.UtcNow);
|
||||
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Operator, null);
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Operator, -10, true, DateTime.UtcNow);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RateIsLessOrZeroTest()
|
||||
{
|
||||
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Operator, new PostConfiguration() { Rate = 0 });
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Operator, new PostConfiguration() { Rate = -10 });
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
@@ -52,25 +60,21 @@ internal class PostDataModelTests
|
||||
public void AllFieldsIsCorrectTest()
|
||||
{
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
var postPostId = Guid.NewGuid().ToString();
|
||||
var postName = "name";
|
||||
var postType = PostType.Operator;
|
||||
var salary = 10;
|
||||
var isActual = false;
|
||||
var changeDate = DateTime.UtcNow.AddDays(-1);
|
||||
var post = CreateDataModel(postId, postName, postType, salary, isActual, changeDate);
|
||||
var configuration = new PostConfiguration() { Rate = 10 };
|
||||
var post = CreateDataModel(postId, postName, postType, configuration);
|
||||
Assert.That(() => post.Validate(), 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(post.IsActual, Is.EqualTo(isActual));
|
||||
Assert.That(post.ChangeDate, Is.EqualTo(changeDate));
|
||||
Assert.That(post.ConfigurationModel, Is.EqualTo(configuration));
|
||||
Assert.That(post.ConfigurationModel.Rate, Is.EqualTo(configuration.Rate));
|
||||
});
|
||||
}
|
||||
|
||||
private static PostDataModel CreateDataModel(string? id, string? postName, PostType postType, double salary, bool isActual, DateTime changeDate) =>
|
||||
new(id, postName, postType, salary, isActual, changeDate);
|
||||
private static PostDataModel CreateDataModel(string? id, string? postName, PostType postType, PostConfiguration configuration) =>
|
||||
new(id, postName, postType, configuration);
|
||||
}
|
||||
|
||||
@@ -9,85 +9,94 @@ internal class SaleDataModelTests
|
||||
[Test]
|
||||
public void IdIsNullOrEmptyTest()
|
||||
{
|
||||
var sale = CreateDataModel(null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, false, CreateSubDataModel());
|
||||
var sale = CreateDataModel(null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), false, CreateSubDataModel());
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
sale = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, false, CreateSubDataModel());
|
||||
sale = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), false, CreateSubDataModel());
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void IdIsNotGuidTest()
|
||||
{
|
||||
var sale = CreateDataModel("id", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, false, CreateSubDataModel());
|
||||
var sale = CreateDataModel("id", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), false, CreateSubDataModel());
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void WorkerIdIsNullOrEmptyTest()
|
||||
{
|
||||
var sale = CreateDataModel(Guid.NewGuid().ToString(), null, Guid.NewGuid().ToString(), 10, false, CreateSubDataModel());
|
||||
var sale = CreateDataModel(Guid.NewGuid().ToString(), null, Guid.NewGuid().ToString(), false, CreateSubDataModel());
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
sale = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, Guid.NewGuid().ToString(), 10, false, CreateSubDataModel());
|
||||
sale = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, Guid.NewGuid().ToString(), false, CreateSubDataModel());
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void WorkerIdIsNotGuidTest()
|
||||
{
|
||||
var sale = CreateDataModel(Guid.NewGuid().ToString(), "employeeId", Guid.NewGuid().ToString(), 10, false, CreateSubDataModel());
|
||||
var sale = CreateDataModel(Guid.NewGuid().ToString(), "workerId", Guid.NewGuid().ToString(), false, CreateSubDataModel());
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RestaurantIdIsNotGuidTest()
|
||||
{
|
||||
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "restaurantId", 10, false, CreateSubDataModel());
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SumIsLessOrZeroTest()
|
||||
{
|
||||
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0, false, CreateSubDataModel());
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -10, false, CreateSubDataModel());
|
||||
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "restaurantId", false, CreateSubDataModel());
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ProductsIsNullOrEmptyTest()
|
||||
{
|
||||
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, false, null);
|
||||
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), false, null);
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, false, []);
|
||||
sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), false, []);
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CalcSumTest()
|
||||
{
|
||||
var saleId = Guid.NewGuid().ToString();
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
var restaurantId = Guid.NewGuid().ToString();
|
||||
var products = new List<SaleProductDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 2, 1.1),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 1.3)
|
||||
};
|
||||
var isCancel = false;
|
||||
var totalSum = products.Sum(x => x.Price * x.Count);
|
||||
var sale = CreateDataModel(saleId, workerId, restaurantId, isCancel, products);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(sale.Sum, Is.EqualTo(totalSum));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AllFieldsIsCorrectTest()
|
||||
{
|
||||
var saleId = Guid.NewGuid().ToString();
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
var restaurantId = Guid.NewGuid().ToString();
|
||||
var sum = 10;
|
||||
var isCancel = true;
|
||||
var products = CreateSubDataModel();
|
||||
var sale = CreateDataModel(saleId, workerId, restaurantId, sum, isCancel, products);
|
||||
var sale = CreateDataModel(saleId, workerId, restaurantId, isCancel, products);
|
||||
Assert.That(() => sale.Validate(), Throws.Nothing);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(sale.Id, Is.EqualTo(saleId));
|
||||
Assert.That(sale.WorkerId, Is.EqualTo(workerId));
|
||||
Assert.That(sale.RestaurantId, Is.EqualTo(restaurantId));
|
||||
Assert.That(sale.Sum, Is.EqualTo(sum));
|
||||
Assert.That(sale.IsCancel, Is.EqualTo(isCancel));
|
||||
Assert.That(sale.Products, Is.EquivalentTo(products));
|
||||
});
|
||||
}
|
||||
|
||||
private static SaleDataModel CreateDataModel(string? id, string? workerId, string? restaurantId, double sum, bool isCancel, List<SaleProductDataModel>? products) =>
|
||||
new(id, workerId, restaurantId, sum, isCancel, products);
|
||||
private static SaleDataModel CreateDataModel(string? id, string? workerId, string? restaurantId, bool isCancel, List<SaleProductDataModel>? products) =>
|
||||
new(id, workerId, restaurantId, isCancel, products);
|
||||
|
||||
private static List<SaleProductDataModel> CreateSubDataModel()
|
||||
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)];
|
||||
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 1.1)];
|
||||
}
|
||||
|
||||
@@ -9,41 +9,41 @@ internal class SaleProductDataModelTests
|
||||
[Test]
|
||||
public void SaleIdIsNullOrEmptyTest()
|
||||
{
|
||||
var saleProduct = CreateDataModel(null, Guid.NewGuid().ToString(), 10);
|
||||
var saleProduct = CreateDataModel(null, Guid.NewGuid().ToString(), 10, 1.1);
|
||||
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
|
||||
saleProduct = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10);
|
||||
saleProduct = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10, 1.1);
|
||||
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SaleIdIsNotGuidTest()
|
||||
{
|
||||
var saleProduct = CreateDataModel("saleId", Guid.NewGuid().ToString(), 10);
|
||||
var saleProduct = CreateDataModel("saleId", Guid.NewGuid().ToString(), 10, 1.1);
|
||||
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ProductIdIsNullOrEmptyTest()
|
||||
{
|
||||
var saleProduct = CreateDataModel(Guid.NewGuid().ToString(), null, 10);
|
||||
var saleProduct = CreateDataModel(Guid.NewGuid().ToString(), null, 10, 1.1);
|
||||
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
|
||||
saleProduct = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10);
|
||||
saleProduct = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10, 1.1);
|
||||
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ProductIdIsNotGuidTest()
|
||||
{
|
||||
var saleProduct = CreateDataModel(Guid.NewGuid().ToString(), "productId", 10);
|
||||
var saleProduct = CreateDataModel(Guid.NewGuid().ToString(), "productId", 10, 1.1);
|
||||
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CountIsLessOrZeroTest()
|
||||
{
|
||||
var saleProduct = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0);
|
||||
var saleProduct = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0, 1.1);
|
||||
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
|
||||
saleProduct = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -10);
|
||||
saleProduct = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -10, 1.1);
|
||||
Assert.That(() => saleProduct.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
@@ -53,7 +53,8 @@ internal class SaleProductDataModelTests
|
||||
var saleId = Guid.NewGuid().ToString();
|
||||
var productId = Guid.NewGuid().ToString();
|
||||
var count = 10;
|
||||
var saleProduct = CreateDataModel(saleId, productId, count);
|
||||
var price = 1.2;
|
||||
var saleProduct = CreateDataModel(saleId, productId, count, price);
|
||||
Assert.That(() => saleProduct.Validate(), Throws.Nothing);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
@@ -63,6 +64,6 @@ internal class SaleProductDataModelTests
|
||||
});
|
||||
}
|
||||
|
||||
private static SaleProductDataModel CreateDataModel(string? saleId, string? productId, int count) =>
|
||||
new(saleId, productId, count);
|
||||
private static SaleProductDataModel CreateDataModel(string? saleId, string? productId, int count, double price) =>
|
||||
new(saleId, productId, count, price);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using SPiluSZharuContratcs.Infrastructure;
|
||||
using SPiluSZharuContracts.Infrastructure;
|
||||
|
||||
namespace SPiluSZharuTests.Infrastructure;
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
using SPiluSZharuContracts.Infrastructure;
|
||||
|
||||
namespace SPiluSZharuTests.Infrastructure;
|
||||
|
||||
class ConfigurationSalaryTest : IConfigurationSalary
|
||||
{
|
||||
public double ExtraSaleSum => 10;
|
||||
|
||||
public int MaxConcurrentThreads => 4;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using SPiluSZharuContracts.Infrastructure;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace SPiluSZharuTests.Infrastructure;
|
||||
|
||||
internal class CustomWebApplicationFactory<TProgram> : WebApplicationFactory<TProgram>
|
||||
where TProgram : class
|
||||
{
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
builder.ConfigureServices(services =>
|
||||
{
|
||||
var databaseConfig = services.SingleOrDefault(x => x.ServiceType == typeof(IConfigurationDatabase));
|
||||
if (databaseConfig is not null)
|
||||
services.Remove(databaseConfig);
|
||||
|
||||
var loggerFactory = services.SingleOrDefault(x => x.ServiceType == typeof(LoggerFactory));
|
||||
if (loggerFactory is not null)
|
||||
services.Remove(loggerFactory);
|
||||
|
||||
services.AddSingleton<IConfigurationDatabase, ConfigurationDatabaseTest>();
|
||||
});
|
||||
|
||||
builder.UseEnvironment("Development");
|
||||
|
||||
base.ConfigureWebHost(builder);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
using SPiluSZharuContracts.Enums;
|
||||
using SPiluSZharuDatabase;
|
||||
using SPiluSZharuDatabase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SPiluSZharuContracts.Infrastructure.PostConfiguration;
|
||||
|
||||
namespace SPiluSZharuTests.Infrastructure;
|
||||
|
||||
internal static class SPiluSZharuDbContextExtensions
|
||||
{
|
||||
public static Restaurant InsertRestaurantToDatabaseAndReturn(this SPiluSZharuDbContext dbContext, string? id = null, string restaurantName = "test", string prevRestaurantName = "prev", string prevPrevRestaurantName = "prevPrev")
|
||||
{
|
||||
var restaurant = new Restaurant() { Id = id ?? Guid.NewGuid().ToString(), RestaurantName = restaurantName, PrevRestaurantName = prevRestaurantName, PrevPrevRestaurantName = prevPrevRestaurantName };
|
||||
dbContext.Restaurants.Add(restaurant);
|
||||
dbContext.SaveChanges();
|
||||
return restaurant;
|
||||
}
|
||||
|
||||
public static Post InsertPostToDatabaseAndReturn(this SPiluSZharuDbContext dbContext, string? id = null, string postName = "test", PostType postType = PostType.Operator, PostConfiguration? config = null, bool isActual = true, DateTime? changeDate = null)
|
||||
{
|
||||
var post = new Post() { Id = Guid.NewGuid().ToString(), PostId = id ?? Guid.NewGuid().ToString(), PostName = postName, PostType = postType, Configuration = config ?? new PostConfiguration() { Rate = 100 }, IsActual = isActual, ChangeDate = changeDate ?? DateTime.UtcNow };
|
||||
dbContext.Posts.Add(post);
|
||||
dbContext.SaveChanges();
|
||||
return post;
|
||||
}
|
||||
|
||||
public static Product InsertProductToDatabaseAndReturn(this SPiluSZharuDbContext dbContext, string? id = null, string productName = "test", ProductType productType = ProductType.Pizza, double price = 1, bool isDeleted = false)
|
||||
{
|
||||
var product = new Product() { Id = id ?? Guid.NewGuid().ToString(), ProductName = productName, ProductType = productType, Price = price, IsDeleted = isDeleted };
|
||||
dbContext.Products.Add(product);
|
||||
dbContext.SaveChanges();
|
||||
return product;
|
||||
}
|
||||
|
||||
public static ProductHistory InsertProductHistoryToDatabaseAndReturn(this SPiluSZharuDbContext dbContext, string productId, double price = 10, DateTime? changeDate = null)
|
||||
{
|
||||
var productHistory = new ProductHistory() { Id = Guid.NewGuid().ToString(), ProductId = productId, OldPrice = price, ChangeDate = changeDate ?? DateTime.UtcNow };
|
||||
dbContext.ProductHistories.Add(productHistory);
|
||||
dbContext.SaveChanges();
|
||||
return productHistory;
|
||||
}
|
||||
|
||||
public static Salary InsertSalaryToDatabaseAndReturn(this SPiluSZharuDbContext dbContext, string workerId, double workerSalary = 1, DateTime? salaryDate = null)
|
||||
{
|
||||
var salary = new Salary() { WorkerId = workerId, WorkerSalary = workerSalary, SalaryDate = salaryDate ?? DateTime.UtcNow };
|
||||
dbContext.Salaries.Add(salary);
|
||||
dbContext.SaveChanges();
|
||||
return salary;
|
||||
}
|
||||
|
||||
public static Sale InsertSaleToDatabaseAndReturn(this SPiluSZharuDbContext dbContext, string workerId, string? restaurantId = null, DateTime? saleDate = null, double sum = 1, bool isCancel = false, List<(string, int, double)>? products = null)
|
||||
{
|
||||
var sale = new Sale() { WorkerId = workerId, RestaurantId = restaurantId, SaleDate = saleDate ?? DateTime.UtcNow, Sum = sum, IsCancel = isCancel, SaleProducts = [] };
|
||||
if (products is not null)
|
||||
{
|
||||
foreach (var elem in products)
|
||||
{
|
||||
sale.SaleProducts.Add(new SaleProduct { ProductId = elem.Item1, SaleId = sale.Id, Count = elem.Item2 });
|
||||
}
|
||||
}
|
||||
dbContext.Sales.Add(sale);
|
||||
dbContext.SaveChanges();
|
||||
return sale;
|
||||
}
|
||||
|
||||
public static Worker InsertWorkerToDatabaseAndReturn(this SPiluSZharuDbContext dbContext, string? id = null, string fio = "test", string? postId = null, string phoneNumber = "+7(777)777-77-77", DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false, DateTime? dateDelete = null)
|
||||
{
|
||||
var worker = new Worker() { Id = id ?? Guid.NewGuid().ToString(), FIO = fio, PostId = postId ?? Guid.NewGuid().ToString(), PhoneNumber = phoneNumber, BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-20), EmploymentDate = employmentDate ?? DateTime.UtcNow, IsDeleted = isDeleted, DateOfDelete = dateDelete };
|
||||
dbContext.Workers.Add(worker);
|
||||
dbContext.SaveChanges();
|
||||
return worker;
|
||||
}
|
||||
|
||||
public static Restaurant? GetRestaurantFromDatabase(this SPiluSZharuDbContext dbContext, string id) => dbContext.Restaurants.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
public static Post? GetPostFromDatabaseByPostId(this SPiluSZharuDbContext dbContext, string id) => dbContext.Posts.FirstOrDefault(x => x.PostId == id && x.IsActual);
|
||||
|
||||
public static Post[] GetPostsFromDatabaseByPostId(this SPiluSZharuDbContext dbContext, string id) => [.. dbContext.Posts.Where(x => x.PostId == id).OrderByDescending(x => x.ChangeDate)];
|
||||
|
||||
public static Product? GetProductFromDatabaseById(this SPiluSZharuDbContext dbContext, string id) => dbContext.Products.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
public static Salary[] GetSalariesFromDatabaseByWorkerId(this SPiluSZharuDbContext dbContext, string id) => [.. dbContext.Salaries.Where(x => x.WorkerId == id)];
|
||||
|
||||
public static Sale? GetSaleFromDatabaseById(this SPiluSZharuDbContext dbContext, string id) => dbContext.Sales.Include(x => x.SaleProducts).FirstOrDefault(x => x.Id == id);
|
||||
|
||||
public static Sale[] GetSalesByRestaurantId(this SPiluSZharuDbContext dbContext, string? restaurantId) => [.. dbContext.Sales.Include(x => x.SaleProducts).Where(x => x.RestaurantId == restaurantId)];
|
||||
|
||||
public static Worker? GetWorkerFromDatabaseById(this SPiluSZharuDbContext dbContext, string id) => dbContext.Workers.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
public static void RemoveRestaurantsFromDatabase(this SPiluSZharuDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Restaurants\" CASCADE;");
|
||||
|
||||
public static void RemovePostsFromDatabase(this SPiluSZharuDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Posts\" CASCADE;");
|
||||
|
||||
public static void RemoveProductsFromDatabase(this SPiluSZharuDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Products\" CASCADE;");
|
||||
|
||||
public static void RemoveSalariesFromDatabase(this SPiluSZharuDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Salaries\" CASCADE;");
|
||||
|
||||
public static void RemoveSalesFromDatabase(this SPiluSZharuDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Sales\" CASCADE;");
|
||||
|
||||
public static void RemoveWorkersFromDatabase(this SPiluSZharuDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Workers\" CASCADE;");
|
||||
|
||||
private static void ExecuteSqlRaw(this SPiluSZharuDbContext dbContext, string command) => dbContext.Database.ExecuteSqlRaw(command);
|
||||
}
|
||||
@@ -8,11 +8,20 @@
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Include="appsettings.json">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
|
||||
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.4">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="9.0.3" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.3" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.13.0" />
|
||||
<PackageReference Include="Moq" Version="4.20.72" />
|
||||
@@ -22,12 +31,15 @@
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="NUnit3TestAdapter" Version="5.0.0" />
|
||||
<PackageReference Include="Serilog" Version="4.2.0" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\SPiluSZharuBuisnessLogic\SPiluSZharuBuisnessLogic.csproj" />
|
||||
<ProjectReference Include="..\SPiluSZharuContracts\SPiluSZharuContracts.csproj" />
|
||||
<ProjectReference Include="..\SPiluSZharuDatabase\SPiluSZharuDatabase.csproj" />
|
||||
<ProjectReference Include="..\SPiluSZharuWebApi\SPiluSZharuWebApi.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -1,17 +1,52 @@
|
||||
using SPiluSZharuDatabase;
|
||||
using SPiluSZharuTests.Infrastructure;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.AspNetCore.TestHost;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace SPiluSZharuTests.StoragesContracts;
|
||||
|
||||
internal abstract class BaseStorageContractTest
|
||||
internal class BaseStorageContractTest
|
||||
{
|
||||
private WebApplicationFactory<Program> _webApplication;
|
||||
|
||||
protected HttpClient HttpClient { get; private set; }
|
||||
|
||||
protected SPiluSZharuDbContext SPiluSZharuDbContext { get; private set; }
|
||||
|
||||
protected static readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
SPiluSZharuDbContext = new SPiluSZharuDbContext(new ConfigurationDatabaseTest());
|
||||
_webApplication = new CustomWebApplicationFactory<Program>();
|
||||
HttpClient = _webApplication
|
||||
.WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.ConfigureTestServices(services =>
|
||||
{
|
||||
using var loggerFactory = new LoggerFactory();
|
||||
loggerFactory.AddSerilog(new LoggerConfiguration()
|
||||
.ReadFrom.Configuration(new ConfigurationBuilder()
|
||||
.SetBasePath(Directory.GetCurrentDirectory())
|
||||
.AddJsonFile("appsettings.json")
|
||||
.Build())
|
||||
.CreateLogger());
|
||||
services.AddSingleton(loggerFactory);
|
||||
});
|
||||
})
|
||||
.CreateClient();
|
||||
|
||||
var request = HttpClient.GetAsync("/login/user").GetAwaiter().GetResult();
|
||||
var data = request.Content.ReadAsStringAsync().GetAwaiter().GetResult();
|
||||
HttpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {data}");
|
||||
|
||||
SPiluSZharuDbContext = _webApplication.Services.GetRequiredService<SPiluSZharuDbContext>();
|
||||
SPiluSZharuDbContext.Database.EnsureDeleted();
|
||||
SPiluSZharuDbContext.Database.EnsureCreated();
|
||||
}
|
||||
@@ -19,7 +54,15 @@ internal abstract class BaseStorageContractTest
|
||||
[OneTimeTearDown]
|
||||
public void OneTimeTearDown()
|
||||
{
|
||||
SPiluSZharuDbContext.Database.EnsureDeleted();
|
||||
SPiluSZharuDbContext.Dispose();
|
||||
SPiluSZharuDbContext?.Database.EnsureDeleted();
|
||||
SPiluSZharuDbContext?.Dispose();
|
||||
HttpClient?.Dispose();
|
||||
_webApplication?.Dispose();
|
||||
}
|
||||
|
||||
protected static async Task<T?> GetModelFromResponseAsync<T>(HttpResponseMessage response) =>
|
||||
JsonSerializer.Deserialize<T>(await response.Content.ReadAsStringAsync(), JsonSerializerOptions);
|
||||
|
||||
protected static StringContent MakeContent(object model) =>
|
||||
new(JsonSerializer.Serialize(model), Encoding.UTF8, "application/json");
|
||||
}
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
using SPiluSZharuContracts.DataModels;
|
||||
using SPiluSZharuContracts.Enums;
|
||||
using SPiluSZharuContracts.Exceptions;
|
||||
using SPiluSZharuContracts.Infrastructure.PostConfiguration;
|
||||
using SPiluSZharuDatabase.Implementations;
|
||||
using SPiluSZharuDatabase.Models;
|
||||
using SPiluSZharuTests.Infrastructure;
|
||||
|
||||
namespace SPiluSZharuTests.StoragesContracts;
|
||||
|
||||
@@ -21,15 +23,15 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
SPiluSZharuDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Posts\" CASCADE;");
|
||||
SPiluSZharuDbContext.RemovePostsFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2");
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3");
|
||||
var post = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2");
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3");
|
||||
var list = _postStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
@@ -45,43 +47,25 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_OnlyActual_Test()
|
||||
public void Try_GetList_WhenDifferentConfigTypes_Test()
|
||||
{
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3", isActual: false);
|
||||
var list = _postStorageContract.GetList(onlyActual: true);
|
||||
var postSimple = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(postName: "name 1");
|
||||
var postCashier = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(postName: "name 2", config: new DeliveryManPostConfiguration() { SalePercent = 500 });
|
||||
var postSupervisor = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(postName: "name 3", config: new OperatorPostConfiguration() { PersonalCountTrendPremium = 20 });
|
||||
var list = _postStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
Assert.That(!list.Any(x => !x.IsActual));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_IncludeNoActual_Test()
|
||||
{
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3", isActual: false);
|
||||
var list = _postStorageContract.GetList(onlyActual: false);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
Assert.That(list.Count(x => x.IsActual), Is.EqualTo(2));
|
||||
Assert.That(list.Count(x => !x.IsActual), Is.EqualTo(1));
|
||||
});
|
||||
AssertElement(list.First(x => x.Id == postSimple.PostId), postSimple);
|
||||
AssertElement(list.First(x => x.Id == postCashier.PostId), postCashier);
|
||||
AssertElement(list.First(x => x.Id == postSupervisor.PostId), postSupervisor);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetPostWithHistory_WhenHaveRecords_Test()
|
||||
{
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
|
||||
var list = _postStorageContract.GetPostWithHistory(postId);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
@@ -91,9 +75,9 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
public void Try_GetPostWithHistory_WhenNoRecords_Test()
|
||||
{
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
|
||||
var list = _postStorageContract.GetPostWithHistory(Guid.NewGuid().ToString());
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(0));
|
||||
@@ -102,103 +86,118 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var post = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn();
|
||||
AssertElement(_postStorageContract.GetElementById(post.PostId), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn();
|
||||
Assert.That(() => _postStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenRecordHasDeleted_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
|
||||
var post = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
Assert.That(() => _postStorageContract.GetElementById(post.PostId), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenTrySearchById_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var post = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn();
|
||||
Assert.That(() => _postStorageContract.GetElementById(post.Id), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenHaveRecord_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var post = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn();
|
||||
AssertElement(_postStorageContract.GetElementByName(post.PostName), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenNoRecord_Test()
|
||||
{
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn();
|
||||
Assert.That(() => _postStorageContract.GetElementByName("name"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenRecordHasDeleted_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
|
||||
var post = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
Assert.That(() => _postStorageContract.GetElementById(post.PostName), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), isActual: true);
|
||||
var post = CreateModel(Guid.NewGuid().ToString());
|
||||
_postStorageContract.AddElement(post);
|
||||
AssertElement(GetPostFromDatabaseByPostId(post.Id), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenActualIsFalse_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), isActual: false);
|
||||
Assert.That(() => _postStorageContract.AddElement(post), Throws.Nothing);
|
||||
AssertElement(GetPostFromDatabaseByPostId(post.Id), CreateModel(post.Id, isActual: true));
|
||||
AssertElement(SPiluSZharuDbContext.GetPostFromDatabaseByPostId(post.Id), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), "name unique", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), postName: post.PostName, isActual: true);
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), "name unique");
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(postName: post.PostName, isActual: true);
|
||||
Assert.That(() => _postStorageContract.AddElement(post), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSamePostIdAndActualIsTrue_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), isActual: true);
|
||||
InsertPostToDatabaseAndReturn(post.Id, isActual: true);
|
||||
var post = CreateModel(Guid.NewGuid().ToString());
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: true);
|
||||
Assert.That(() => _postStorageContract.AddElement(post), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WithDeliveryManPostConfiguration_Test()
|
||||
{
|
||||
var salePercent = 10;
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), config: new DeliveryManPostConfiguration() { SalePercent = salePercent });
|
||||
_postStorageContract.AddElement(post);
|
||||
var element = SPiluSZharuDbContext.GetPostFromDatabaseByPostId(post.Id);
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(DeliveryManPostConfiguration).Name));
|
||||
Assert.That((element.Configuration as DeliveryManPostConfiguration)!.SalePercent, Is.EqualTo(salePercent));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WithOperatorPostConfiguration_Test()
|
||||
{
|
||||
var personalCountTrendPremium = 50;
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), config: new OperatorPostConfiguration() { PersonalCountTrendPremium = personalCountTrendPremium });
|
||||
_postStorageContract.AddElement(post);
|
||||
var element = SPiluSZharuDbContext.GetPostFromDatabaseByPostId(post.Id);
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(OperatorPostConfiguration).Name));
|
||||
Assert.That((element.Configuration as OperatorPostConfiguration)!.PersonalCountTrendPremium, Is.EqualTo(personalCountTrendPremium));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertPostToDatabaseAndReturn(post.Id, isActual: true);
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: true);
|
||||
_postStorageContract.UpdElement(post);
|
||||
var posts = SPiluSZharuDbContext.Posts.Where(x => x.PostId == post.Id).OrderByDescending(x => x.ChangeDate);
|
||||
Assert.That(posts.Count(), Is.EqualTo(2));
|
||||
AssertElement(posts.First(), CreateModel(post.Id, isActual: true));
|
||||
AssertElement(posts.Last(), CreateModel(post.Id, isActual: false));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenActualIsFalse_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), isActual: false);
|
||||
InsertPostToDatabaseAndReturn(post.Id, isActual: true);
|
||||
_postStorageContract.UpdElement(post);
|
||||
AssertElement(GetPostFromDatabaseByPostId(post.Id), CreateModel(post.Id, isActual: true));
|
||||
var posts = SPiluSZharuDbContext.GetPostsFromDatabaseByPostId(post.Id);
|
||||
Assert.That(posts, Is.Not.Null);
|
||||
Assert.That(posts, Has.Length.EqualTo(2));
|
||||
AssertElement(posts[0], CreateModel(post.Id));
|
||||
AssertElement(posts[^1], CreateModel(post.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -211,8 +210,8 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), "New Name");
|
||||
InsertPostToDatabaseAndReturn(post.Id, postName: "name");
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), postName: post.PostName);
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(post.Id, postName: "name");
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(postName: post.PostName);
|
||||
Assert.That(() => _postStorageContract.UpdElement(post), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
@@ -220,23 +219,47 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertPostToDatabaseAndReturn(post.Id, isActual: false);
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: false);
|
||||
Assert.That(() => _postStorageContract.UpdElement(post), Throws.TypeOf<ElementDeletedException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
public void Try_UpdElement_WithDeliveryManPostConfiguration_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: true);
|
||||
_postStorageContract.DelElement(post.PostId);
|
||||
var element = GetPostFromDatabaseByPostId(post.PostId);
|
||||
var post = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn();
|
||||
var salePercent = 10;
|
||||
_postStorageContract.UpdElement(CreateModel(post.PostId, config: new DeliveryManPostConfiguration() { SalePercent = salePercent }));
|
||||
var element = SPiluSZharuDbContext.GetPostFromDatabaseByPostId(post.PostId);
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.That(!element!.IsActual);
|
||||
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(DeliveryManPostConfiguration).Name));
|
||||
Assert.That((element.Configuration as DeliveryManPostConfiguration)!.SalePercent, Is.EqualTo(salePercent));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WithOperatorPostConfiguration_Test()
|
||||
{
|
||||
var post = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn();
|
||||
var personalCountTrendPremium = 50;
|
||||
_postStorageContract.UpdElement(CreateModel(post.PostId, config: new OperatorPostConfiguration() { PersonalCountTrendPremium = personalCountTrendPremium }));
|
||||
var element = SPiluSZharuDbContext.GetPostFromDatabaseByPostId(post.PostId);
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(OperatorPostConfiguration).Name));
|
||||
Assert.That((element.Configuration as OperatorPostConfiguration)!.PersonalCountTrendPremium, Is.EqualTo(personalCountTrendPremium));
|
||||
});
|
||||
}
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var post = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(isActual: true);
|
||||
_postStorageContract.DelElement(post.PostId);
|
||||
Assert.That(SPiluSZharuDbContext.GetPostFromDatabaseByPostId(post.PostId), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
@@ -246,16 +269,16 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_DelElement_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
|
||||
var post = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
Assert.That(() => _postStorageContract.DelElement(post.PostId), Throws.TypeOf<ElementDeletedException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_ResElement_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
|
||||
var post = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
_postStorageContract.ResElement(post.PostId);
|
||||
var element = GetPostFromDatabaseByPostId(post.PostId);
|
||||
var element = SPiluSZharuDbContext.GetPostFromDatabaseByPostId(post.PostId);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element, Is.Not.Null);
|
||||
@@ -272,18 +295,10 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_ResElement_WhenRecordNotWasDeleted_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: true);
|
||||
var post = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(isActual: true);
|
||||
Assert.That(() => _postStorageContract.ResElement(post.PostId), Throws.Nothing);
|
||||
}
|
||||
|
||||
private Post InsertPostToDatabaseAndReturn(string id, string postName = "test", PostType postType = PostType.Operator, double salary = 10, bool isActual = true, DateTime? changeDate = null)
|
||||
{
|
||||
var post = new Post() { Id = Guid.NewGuid().ToString(), PostId = id, PostName = postName, PostType = postType, Salary = salary, IsActual = isActual, ChangeDate = changeDate ?? DateTime.UtcNow };
|
||||
SPiluSZharuDbContext.Posts.Add(post);
|
||||
SPiluSZharuDbContext.SaveChanges();
|
||||
return post;
|
||||
}
|
||||
|
||||
private static void AssertElement(PostDataModel? actual, Post expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
@@ -292,15 +307,12 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.PostId));
|
||||
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
|
||||
Assert.That(actual.PostType, Is.EqualTo(expected.PostType));
|
||||
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
|
||||
Assert.That(actual.IsActual, Is.EqualTo(expected.IsActual));
|
||||
Assert.That(actual.ConfigurationModel.Rate, Is.EqualTo(expected.Configuration.Rate));
|
||||
});
|
||||
}
|
||||
|
||||
private static PostDataModel CreateModel(string postId, string postName = "test", PostType postType = PostType.Operator, double salary = 10, bool isActual = false, DateTime? changeDate = null)
|
||||
=> new(postId, postName, postType, salary, isActual, changeDate ?? DateTime.UtcNow);
|
||||
|
||||
private Post? GetPostFromDatabaseByPostId(string id) => SPiluSZharuDbContext.Posts.Where(x => x.PostId == id).OrderByDescending(x => x.ChangeDate).FirstOrDefault();
|
||||
private static PostDataModel CreateModel(string postId, string postName = "test", PostType postType = PostType.Operator, PostConfiguration? config = null)
|
||||
=> new(postId, postName, postType, config ?? new PostConfiguration() { Rate = 100 });
|
||||
|
||||
private static void AssertElement(Post? actual, PostDataModel expected)
|
||||
{
|
||||
@@ -310,8 +322,7 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(actual.PostId, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
|
||||
Assert.That(actual.PostType, Is.EqualTo(expected.PostType));
|
||||
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
|
||||
Assert.That(actual.IsActual, Is.EqualTo(expected.IsActual));
|
||||
Assert.That(actual.Configuration.Rate, Is.EqualTo(expected.ConfigurationModel.Rate));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ using SPiluSZharuContracts.Enums;
|
||||
using SPiluSZharuContracts.Exceptions;
|
||||
using SPiluSZharuDatabase.Implementations;
|
||||
using SPiluSZharuDatabase.Models;
|
||||
using SPiluSZharuTests.Infrastructure;
|
||||
|
||||
namespace SPiluSZharuTests.StoragesContracts;
|
||||
|
||||
@@ -21,15 +22,15 @@ internal class ProductStorageContractTests : BaseStorageContractTest
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
SPiluSZharuDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Products\" CASCADE;");
|
||||
SPiluSZharuDbContext.RemoveProductsFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
|
||||
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2");
|
||||
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3");
|
||||
var product = SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productName: "name 1");
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productName: "name 2");
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productName: "name 3");
|
||||
var list = _productStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
@@ -47,9 +48,9 @@ internal class ProductStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_OnlyActual_Test()
|
||||
{
|
||||
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isDeleted: true);
|
||||
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2", isDeleted: false);
|
||||
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3", isDeleted: false);
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productName: "name 1", isDeleted: true);
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productName: "name 2", isDeleted: false);
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productName: "name 3", isDeleted: false);
|
||||
var list = _productStorageContract.GetList(onlyActive: true);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
@@ -62,9 +63,9 @@ internal class ProductStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_IncludeNoActual_Test()
|
||||
{
|
||||
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isDeleted: true);
|
||||
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2", isDeleted: true);
|
||||
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3", isDeleted: false);
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productName: "name 1", isDeleted: true);
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productName: "name 2", isDeleted: true);
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productName: "name 3", isDeleted: false);
|
||||
var list = _productStorageContract.GetList(onlyActive: false);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
@@ -78,10 +79,10 @@ internal class ProductStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetHistoryByProductId_WhenHaveRecords_Test()
|
||||
{
|
||||
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
|
||||
InsertProductHistoryToDatabaseAndReturn(product.Id, 20, DateTime.UtcNow.AddDays(-1));
|
||||
InsertProductHistoryToDatabaseAndReturn(product.Id, 30, DateTime.UtcNow.AddMinutes(-10));
|
||||
InsertProductHistoryToDatabaseAndReturn(product.Id, 40, DateTime.UtcNow.AddDays(1));
|
||||
var product = SPiluSZharuDbContext.InsertProductToDatabaseAndReturn();
|
||||
SPiluSZharuDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 20, DateTime.UtcNow.AddDays(-1));
|
||||
SPiluSZharuDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 30, DateTime.UtcNow.AddMinutes(-10));
|
||||
SPiluSZharuDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 40, DateTime.UtcNow.AddDays(1));
|
||||
var list = _productStorageContract.GetHistoryByProductId(product.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
@@ -90,10 +91,10 @@ internal class ProductStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetHistoryByProductId_WhenNoRecords_Test()
|
||||
{
|
||||
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
|
||||
InsertProductHistoryToDatabaseAndReturn(product.Id, 20, DateTime.UtcNow.AddDays(-1));
|
||||
InsertProductHistoryToDatabaseAndReturn(product.Id, 30, DateTime.UtcNow.AddMinutes(-10));
|
||||
InsertProductHistoryToDatabaseAndReturn(product.Id, 40, DateTime.UtcNow.AddDays(1));
|
||||
var product = SPiluSZharuDbContext.InsertProductToDatabaseAndReturn();
|
||||
SPiluSZharuDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 20, DateTime.UtcNow.AddDays(-1));
|
||||
SPiluSZharuDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 30, DateTime.UtcNow.AddMinutes(-10));
|
||||
SPiluSZharuDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 40, DateTime.UtcNow.AddDays(1));
|
||||
var list = _productStorageContract.GetHistoryByProductId(Guid.NewGuid().ToString());
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(0));
|
||||
@@ -102,42 +103,42 @@ internal class ProductStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var product = SPiluSZharuDbContext.InsertProductToDatabaseAndReturn();
|
||||
AssertElement(_productStorageContract.GetElementById(product.Id), product);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn();
|
||||
Assert.That(() => _productStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenRecordHasDeleted_Test()
|
||||
{
|
||||
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), isDeleted: true);
|
||||
var product = SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(isDeleted: true);
|
||||
Assert.That(() => _productStorageContract.GetElementById(product.Id), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenHaveRecord_Test()
|
||||
{
|
||||
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var product = SPiluSZharuDbContext.InsertProductToDatabaseAndReturn();
|
||||
AssertElement(_productStorageContract.GetElementByName(product.ProductName), product);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenNoRecord_Test()
|
||||
{
|
||||
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn();
|
||||
Assert.That(() => _productStorageContract.GetElementByName("name"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenRecordHasDeleted_Test()
|
||||
{
|
||||
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), isDeleted: true);
|
||||
var product = SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(isDeleted: true);
|
||||
Assert.That(() => _productStorageContract.GetElementById(product.ProductName), Is.Null);
|
||||
}
|
||||
|
||||
@@ -146,7 +147,7 @@ internal class ProductStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
var product = CreateModel(Guid.NewGuid().ToString(), isDeleted: false);
|
||||
_productStorageContract.AddElement(product);
|
||||
AssertElement(GetProductFromDatabaseById(product.Id), product);
|
||||
AssertElement(SPiluSZharuDbContext.GetProductFromDatabaseById(product.Id), product);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -154,30 +155,30 @@ internal class ProductStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
var product = CreateModel(Guid.NewGuid().ToString(), isDeleted: true);
|
||||
Assert.That(() => _productStorageContract.AddElement(product), Throws.Nothing);
|
||||
AssertElement(GetProductFromDatabaseById(product.Id), CreateModel(product.Id, isDeleted: false));
|
||||
AssertElement(SPiluSZharuDbContext.GetProductFromDatabaseById(product.Id), CreateModel(product.Id, isDeleted: false));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
|
||||
{
|
||||
var product = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertProductToDatabaseAndReturn(product.Id, productName: "name unique");
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(product.Id, productName: "name unique");
|
||||
Assert.That(() => _productStorageContract.AddElement(product), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var product = CreateModel(Guid.NewGuid().ToString(), "name unique", isDeleted: false);
|
||||
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), productName: product.ProductName, isDeleted: false);
|
||||
var product = CreateModel("name unique", isDeleted: false);
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productName: product.ProductName, isDeleted: false);
|
||||
Assert.That(() => _productStorageContract.AddElement(product), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameNameButOneWasDeleted_Test()
|
||||
{
|
||||
var product = CreateModel(Guid.NewGuid().ToString(), "name unique", isDeleted: false);
|
||||
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), productName: product.ProductName, isDeleted: true);
|
||||
var product = CreateModel("name unique", isDeleted: false);
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productName: product.ProductName, isDeleted: true);
|
||||
Assert.That(() => _productStorageContract.AddElement(product), Throws.Nothing);
|
||||
}
|
||||
|
||||
@@ -185,18 +186,18 @@ internal class ProductStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var product = CreateModel(Guid.NewGuid().ToString(), isDeleted: false);
|
||||
InsertProductToDatabaseAndReturn(product.Id, isDeleted: false);
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(product.Id, isDeleted: false);
|
||||
_productStorageContract.UpdElement(product);
|
||||
AssertElement(GetProductFromDatabaseById(product.Id), product);
|
||||
AssertElement(SPiluSZharuDbContext.GetProductFromDatabaseById(product.Id), product);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenIsDeletedIsTrue_Test()
|
||||
{
|
||||
var product = CreateModel(Guid.NewGuid().ToString(), isDeleted: true);
|
||||
InsertProductToDatabaseAndReturn(product.Id, isDeleted: false);
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(product.Id, isDeleted: false);
|
||||
_productStorageContract.UpdElement(product);
|
||||
AssertElement(GetProductFromDatabaseById(product.Id), CreateModel(product.Id, isDeleted: false));
|
||||
AssertElement(SPiluSZharuDbContext.GetProductFromDatabaseById(product.Id), CreateModel(product.Id, isDeleted: false));
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -209,8 +210,8 @@ internal class ProductStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var product = CreateModel(Guid.NewGuid().ToString(), "name unique", isDeleted: false);
|
||||
InsertProductToDatabaseAndReturn(product.Id, productName: "name");
|
||||
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), productName: product.ProductName);
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(product.Id, productName: "name");
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productName: product.ProductName);
|
||||
Assert.That(() => _productStorageContract.UpdElement(product), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
@@ -218,8 +219,8 @@ internal class ProductStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_WhenHaveRecordWithSameNameButOneWasDeleted_Test()
|
||||
{
|
||||
var product = CreateModel(Guid.NewGuid().ToString(), "name unique", isDeleted: false);
|
||||
InsertProductToDatabaseAndReturn(product.Id, productName: "name");
|
||||
InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), productName: product.ProductName, isDeleted: true);
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(product.Id, productName: "name");
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), productName: product.ProductName, isDeleted: true);
|
||||
Assert.That(() => _productStorageContract.UpdElement(product), Throws.Nothing);
|
||||
}
|
||||
|
||||
@@ -227,16 +228,16 @@ internal class ProductStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var product = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertProductToDatabaseAndReturn(product.Id, isDeleted: true);
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(product.Id, isDeleted: true);
|
||||
Assert.That(() => _productStorageContract.UpdElement(product), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), isDeleted: false);
|
||||
var product = SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(isDeleted: false);
|
||||
_productStorageContract.DelElement(product.Id);
|
||||
var element = GetProductFromDatabaseById(product.Id);
|
||||
var element = SPiluSZharuDbContext.GetProductFromDatabaseById(product.Id);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element, Is.Not.Null);
|
||||
@@ -253,26 +254,10 @@ internal class ProductStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_DelElement_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var product = InsertProductToDatabaseAndReturn(Guid.NewGuid().ToString(), isDeleted: true);
|
||||
var product = SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(isDeleted: true);
|
||||
Assert.That(() => _productStorageContract.DelElement(product.Id), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private Product InsertProductToDatabaseAndReturn(string id, string productName = "test", ProductType productType = ProductType.Burgers, double price = 1, bool isDeleted = false)
|
||||
{
|
||||
var product = new Product() { Id = id, ProductName = productName, ProductType = productType, Price = price, IsDeleted = isDeleted };
|
||||
SPiluSZharuDbContext.Products.Add(product);
|
||||
SPiluSZharuDbContext.SaveChanges();
|
||||
return product;
|
||||
}
|
||||
|
||||
private ProductHistory InsertProductHistoryToDatabaseAndReturn(string productId, double price, DateTime changeDate)
|
||||
{
|
||||
var productHistory = new ProductHistory() { Id = Guid.NewGuid().ToString(), ProductId = productId, OldPrice = price, ChangeDate = changeDate };
|
||||
SPiluSZharuDbContext.ProductHistories.Add(productHistory);
|
||||
SPiluSZharuDbContext.SaveChanges();
|
||||
return productHistory;
|
||||
}
|
||||
|
||||
private static void AssertElement(ProductDataModel? actual, Product expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
@@ -289,8 +274,6 @@ internal class ProductStorageContractTests : BaseStorageContractTest
|
||||
private static ProductDataModel CreateModel(string id, string productName = "test", ProductType productType = ProductType.Burgers, double price = 1, bool isDeleted = false)
|
||||
=> new(id, productName, productType, price, isDeleted);
|
||||
|
||||
private Product? GetProductFromDatabaseById(string id) => SPiluSZharuDbContext.Products.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
private static void AssertElement(Product? actual, ProductDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
|
||||
@@ -3,6 +3,8 @@ using SPiluSZharuContracts.DataModels;
|
||||
using SPiluSZharuContracts.Exceptions;
|
||||
using SPiluSZharuDatabase.Implementations;
|
||||
using SPiluSZharuDatabase.Models;
|
||||
using SPiluSZharuDatabase;
|
||||
using SPiluSZharuTests.Infrastructure;
|
||||
|
||||
namespace SPiluSZharuTests.StoragesContracts;
|
||||
|
||||
@@ -20,15 +22,15 @@ internal class RestaurantStorageContractTest : BaseStorageContractTest
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
SPiluSZharuDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Restaurants\" CASCADE;");
|
||||
}
|
||||
SPiluSZharuDbContext.RemoveRestaurantsFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var restaurant = InsertRestaurantToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
|
||||
InsertRestaurantToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2");
|
||||
InsertRestaurantToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3");
|
||||
var restaurant = SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn(restaurantName: "name 1");
|
||||
SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn(restaurantName: "name 2");
|
||||
SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn(restaurantName: "name 3");
|
||||
var list = _restaurantStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
@@ -46,35 +48,35 @@ internal class RestaurantStorageContractTest : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var restaurant = InsertRestaurantToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var restaurant = SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn();
|
||||
AssertElement(_restaurantStorageContract.GetElementById(restaurant.Id), restaurant);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
InsertRestaurantToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn();
|
||||
Assert.That(() => _restaurantStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenHaveRecord_Test()
|
||||
{
|
||||
var restaurant = InsertRestaurantToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var restaurant = SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn();
|
||||
AssertElement(_restaurantStorageContract.GetElementByName(restaurant.RestaurantName), restaurant);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenNoRecord_Test()
|
||||
{
|
||||
InsertRestaurantToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn();
|
||||
Assert.That(() => _restaurantStorageContract.GetElementByName("name"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByOldName_WhenHaveRecord_Test()
|
||||
{
|
||||
var restaurant = InsertRestaurantToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var restaurant = SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn();
|
||||
AssertElement(_restaurantStorageContract.GetElementByOldName(restaurant.PrevRestaurantName!), restaurant);
|
||||
AssertElement(_restaurantStorageContract.GetElementByOldName(restaurant.PrevPrevRestaurantName!), restaurant);
|
||||
}
|
||||
@@ -82,7 +84,7 @@ internal class RestaurantStorageContractTest : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetElementByOldName_WhenNoRecord_Test()
|
||||
{
|
||||
InsertRestaurantToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn();
|
||||
Assert.That(() => _restaurantStorageContract.GetElementByOldName("name"), Is.Null);
|
||||
}
|
||||
|
||||
@@ -98,7 +100,7 @@ internal class RestaurantStorageContractTest : BaseStorageContractTest
|
||||
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
|
||||
{
|
||||
var restaurant = CreateModel(Guid.NewGuid().ToString(), "name unique");
|
||||
InsertRestaurantToDatabaseAndReturn(restaurant.Id);
|
||||
SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn(restaurant.Id);
|
||||
Assert.That(() => _restaurantStorageContract.AddElement(restaurant), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
@@ -106,7 +108,7 @@ internal class RestaurantStorageContractTest : BaseStorageContractTest
|
||||
public void Try_AddElement_WhenHaveRecordWithSameRestaurantName_Test()
|
||||
{
|
||||
var restaurant = CreateModel(Guid.NewGuid().ToString(), "name unique");
|
||||
InsertRestaurantToDatabaseAndReturn(Guid.NewGuid().ToString(), restaurantName: restaurant.RestaurantName);
|
||||
SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn(Guid.NewGuid().ToString(), restaurantName: restaurant.RestaurantName);
|
||||
Assert.That(() => _restaurantStorageContract.AddElement(restaurant), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
@@ -114,7 +116,7 @@ internal class RestaurantStorageContractTest : BaseStorageContractTest
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var restaurant = CreateModel(Guid.NewGuid().ToString(), "name new", "test", "prev");
|
||||
InsertRestaurantToDatabaseAndReturn(restaurant.Id, restaurantName: restaurant.PrevRestaurantName!, prevRestaurantName: restaurant.PrevPrevRestaurantName!);
|
||||
SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn(restaurant.Id, restaurantName: restaurant.PrevRestaurantName!, prevRestaurantName: restaurant.PrevPrevRestaurantName!);
|
||||
_restaurantStorageContract.UpdElement(CreateModel(restaurant.Id, "name new", "some name", "some name"));
|
||||
AssertElement(GetRestaurantFromDatabase(restaurant.Id), restaurant);
|
||||
}
|
||||
@@ -123,7 +125,7 @@ internal class RestaurantStorageContractTest : BaseStorageContractTest
|
||||
public void Try_UpdElement_WhenNoChangeRestaurantName_Test()
|
||||
{
|
||||
var restaurant = CreateModel(Guid.NewGuid().ToString(), "name new", "test", "prev");
|
||||
InsertRestaurantToDatabaseAndReturn(restaurant.Id, restaurantName: restaurant.RestaurantName!, prevRestaurantName: restaurant.PrevRestaurantName!, prevPrevRestaurantName: restaurant.PrevPrevRestaurantName!);
|
||||
SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn(restaurant.Id, restaurantName: restaurant.RestaurantName!, prevRestaurantName: restaurant.PrevRestaurantName!, prevPrevRestaurantName: restaurant.PrevPrevRestaurantName!);
|
||||
_restaurantStorageContract.UpdElement(restaurant);
|
||||
AssertElement(GetRestaurantFromDatabase(restaurant.Id), restaurant);
|
||||
}
|
||||
@@ -138,8 +140,8 @@ internal class RestaurantStorageContractTest : BaseStorageContractTest
|
||||
public void Try_UpdElement_WhenHaveRecordWithSameRestaurantName_Test()
|
||||
{
|
||||
var restaurant = CreateModel(Guid.NewGuid().ToString(), "name unique");
|
||||
InsertRestaurantToDatabaseAndReturn(restaurant.Id, restaurantName: "some name");
|
||||
InsertRestaurantToDatabaseAndReturn(Guid.NewGuid().ToString(), restaurantName: restaurant.RestaurantName);
|
||||
SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn(restaurant.Id, restaurantName: "some name");
|
||||
SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn(restaurantName: restaurant.RestaurantName);
|
||||
Assert.That(() => _restaurantStorageContract.UpdElement(restaurant), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
@@ -149,14 +151,6 @@ internal class RestaurantStorageContractTest : BaseStorageContractTest
|
||||
Assert.That(() => _restaurantStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private Restaurant InsertRestaurantToDatabaseAndReturn(string id, string restaurantName = "test", string prevRestaurantName = "prev", string prevPrevRestaurantName = "prevPrev")
|
||||
{
|
||||
var restaurant = new Restaurant() { Id = id, RestaurantName = restaurantName, PrevRestaurantName = prevRestaurantName, PrevPrevRestaurantName = prevPrevRestaurantName };
|
||||
SPiluSZharuDbContext.Restaurants.Add(restaurant);
|
||||
SPiluSZharuDbContext.SaveChanges();
|
||||
return restaurant;
|
||||
}
|
||||
|
||||
private static void AssertElement(RestaurantDataModel? actual, Restaurant expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
using SPiluSZharuContracts.DataModels;
|
||||
using SPiluSZharuDatabase.Implementations;
|
||||
using SPiluSZharuDatabase.Models;
|
||||
using SPiluSZharuTests.Infrastructure;
|
||||
|
||||
namespace SPiluSZharuTests.StoragesContracts;
|
||||
|
||||
@@ -15,26 +16,26 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
|
||||
public void SetUp()
|
||||
{
|
||||
_salaryStorageContract = new SalaryStorageContract(SPiluSZharuDbContext);
|
||||
_worker = InsertWorkerToDatabaseAndReturn();
|
||||
_worker = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
SPiluSZharuDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Salaries\" CASCADE;");
|
||||
SPiluSZharuDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Workers\" CASCADE;");
|
||||
SPiluSZharuDbContext.RemoveSalariesFromDatabase();
|
||||
SPiluSZharuDbContext.RemoveWorkersFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var salary = InsertSalaryToDatabaseAndReturn(_worker.Id, workerSalary: 100);
|
||||
InsertSalaryToDatabaseAndReturn(_worker.Id);
|
||||
InsertSalaryToDatabaseAndReturn(_worker.Id);
|
||||
var salary = SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, workerSalary: 100);
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id);
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id);
|
||||
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-10), DateTime.UtcNow.AddDays(10));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
AssertElement(list.First(), salary);
|
||||
AssertElement(list.Single(x => x.Salary == salary.WorkerSalary), salary);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -48,12 +49,12 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_OnlyInDatePeriod_Test()
|
||||
{
|
||||
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-5));
|
||||
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(5));
|
||||
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-5));
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(5));
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
@@ -65,10 +66,10 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByWorker_Test()
|
||||
{
|
||||
var worker = InsertWorkerToDatabaseAndReturn("name 2", "+7(555)555-55-55");
|
||||
InsertSalaryToDatabaseAndReturn(_worker.Id);
|
||||
InsertSalaryToDatabaseAndReturn(_worker.Id);
|
||||
InsertSalaryToDatabaseAndReturn(worker.Id);
|
||||
var worker = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn("name 2", phoneNumber: "+7(555)555-55-55");
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id);
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id);
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(worker.Id);
|
||||
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1), _worker.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
@@ -81,13 +82,13 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByWorkerOnlyInDatePeriod_Test()
|
||||
{
|
||||
var worker = InsertWorkerToDatabaseAndReturn("name 2", "+7(555)555-55-55");
|
||||
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
var worker = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "name 2", phoneNumber: "+7(555)555-55-55");
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1), _worker.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
@@ -102,23 +103,7 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
var salary = CreateModel(_worker.Id);
|
||||
_salaryStorageContract.AddElement(salary);
|
||||
AssertElement(GetSalaryFromDatabaseByWorkerId(_worker.Id), salary);
|
||||
}
|
||||
|
||||
private Worker InsertWorkerToDatabaseAndReturn(string workerFIO = "fio", string phoneNumber = "+7(777)777-77-77")
|
||||
{
|
||||
var worker = new Worker() { Id = Guid.NewGuid().ToString(), FIO = workerFIO, PostId = Guid.NewGuid().ToString(), PhoneNumber = phoneNumber, IsDeleted = false };
|
||||
SPiluSZharuDbContext.Workers.Add(worker);
|
||||
SPiluSZharuDbContext.SaveChanges();
|
||||
return worker;
|
||||
}
|
||||
|
||||
private Salary InsertSalaryToDatabaseAndReturn(string workerId, double workerSalary = 1, DateTime? salaryDate = null)
|
||||
{
|
||||
var salary = new Salary() { WorkerId = workerId, WorkerSalary = workerSalary, SalaryDate = salaryDate ?? DateTime.UtcNow };
|
||||
SPiluSZharuDbContext.Salaries.Add(salary);
|
||||
SPiluSZharuDbContext.SaveChanges();
|
||||
return salary;
|
||||
AssertElement(SPiluSZharuDbContext.GetSalariesFromDatabaseByWorkerId(_worker.Id).First(), salary);
|
||||
}
|
||||
|
||||
private static void AssertElement(SalaryDataModel? actual, Salary expected)
|
||||
@@ -134,8 +119,6 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
|
||||
private static SalaryDataModel CreateModel(string workerId, double workerSalary = 1, DateTime? salaryDate = null)
|
||||
=> new(workerId, salaryDate ?? DateTime.UtcNow, workerSalary);
|
||||
|
||||
private Salary? GetSalaryFromDatabaseByWorkerId(string id) => SPiluSZharuDbContext.Salaries.FirstOrDefault(x => x.WorkerId == id);
|
||||
|
||||
private static void AssertElement(Salary? actual, SalaryDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
|
||||
@@ -4,13 +4,14 @@ using SPiluSZharuContracts.Enums;
|
||||
using SPiluSZharuContracts.Exceptions;
|
||||
using SPiluSZharuDatabase.Implementations;
|
||||
using SPiluSZharuDatabase.Models;
|
||||
using SPiluSZharuTests.Infrastructure;
|
||||
|
||||
namespace SPiluSZharuTests.StoragesContracts;
|
||||
|
||||
[TestFixture]
|
||||
internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
private SaleStorageContract _saletStorageContract;
|
||||
private SaleStorageContract _saleStorageContract;
|
||||
private Restaurant _restaurant;
|
||||
private Worker _worker;
|
||||
private Product _product;
|
||||
@@ -18,28 +19,28 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_saletStorageContract = new SaleStorageContract(SPiluSZharuDbContext);
|
||||
_restaurant = InsertRestaurantToDatabaseAndReturn();
|
||||
_worker = InsertWorkerToDatabaseAndReturn();
|
||||
_product = InsertProductToDatabaseAndReturn();
|
||||
_saleStorageContract = new SaleStorageContract(SPiluSZharuDbContext);
|
||||
_restaurant = SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn();
|
||||
_worker = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
_product = SPiluSZharuDbContext.InsertProductToDatabaseAndReturn();
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
SPiluSZharuDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Sales\" CASCADE;");
|
||||
SPiluSZharuDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Restaurants\" CASCADE;");
|
||||
SPiluSZharuDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Workers\" CASCADE;");
|
||||
SPiluSZharuDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Products\" CASCADE;");
|
||||
SPiluSZharuDbContext.RemoveSalesFromDatabase();
|
||||
SPiluSZharuDbContext.RemoveWorkersFromDatabase();
|
||||
SPiluSZharuDbContext.RemoveRestaurantsFromDatabase();
|
||||
SPiluSZharuDbContext.RemoveProductsFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 5)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, null, products: [(_product.Id, 10)]);
|
||||
var list = _saletStorageContract.GetList();
|
||||
var sale = SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1, 1.2)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 5, 1.2)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, null, products: [(_product.Id, 10, 1.2)]);
|
||||
var list = _saleStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
AssertElement(list.First(x => x.Id == sale.Id), sale);
|
||||
@@ -48,7 +49,7 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_WhenNoRecords_Test()
|
||||
{
|
||||
var list = _saletStorageContract.GetList();
|
||||
var list = _saleStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
@@ -56,11 +57,11 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByPeriod_Test()
|
||||
{
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), products: [(_product.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(3), products: [(_product.Id, 1)]);
|
||||
var list = _saletStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1));
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), products: [(_product.Id, 1, 1.2)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1, 1.2)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1, 1.2)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(3), products: [(_product.Id, 1, 1.2)]);
|
||||
var list = _saleStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
}
|
||||
@@ -68,11 +69,11 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByWorkerId_Test()
|
||||
{
|
||||
var worker = InsertWorkerToDatabaseAndReturn("Other worker", "+7(555)555-55-55");
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(worker.Id, null, products: [(_product.Id, 1)]);
|
||||
var list = _saletStorageContract.GetList(workerId: _worker.Id);
|
||||
var worker = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "Other worker", phoneNumber: "+7(555)555-55-55");
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1, 1.2)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1, 1.2)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(worker.Id, null, products: [(_product.Id, 1, 1.2)]);
|
||||
var list = _saleStorageContract.GetList(workerId: _worker.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
Assert.That(list.All(x => x.WorkerId == _worker.Id));
|
||||
@@ -81,12 +82,12 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByRestaurantId_Test()
|
||||
{
|
||||
var restaurant = InsertRestaurantToDatabaseAndReturn("Other restaurant");
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, restaurant.Id, products: [(_product.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, null, products: [(_product.Id, 1)]);
|
||||
var list = _saletStorageContract.GetList(restaurantId: _restaurant.Id);
|
||||
var restaurant = SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn(restaurantName: "Other restaurant");
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1, 1.2)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1, 1.2)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, restaurant.Id, products: [(_product.Id, 1, 1.2)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, null, products: [(_product.Id, 1, 1.2)]);
|
||||
var list = _saleStorageContract.GetList(restaurantId: _restaurant.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
Assert.That(list.All(x => x.RestaurantId == _restaurant.Id));
|
||||
@@ -95,31 +96,31 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByProductId_Test()
|
||||
{
|
||||
var product = InsertProductToDatabaseAndReturn("Other name");
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 5)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1), (product.Id, 4)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, null, products: [(product.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, null, products: [(product.Id, 1), (_product.Id, 1)]);
|
||||
var list = _saletStorageContract.GetList(productId: _product.Id);
|
||||
var product = SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productName: "Other name");
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 5, 1.2)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1, 1.2), (product.Id, 4, 1.2)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, null, products: [(product.Id, 1, 1.2)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, null, products: [(product.Id, 1, 1.2), (_product.Id, 1, 1.2)]);
|
||||
var list = _saleStorageContract.GetList(productId: _product.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
Assert.That(list.All(x => x.Products.Any(y => y.ProductId == _product.Id)));
|
||||
Assert.That(list.All(x => x.Products!.Any(y => y.ProductId == _product.Id)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByAllParameters_Test()
|
||||
{
|
||||
var worker = InsertWorkerToDatabaseAndReturn("Other worker", "+7(555)555-55-55");
|
||||
var restaurant = InsertRestaurantToDatabaseAndReturn("Other restaurant");
|
||||
var product = InsertProductToDatabaseAndReturn("Other name");
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), products: [(_product.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(worker.Id, null, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(worker.Id, _restaurant.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(worker.Id, _restaurant.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(product.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, restaurant.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(product.Id, 1)]);
|
||||
InsertSaleToDatabaseAndReturn(worker.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1)]);
|
||||
var list = _saletStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1), workerId: _worker.Id, restaurantId: _restaurant.Id, productId: product.Id);
|
||||
var worker = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "Other worker", phoneNumber: "+7(555)555-55-55");
|
||||
var restaurant = SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn(restaurantName: "Other restaurant");
|
||||
var product = SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productName: "Other name");
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), products: [(_product.Id, 1, 1.2)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(worker.Id, null, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1, 1.2)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(worker.Id, _restaurant.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_product.Id, 1, 1.2)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(worker.Id, _restaurant.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(product.Id, 1, 1.2)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, restaurant.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1, 1.2)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(product.Id, 1, 1.2)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(worker.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_product.Id, 1, 1.2)]);
|
||||
var list = _saleStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1), workerId: _worker.Id, restaurantId: _restaurant.Id, productId: product.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(1));
|
||||
}
|
||||
@@ -127,46 +128,46 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1)]);
|
||||
AssertElement(_saletStorageContract.GetElementById(sale.Id), sale);
|
||||
var sale = SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1, 1.2)]);
|
||||
AssertElement(_saleStorageContract.GetElementById(sale.Id), sale);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1)]);
|
||||
Assert.That(() => _saletStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1, 1.2)]);
|
||||
Assert.That(() => _saleStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenRecordHasCanceled_Test()
|
||||
{
|
||||
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1)], isCancel: true);
|
||||
AssertElement(_saletStorageContract.GetElementById(sale.Id), sale);
|
||||
var sale = SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1, 1.2)], isCancel: true);
|
||||
AssertElement(_saleStorageContract.GetElementById(sale.Id), sale);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var sale = CreateModel(Guid.NewGuid().ToString(), _worker.Id, _restaurant.Id, 1, false, [_product.Id]);
|
||||
_saletStorageContract.AddElement(sale);
|
||||
AssertElement(GetSaleFromDatabaseById(sale.Id), sale);
|
||||
var sale = CreateModel(Guid.NewGuid().ToString(), _worker.Id, _restaurant.Id, false, [_product.Id]);
|
||||
_saleStorageContract.AddElement(sale);
|
||||
AssertElement(SPiluSZharuDbContext.GetSaleFromDatabaseById(sale.Id), sale);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenIsDeletedIsTrue_Test()
|
||||
{
|
||||
var sale = CreateModel(Guid.NewGuid().ToString(), _worker.Id, _restaurant.Id, 1, true, [_product.Id]);
|
||||
Assert.That(() => _saletStorageContract.AddElement(sale), Throws.Nothing);
|
||||
AssertElement(GetSaleFromDatabaseById(sale.Id), CreateModel(sale.Id, _worker.Id, _restaurant.Id, 1, false, [_product.Id]));
|
||||
var sale = CreateModel(Guid.NewGuid().ToString(), _worker.Id, _restaurant.Id, true, [_product.Id]);
|
||||
Assert.That(() => _saleStorageContract.AddElement(sale), Throws.Nothing);
|
||||
AssertElement(SPiluSZharuDbContext.GetSaleFromDatabaseById(sale.Id), CreateModel(sale.Id, _worker.Id, _restaurant.Id, false, [_product.Id]));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1)], isCancel: false);
|
||||
_saletStorageContract.DelElement(sale.Id);
|
||||
var element = GetSaleFromDatabaseById(sale.Id);
|
||||
var sale = SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1, 1.2)], isCancel: false);
|
||||
_saleStorageContract.DelElement(sale.Id);
|
||||
var element = SPiluSZharuDbContext.GetSaleFromDatabaseById(sale.Id);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element, Is.Not.Null);
|
||||
@@ -177,53 +178,14 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_DelElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _saletStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
Assert.That(() => _saleStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenRecordWasCanceled_Test()
|
||||
{
|
||||
var sale = InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1)], isCancel: true);
|
||||
Assert.That(() => _saletStorageContract.DelElement(sale.Id), Throws.TypeOf<ElementDeletedException>());
|
||||
}
|
||||
|
||||
private Restaurant InsertRestaurantToDatabaseAndReturn(string restaurantName = "test")
|
||||
{
|
||||
var restaurant = new Restaurant() { Id = Guid.NewGuid().ToString(), RestaurantName = restaurantName };
|
||||
SPiluSZharuDbContext.Restaurants.Add(restaurant);
|
||||
SPiluSZharuDbContext.SaveChanges();
|
||||
return restaurant;
|
||||
}
|
||||
|
||||
private Worker InsertWorkerToDatabaseAndReturn(string fio = "test", string phoneNumber = "+7(777)777-77-77")
|
||||
{
|
||||
var worker = new Worker() { Id = Guid.NewGuid().ToString(), FIO = fio, PostId = Guid.NewGuid().ToString(), PhoneNumber = phoneNumber };
|
||||
SPiluSZharuDbContext.Workers.Add(worker);
|
||||
SPiluSZharuDbContext.SaveChanges();
|
||||
return worker;
|
||||
}
|
||||
|
||||
private Product InsertProductToDatabaseAndReturn(string productName = "test", ProductType productType = ProductType.Burgers, double price = 1, bool isDeleted = false)
|
||||
{
|
||||
var product = new Product() { Id = Guid.NewGuid().ToString(), ProductName = productName, ProductType = productType, Price = price, IsDeleted = isDeleted };
|
||||
SPiluSZharuDbContext.Products.Add(product);
|
||||
SPiluSZharuDbContext.SaveChanges();
|
||||
return product;
|
||||
}
|
||||
|
||||
private Sale InsertSaleToDatabaseAndReturn(string workerId, string? restaurantId, DateTime? saleDate = null, double sum = 1, bool isCancel = false, List<(string, int)>? products = null)
|
||||
{
|
||||
var sale = new Sale() { WorkerId = workerId, RestaurantId = restaurantId, SaleDate = saleDate ?? DateTime.UtcNow, Sum = sum, IsCancel = isCancel, SaleProducts = [] };
|
||||
if (products is not null)
|
||||
{
|
||||
foreach (var elem in products)
|
||||
{
|
||||
sale.SaleProducts.Add(new SaleProduct { ProductId = elem.Item1, SaleId = sale.Id, Count = elem.Item2 });
|
||||
}
|
||||
}
|
||||
SPiluSZharuDbContext.Sales.Add(sale);
|
||||
SPiluSZharuDbContext.SaveChanges();
|
||||
return sale;
|
||||
var sale = SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _restaurant.Id, products: [(_product.Id, 1, 1.2)], isCancel: true);
|
||||
Assert.That(() => _saleStorageContract.DelElement(sale.Id), Throws.TypeOf<ElementDeletedException>());
|
||||
}
|
||||
|
||||
private static void AssertElement(SaleDataModel? actual, Sale expected)
|
||||
@@ -256,14 +218,12 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
}
|
||||
}
|
||||
|
||||
private static SaleDataModel CreateModel(string id, string workerId, string? restaurantId, double sum, bool isCancel, List<string> productIds)
|
||||
private static SaleDataModel CreateModel(string id, string workerId, string? restaurantId, bool isCancel, List<string> productIds)
|
||||
{
|
||||
var products = productIds.Select(x => new SaleProductDataModel(id, x, 1)).ToList();
|
||||
return new(id, workerId, restaurantId, sum, isCancel, products);
|
||||
var products = productIds.Select(x => new SaleProductDataModel(id, x, 1, 1.1)).ToList();
|
||||
return new(id, workerId, restaurantId, isCancel, products);
|
||||
}
|
||||
|
||||
private Sale? GetSaleFromDatabaseById(string id) => SPiluSZharuDbContext.Sales.Include(x => x.SaleProducts).FirstOrDefault(x => x.Id == id);
|
||||
|
||||
private static void AssertElement(Sale? actual, SaleDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
|
||||
@@ -3,6 +3,7 @@ using SPiluSZharuContracts.DataModels;
|
||||
using SPiluSZharuContracts.Exceptions;
|
||||
using SPiluSZharuDatabase.Implementations;
|
||||
using SPiluSZharuDatabase.Models;
|
||||
using SPiluSZharuTests.Infrastructure;
|
||||
|
||||
namespace SPiluSZharuTests.StoragesContracts;
|
||||
|
||||
@@ -20,19 +21,19 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
SPiluSZharuDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Workers\" CASCADE;");
|
||||
SPiluSZharuDbContext.RemoveWorkersFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", phoneNumber:"+7(555)555-55-55");
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", phoneNumber: "+7(333)333-33-33");
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", phoneNumber: "+7(111)111-11-11");
|
||||
var worker = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", phoneNumber:"+7(555)555-55-55");
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", phoneNumber: "+7(333)333-33-33");
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", phoneNumber: "+7(111)111-11-11");
|
||||
var list = _workerStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
AssertElement(list.First(), worker);
|
||||
AssertElement(list.First(x => x.FIO == worker.FIO), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -47,9 +48,9 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
public void Try_GetList_ByPostId_Test()
|
||||
{
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", postId, "+7(555)555-55-55");
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", postId, "+7(333)333-33-33");
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", phoneNumber: "+7(111)111-11-11");
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: postId, phoneNumber: "+7(555)555-55-55");
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: postId, phoneNumber: "+7(333)333-33-33");
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", phoneNumber: "+7(111)111-11-11");
|
||||
var list = _workerStorageContract.GetList(postId: postId);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
@@ -59,10 +60,10 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByBirthDate_Test()
|
||||
{
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", phoneNumber: "+7(555)555-55-55", birthDate: DateTime.UtcNow.AddYears(-25));
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", phoneNumber: "+7(333)333-33-33", birthDate: DateTime.UtcNow.AddYears(-21));
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", phoneNumber: "+7(111)111-11-11", birthDate: DateTime.UtcNow.AddYears(-20));
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", phoneNumber: "+7(222)222-22-22", birthDate: DateTime.UtcNow.AddYears(-19));
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", phoneNumber: "+7(555)555-55-55", birthDate: DateTime.UtcNow.AddYears(-25));
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", phoneNumber: "+7(333)333-33-33", birthDate: DateTime.UtcNow.AddYears(-21));
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", phoneNumber: "+7(111)111-11-11", birthDate: DateTime.UtcNow.AddYears(-20));
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", phoneNumber: "+7(222)222-22-22", birthDate: DateTime.UtcNow.AddYears(-19));
|
||||
var list = _workerStorageContract.GetList(fromBirthDate: DateTime.UtcNow.AddYears(-21).AddMinutes(-1), toBirthDate: DateTime.UtcNow.AddYears(-20).AddMinutes(1));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
@@ -71,10 +72,10 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByEmploymentDate_Test()
|
||||
{
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", phoneNumber: "+7(555)555-55-55", employmentDate: DateTime.UtcNow.AddDays(-2));
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", phoneNumber: "+7(333)333-33-33", employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", phoneNumber: "+7(111)111-11-11", employmentDate: DateTime.UtcNow.AddDays(1));
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", phoneNumber: "+7(222)222-22-22", employmentDate: DateTime.UtcNow.AddDays(2));
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", phoneNumber: "+7(555)555-55-55", employmentDate: DateTime.UtcNow.AddDays(-2));
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", phoneNumber: "+7(333)333-33-33", employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", phoneNumber: "+7(111)111-11-11", employmentDate: DateTime.UtcNow.AddDays(1));
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", phoneNumber: "+7(222)222-22-22", employmentDate: DateTime.UtcNow.AddDays(2));
|
||||
var list = _workerStorageContract.GetList(fromEmploymentDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-1), toEmploymentDate: DateTime.UtcNow.AddDays(1).AddMinutes(1));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
@@ -84,10 +85,10 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
public void Try_GetList_ByAllParameters_Test()
|
||||
{
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", postId, "+7(555)555-55-55", birthDate: DateTime.UtcNow.AddYears(-25), employmentDate: DateTime.UtcNow.AddDays(-2));
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", postId, "+7(333)333-33-33", birthDate: DateTime.UtcNow.AddYears(-22), employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", postId, "+7(111)111-11-11", birthDate: DateTime.UtcNow.AddYears(-21), employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", phoneNumber: "+7(222)222-22-22", birthDate: DateTime.UtcNow.AddYears(-20), employmentDate: DateTime.UtcNow.AddDays(1));
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: postId, phoneNumber: "+7(555)555-55-55", birthDate: DateTime.UtcNow.AddYears(-25), employmentDate: DateTime.UtcNow.AddDays(-2));
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: postId, phoneNumber: "+7(333)333-33-33", birthDate: DateTime.UtcNow.AddYears(-22), employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", postId: postId, phoneNumber: "+7(111)111-11-11", birthDate: DateTime.UtcNow.AddYears(-21), employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", phoneNumber: "+7(222)222-22-22", birthDate: DateTime.UtcNow.AddYears(-20), employmentDate: DateTime.UtcNow.AddDays(1));
|
||||
var list = _workerStorageContract.GetList(postId: postId, fromBirthDate: DateTime.UtcNow.AddYears(-21).AddMinutes(-1), toBirthDate: DateTime.UtcNow.AddYears(-20).AddMinutes(1), fromEmploymentDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-1), toEmploymentDate: DateTime.UtcNow.AddDays(1).AddMinutes(1));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(1));
|
||||
@@ -96,7 +97,7 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var worker = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
AssertElement(_workerStorageContract.GetElementById(worker.Id), worker);
|
||||
}
|
||||
|
||||
@@ -109,7 +110,7 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetElementByFIO_WhenHaveRecord_Test()
|
||||
{
|
||||
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var worker = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
AssertElement(_workerStorageContract.GetElementByFIO(worker.FIO), worker);
|
||||
}
|
||||
|
||||
@@ -122,14 +123,14 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetElementByPhoneNumber_WhenHaveRecord_Test()
|
||||
{
|
||||
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var worker = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
AssertElement(_workerStorageContract.GetElementByPhoneNumber(worker.PhoneNumber), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByPhoneNumber_WhenNoRecord_Test()
|
||||
{
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
Assert.That(() => _workerStorageContract.GetElementByPhoneNumber("+7(888)888-88-88"), Is.Null);
|
||||
}
|
||||
|
||||
@@ -138,24 +139,24 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString());
|
||||
_workerStorageContract.AddElement(worker);
|
||||
AssertElement(GetWorkerFromDatabase(worker.Id), worker);
|
||||
AssertElement(SPiluSZharuDbContext.GetWorkerFromDatabaseById(worker.Id), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertWorkerToDatabaseAndReturn(worker.Id);
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(worker.Id);
|
||||
Assert.That(() => _workerStorageContract.AddElement(worker), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+7(555)555-55-55");
|
||||
InsertWorkerToDatabaseAndReturn(worker.Id);
|
||||
var worker = CreateModel(Guid.NewGuid().ToString(), "New Fio", phoneNumber: "+7(555)555-55-55");
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(worker.Id);
|
||||
_workerStorageContract.UpdElement(worker);
|
||||
AssertElement(GetWorkerFromDatabase(worker.Id), worker);
|
||||
AssertElement(SPiluSZharuDbContext.GetWorkerFromDatabaseById(worker.Id), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -168,16 +169,16 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_WhenNoRecordWasDeleted_Test()
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString(), "+7(555)555-55-55");
|
||||
InsertWorkerToDatabaseAndReturn(worker.Id, isDeleted: true);
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(worker.Id, isDeleted: true);
|
||||
Assert.That(() => _workerStorageContract.UpdElement(worker), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var worker = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
_workerStorageContract.DelElement(worker.Id);
|
||||
var element = GetWorkerFromDatabase(worker.Id);
|
||||
var element = SPiluSZharuDbContext.GetWorkerFromDatabaseById(worker.Id);
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.That(element.IsDeleted);
|
||||
}
|
||||
@@ -192,18 +193,47 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
public void Try_DelElement_WhenNoRecordWasDeleted_Test()
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertWorkerToDatabaseAndReturn(worker.Id, isDeleted: true);
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(worker.Id, isDeleted: true);
|
||||
Assert.That(() => _workerStorageContract.DelElement(worker.Id), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private Worker InsertWorkerToDatabaseAndReturn(string id, string fio = "test", string? postId = null, string phoneNumber = "+7(777)777-77-77", DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false)
|
||||
[Test]
|
||||
public void Try_GetWorkerTrend_WhenNoNewAndDeletedWorkers_Test()
|
||||
{
|
||||
var worker = new Worker() { Id = id, FIO = fio, PostId = postId ?? Guid.NewGuid().ToString(), PhoneNumber = phoneNumber, BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-20), EmploymentDate = employmentDate ?? DateTime.UtcNow, IsDeleted = isDeleted };
|
||||
SPiluSZharuDbContext.Workers.Add(worker);
|
||||
SPiluSZharuDbContext.SaveChanges();
|
||||
return worker;
|
||||
var startDate = DateTime.UtcNow.AddDays(-5);
|
||||
var endDate = DateTime.UtcNow.AddDays(-3);
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-10));
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(phoneNumber: "+7(555)555-55-55", employmentDate: DateTime.UtcNow.AddDays(-10), isDeleted: true, dateDelete: DateTime.UtcNow.AddDays(-9));
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(phoneNumber: "+7(333)333-33-33", employmentDate: DateTime.UtcNow.AddDays(-10), isDeleted: true, dateDelete: DateTime.UtcNow.AddDays(-1));
|
||||
var count = _workerStorageContract.GetWorkerTrend(startDate, endDate);
|
||||
Assert.That(count, Is.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetWorkerTrend_WhenHaveNewAndNoDeletedWorkers_Test()
|
||||
{
|
||||
var startDate = DateTime.UtcNow.AddDays(-5);
|
||||
var endDate = DateTime.UtcNow.AddDays(-3);
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-10));
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(phoneNumber: "+7(555)555-55-55", employmentDate: DateTime.UtcNow.AddDays(-4));
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(phoneNumber: "+7(333)333-33-33", employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
var count = _workerStorageContract.GetWorkerTrend(startDate, endDate);
|
||||
Assert.That(count, Is.EqualTo(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetWorkerTrend_WhenNoNewAndHaveDeletedWorkers_Test()
|
||||
{
|
||||
var startDate = DateTime.UtcNow.AddDays(-5);
|
||||
var endDate = DateTime.UtcNow.AddDays(-3);
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-10), isDeleted: true, dateDelete: DateTime.UtcNow.AddDays(-9));
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(phoneNumber: "+7(555)555-55-55", employmentDate: DateTime.UtcNow.AddDays(-10), isDeleted: true, dateDelete: DateTime.UtcNow.AddDays(-4));
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(phoneNumber: "+7(333)333-33-33", employmentDate: DateTime.UtcNow.AddDays(-10), isDeleted: true, dateDelete: DateTime.UtcNow.AddDays(-1));
|
||||
var count = _workerStorageContract.GetWorkerTrend(startDate, endDate);
|
||||
Assert.That(count, Is.EqualTo(-1));
|
||||
}
|
||||
|
||||
|
||||
private static void AssertElement(WorkerDataModel? actual, Worker expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
@@ -212,6 +242,7 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.PostId, Is.EqualTo(expected.PostId));
|
||||
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
|
||||
Assert.That(actual.PhoneNumber, Is.EqualTo(expected.PhoneNumber));
|
||||
Assert.That(actual.BirthDate, Is.EqualTo(expected.BirthDate));
|
||||
Assert.That(actual.EmploymentDate, Is.EqualTo(expected.EmploymentDate));
|
||||
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
|
||||
@@ -221,8 +252,6 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
private static WorkerDataModel CreateModel(string id, string fio = "fio", string? postId = null, string phoneNumber = "+7(777)777-77-77", DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false) =>
|
||||
new(id, fio, postId ?? Guid.NewGuid().ToString(), phoneNumber, birthDate ?? DateTime.UtcNow.AddYears(-20), employmentDate ?? DateTime.UtcNow, isDeleted);
|
||||
|
||||
private Worker? GetWorkerFromDatabase(string id) => SPiluSZharuDbContext.Workers.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
private static void AssertElement(Worker? actual, WorkerDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
@@ -231,9 +260,11 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.PostId, Is.EqualTo(expected.PostId));
|
||||
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
|
||||
Assert.That(actual.PhoneNumber, Is.EqualTo(expected.PhoneNumber));
|
||||
Assert.That(actual.BirthDate, Is.EqualTo(expected.BirthDate));
|
||||
Assert.That(actual.EmploymentDate, Is.EqualTo(expected.EmploymentDate));
|
||||
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
|
||||
Assert.That(actual.DateOfDelete.HasValue, Is.EqualTo(expected.IsDeleted));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
using SPiluSZharuDatabase;
|
||||
using SPiluSZharuTests.Infrastructure;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.AspNetCore.TestHost;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace SPiluSZharuTests.WebApiControllersTests;
|
||||
|
||||
internal class BaseWebApiControllerTest
|
||||
{
|
||||
private WebApplicationFactory<Program> _webApplication;
|
||||
|
||||
protected HttpClient HttpClient { get; private set; }
|
||||
|
||||
protected SPiluSZharuDbContext SPiluSZharuDbContext { get; private set; }
|
||||
|
||||
protected static readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
_webApplication = new CustomWebApplicationFactory<Program>();
|
||||
HttpClient = _webApplication
|
||||
.WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.ConfigureTestServices(services =>
|
||||
{
|
||||
using var loggerFactory = new LoggerFactory();
|
||||
loggerFactory.AddSerilog(new LoggerConfiguration()
|
||||
.ReadFrom.Configuration(new ConfigurationBuilder()
|
||||
.SetBasePath(Directory.GetCurrentDirectory())
|
||||
.AddJsonFile("appsettings.json")
|
||||
.Build())
|
||||
.CreateLogger());
|
||||
services.AddSingleton(loggerFactory);
|
||||
});
|
||||
})
|
||||
.CreateClient();
|
||||
|
||||
var request = HttpClient.GetAsync("/login/user").GetAwaiter().GetResult();
|
||||
var data = request.Content.ReadAsStringAsync().GetAwaiter().GetResult();
|
||||
HttpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {data}");
|
||||
|
||||
SPiluSZharuDbContext = _webApplication.Services.GetRequiredService<SPiluSZharuDbContext>();
|
||||
SPiluSZharuDbContext.Database.EnsureDeleted();
|
||||
SPiluSZharuDbContext.Database.EnsureCreated();
|
||||
}
|
||||
|
||||
[OneTimeTearDown]
|
||||
public void OneTimeTearDown()
|
||||
{
|
||||
SPiluSZharuDbContext?.Database.EnsureDeleted();
|
||||
SPiluSZharuDbContext?.Dispose();
|
||||
HttpClient?.Dispose();
|
||||
_webApplication?.Dispose();
|
||||
}
|
||||
|
||||
protected static async Task<T?> GetModelFromResponseAsync<T>(HttpResponseMessage response) =>
|
||||
JsonSerializer.Deserialize<T>(await response.Content.ReadAsStringAsync(), JsonSerializerOptions);
|
||||
|
||||
protected static StringContent MakeContent(object model) =>
|
||||
new(JsonSerializer.Serialize(model), Encoding.UTF8, "application/json");
|
||||
}
|
||||
@@ -0,0 +1,552 @@
|
||||
using SPiluSZharuContracts.BindingModels;
|
||||
using SPiluSZharuContracts.Enums;
|
||||
using SPiluSZharuContracts.Infrastructure.PostConfiguration;
|
||||
using SPiluSZharuContracts.ViewModels;
|
||||
using SPiluSZharuDatabase.Models;
|
||||
using SPiluSZharuTests.Infrastructure;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace SPiluSZharuTests.WebApiControllersTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class PostControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
SPiluSZharuDbContext.RemovePostsFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetRecords_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var post = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(postName: "name 1");
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(postName: "name 2");
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(postName: "name 3");
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/posts");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<PostViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
});
|
||||
AssertElement(data.First(x => x.Id == post.PostId), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetRecords_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/posts");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<RestaurantViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetHistory_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
|
||||
var post = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posthistory/{postId}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<PostViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
});
|
||||
AssertElement(data.First(x => x.Id == post.PostId), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetHistory_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posthistory/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<PostViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetHistory_WhenWrongData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posthistory/id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var post = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posts/{post.PostId}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<PostViewModel>(response), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posts/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenRecordWasDeleted_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
var post = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posts/{post.PostId}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var post = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posts/{post.PostName}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<PostViewModel>(response), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posts/New%20Name");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenRecordWasDeleted_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
var post = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/posts/{post.PostName}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn();
|
||||
var postModel = CreateModel();
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(SPiluSZharuDbContext.GetPostFromDatabaseByPostId(postModel.Id!), postModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModel = CreateModel();
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(postModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModel = CreateModel(postName: "unique name");
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(postName: postModel.PostName!);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.DeliveryMan.ToString(), ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
|
||||
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.DeliveryMan.ToString(), ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
|
||||
var postModelWithPostTypeIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = string.Empty, ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
|
||||
var postModelWithSalaryIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.DeliveryMan.ToString(), ConfigurationJson = null };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithIdIncorrect));
|
||||
var responseWithNameIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithNameIncorrect));
|
||||
var responseWithPostTypeIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithPostTypeIncorrect));
|
||||
var responseWithSalaryIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithSalaryIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
|
||||
Assert.That(responseWithNameIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
Assert.That(responseWithPostTypeIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Type is incorrect");
|
||||
Assert.That(responseWithSalaryIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Salary is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(string.Empty));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WithDeliveryManPostConfiguration_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var salePercent = 10;
|
||||
var postModel = CreateModel(configuration: JsonSerializer.Serialize(new DeliveryManPostConfiguration() { SalePercent = salePercent, Rate = 10 }));
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
var element = SPiluSZharuDbContext.GetPostFromDatabaseByPostId(postModel.Id!);
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(DeliveryManPostConfiguration).Name));
|
||||
Assert.That((element.Configuration as DeliveryManPostConfiguration)!.SalePercent, Is.EqualTo(salePercent));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WithOperatorPostConfiguration_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var personalCountTrendPremium = 50;
|
||||
var postModel = CreateModel(configuration: JsonSerializer.Serialize(new OperatorPostConfiguration() { PersonalCountTrendPremium = personalCountTrendPremium, Rate = 10 }));
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
var element = SPiluSZharuDbContext.GetPostFromDatabaseByPostId(postModel.Id!);
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(OperatorPostConfiguration).Name));
|
||||
Assert.That((element.Configuration as OperatorPostConfiguration)!.PersonalCountTrendPremium, Is.EqualTo(personalCountTrendPremium));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModel = CreateModel();
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(postModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
SPiluSZharuDbContext.ChangeTracker.Clear();
|
||||
AssertElement(SPiluSZharuDbContext.GetPostFromDatabaseByPostId(postModel.Id!), postModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModel = CreateModel();
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenRecordWasDeleted_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModel = CreateModel();
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(postModel.Id, isActual: false);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModel = CreateModel(postName: "unique name");
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(postModel.Id);
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(postName: postModel.PostName!);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.DeliveryMan.ToString(), ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
|
||||
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.DeliveryMan.ToString(), ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
|
||||
var postModelWithPostTypeIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = string.Empty, ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
|
||||
var postModelWithSalaryIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.DeliveryMan.ToString(), ConfigurationJson = null };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithIdIncorrect));
|
||||
var responseWithNameIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithNameIncorrect));
|
||||
var responseWithPostTypeIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithPostTypeIncorrect));
|
||||
var responseWithSalaryIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithSalaryIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
|
||||
Assert.That(responseWithNameIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
Assert.That(responseWithPostTypeIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Type is incorrect");
|
||||
Assert.That(responseWithSalaryIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Salary is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(string.Empty));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WithDeliveryManPostConfiguration_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var salePercent = 10;
|
||||
var post = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn();
|
||||
var postModel = CreateModel(post.PostId, configuration: JsonSerializer.Serialize(new DeliveryManPostConfiguration() { SalePercent = salePercent, Rate = 10 }));
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
SPiluSZharuDbContext.ChangeTracker.Clear();
|
||||
var element = SPiluSZharuDbContext.GetPostFromDatabaseByPostId(postModel.Id!);
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(DeliveryManPostConfiguration).Name));
|
||||
Assert.That((element.Configuration as DeliveryManPostConfiguration)!.SalePercent, Is.EqualTo(salePercent));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WithOperatorPostConfiguration_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var personalCountTrendPremium = 50;
|
||||
var post = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn();
|
||||
var postModel = CreateModel(post.PostId, configuration: JsonSerializer.Serialize(new OperatorPostConfiguration() { PersonalCountTrendPremium = personalCountTrendPremium, Rate = 10 }));
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
SPiluSZharuDbContext.ChangeTracker.Clear();
|
||||
var element = SPiluSZharuDbContext.GetPostFromDatabaseByPostId(postModel.Id!);
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(OperatorPostConfiguration).Name));
|
||||
Assert.That((element.Configuration as OperatorPostConfiguration)!.PersonalCountTrendPremium, Is.EqualTo(personalCountTrendPremium));
|
||||
});
|
||||
}
|
||||
[Test]
|
||||
public async Task Delete_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postId = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn().PostId;
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/posts/{postId}");
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(SPiluSZharuDbContext.GetPostFromDatabaseByPostId(postId), Is.Null);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/posts/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postId = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(isActual: false).PostId;
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/posts/{postId}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/posts/id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Patch_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postId = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(isActual: false).PostId;
|
||||
//Act
|
||||
var response = await HttpClient.PatchAsync($"/api/posts/{postId}", null);
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(SPiluSZharuDbContext.GetPostFromDatabaseByPostId(postId), Is.Not.Null);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Patch_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.PatchAsync($"/api/posts/{Guid.NewGuid()}", null);
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Patch_WhenRecordNotWasDeleted_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postId = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn().PostId;
|
||||
//Act
|
||||
var response = await HttpClient.PatchAsync($"/api/posts/{postId}", null);
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(SPiluSZharuDbContext.GetPostFromDatabaseByPostId(postId), Is.Not.Null);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Patch_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PatchAsync($"/api/posts/id", null);
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
private static void AssertElement(PostViewModel? actual, Post expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.PostId));
|
||||
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
|
||||
Assert.That(actual.PostType, Is.EqualTo(expected.PostType.ToString()));
|
||||
Assert.That(JsonNode.Parse(actual.Configuration)!["Type"]!.GetValue<string>(), Is.EqualTo(expected.Configuration.Type));
|
||||
});
|
||||
}
|
||||
|
||||
private static PostBindingModel CreateModel(string? postId = null, string postName = "name", PostType postType = PostType.DeliveryMan, string? configuration = null)
|
||||
=> new()
|
||||
{
|
||||
Id = postId ?? Guid.NewGuid().ToString(),
|
||||
PostName = postName,
|
||||
PostType = postType.ToString(),
|
||||
ConfigurationJson = configuration ?? JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 })
|
||||
};
|
||||
|
||||
private static void AssertElement(Post? actual, PostBindingModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.PostId, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
|
||||
Assert.That(actual.PostType.ToString(), Is.EqualTo(expected.PostType));
|
||||
Assert.That(actual.Configuration.Type, Is.EqualTo(JsonNode.Parse(expected.ConfigurationJson!)!["Type"]!.GetValue<string>()));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,471 @@
|
||||
using SPiluSZharuContracts.BindingModels;
|
||||
using SPiluSZharuContracts.Enums;
|
||||
using SPiluSZharuContracts.ViewModels;
|
||||
using SPiluSZharuDatabase;
|
||||
using SPiluSZharuDatabase.Models;
|
||||
using SPiluSZharuTests.Infrastructure;
|
||||
using System.Net;
|
||||
|
||||
namespace SPiluSZharuTests.WebApiControllersTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class ProductControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
SPiluSZharuDbContext.RemoveProductsFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var product = SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productName: "name 1");
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productName: "name 2");
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productName: "name 3");
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/products/getrecords?includeDeleted=false");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ProductViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
});
|
||||
AssertElement(data.First(x => x.Id == product.Id), product);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/products/getrecords?includeDeleted=false");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ProductViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_OnlyActual_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productName: "name 1", isDeleted: true);
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productName: "name 2", isDeleted: false);
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productName: "name 3", isDeleted: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/products/getrecords?includeDeleted=false");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ProductViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
Assert.That(data.All(x => !x.IsDeleted));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_IncludeNoActual_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productName: "name 1", isDeleted: true);
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productName: "name 2", isDeleted: true);
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productName: "name 3", isDeleted: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/products/getrecords?includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ProductViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
Assert.That(data.Any(x => x.IsDeleted));
|
||||
Assert.That(data.Any(x => !x.IsDeleted));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetHistoryByProductId_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var product = SPiluSZharuDbContext.InsertProductToDatabaseAndReturn();
|
||||
SPiluSZharuDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 20, DateTime.UtcNow.AddDays(-1));
|
||||
SPiluSZharuDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 30, DateTime.UtcNow.AddMinutes(-10));
|
||||
var history = SPiluSZharuDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 40, DateTime.UtcNow.AddDays(1));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/products/gethistory?id={product.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ProductHistoryViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
AssertElement(data[0], history);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetHistoryByProductId_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var product = SPiluSZharuDbContext.InsertProductToDatabaseAndReturn();
|
||||
SPiluSZharuDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 20, DateTime.UtcNow.AddDays(-1));
|
||||
SPiluSZharuDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 30, DateTime.UtcNow.AddMinutes(-10));
|
||||
SPiluSZharuDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 40, DateTime.UtcNow.AddDays(1));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/products/gethistory?id={Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ProductViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetHistoryByProductId_WhenProductIdIsNotGuid_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/products/gethistory?id=id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var product = SPiluSZharuDbContext.InsertProductToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/products/getrecord/{product.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<ProductViewModel>(response), product);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/products/getrecord/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenRecordWasDeleted_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
var product = SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(isDeleted: true);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/products/getrecord/{product.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var product = SPiluSZharuDbContext.InsertProductToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/products/getrecord/{product.ProductName}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<ProductViewModel>(response), product);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/products/getrecord/New%20Name");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenRecordWasDeleted_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
var product = SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(isDeleted: true);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/products/getrecord/{product.ProductName}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn();
|
||||
var productModel = CreateModel();
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/products/register", MakeContent(productModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(SPiluSZharuDbContext.GetProductFromDatabaseById(productModel.Id!), productModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var productModel = CreateModel();
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/products/register", MakeContent(productModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var productModel = CreateModel(productName: "unique name");
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productName: productModel.ProductName!);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/products/register", MakeContent(productModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var productModelWithIdIncorrect = new ProductBindingModel { Id = "Id", ProductName = "name", Price = 100, ProductType = ProductType.Burgers.ToString() };
|
||||
var productModelWithNameIncorrect = new ProductBindingModel { Id = Guid.NewGuid().ToString(), ProductName = string.Empty, Price = 100, ProductType = ProductType.Burgers.ToString() };
|
||||
var productModelWithProductTypeIncorrect = new ProductBindingModel { Id = Guid.NewGuid().ToString(), ProductName = "name", Price = 100, ProductType = string.Empty };
|
||||
var productModelWithPriceIncorrect = new ProductBindingModel { Id = Guid.NewGuid().ToString(), ProductName = "name", Price = 0, ProductType = ProductType.Burgers.ToString() };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/products/register", MakeContent(productModelWithIdIncorrect));
|
||||
var responseWithNameIncorrect = await HttpClient.PostAsync($"/api/products/register", MakeContent(productModelWithNameIncorrect));
|
||||
var responseWithProductTypeIncorrect = await HttpClient.PostAsync($"/api/products/register", MakeContent(productModelWithProductTypeIncorrect));
|
||||
var responseWithPriceIncorrect = await HttpClient.PostAsync($"/api/products/register", MakeContent(productModelWithPriceIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
|
||||
Assert.That(responseWithNameIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
Assert.That(responseWithProductTypeIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
Assert.That(responseWithPriceIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/products/register", MakeContent(string.Empty));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/products/register", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var productModel = CreateModel();
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/products/changeinfo", MakeContent(productModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
SPiluSZharuDbContext.ChangeTracker.Clear();
|
||||
AssertElement(SPiluSZharuDbContext.GetProductFromDatabaseById(productModel.Id!), productModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var productModel = CreateModel();
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/products/changeinfo", MakeContent(productModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var productModel = CreateModel(productName: "unique name");
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productModel.Id);
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productName: productModel.ProductName!);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/products/changeinfo", MakeContent(productModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenRecordWasDeleted_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var productModel = CreateModel();
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productModel.Id, isDeleted: true);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/products/changeinfo", MakeContent(productModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var productModelWithIdIncorrect = new ProductBindingModel { Id = "Id", ProductName = "name", Price = 100, ProductType = ProductType.Burgers.ToString() };
|
||||
var productModelWithNameIncorrect = new ProductBindingModel { Id = Guid.NewGuid().ToString(), ProductName = string.Empty, Price = 100, ProductType = ProductType.Burgers.ToString() };
|
||||
var productModelWithProductTypeIncorrect = new ProductBindingModel { Id = Guid.NewGuid().ToString(), ProductName = "name", Price = 100, ProductType = string.Empty };
|
||||
var productModelWithPriceIncorrect = new ProductBindingModel { Id = Guid.NewGuid().ToString(), ProductName = "name", Price = 0, ProductType = ProductType.Burgers.ToString() };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/products/changeinfo", MakeContent(productModelWithIdIncorrect));
|
||||
var responseWithNameIncorrect = await HttpClient.PutAsync($"/api/products/changeinfo", MakeContent(productModelWithNameIncorrect));
|
||||
var responseWithProductTypeIncorrect = await HttpClient.PutAsync($"/api/products/changeinfo", MakeContent(productModelWithProductTypeIncorrect));
|
||||
var responseWithPriceIncorrect = await HttpClient.PutAsync($"/api/products/changeinfo", MakeContent(productModelWithPriceIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
|
||||
Assert.That(responseWithNameIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
Assert.That(responseWithProductTypeIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
Assert.That(responseWithPriceIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/products/changeinfo", MakeContent(string.Empty));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/products/changeinfo", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var productId = Guid.NewGuid().ToString();
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productId);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/products/delete/{productId}");
|
||||
SPiluSZharuDbContext.ChangeTracker.Clear();
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(SPiluSZharuDbContext.GetProductFromDatabaseById(productId)!.IsDeleted);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertProductToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/products/delete/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenRecordWasDeleted_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var productId = SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(isDeleted: true).Id;
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/products/delete/{productId}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/products/delete/id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
private static void AssertElement(ProductViewModel? actual, Product expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.ProductName, Is.EqualTo(expected.ProductName));
|
||||
Assert.That(actual.ProductType, Is.EqualTo(expected.ProductType.ToString()));
|
||||
Assert.That(actual.Price, Is.EqualTo(expected.Price));
|
||||
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
|
||||
});
|
||||
}
|
||||
|
||||
private static void AssertElement(ProductHistoryViewModel? actual, ProductHistory expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.ProductName, Is.EqualTo(expected.Product!.ProductName));
|
||||
Assert.That(actual.OldPrice, Is.EqualTo(expected.OldPrice));
|
||||
Assert.That(actual.ChangeDate.ToString(), Is.EqualTo(expected.ChangeDate.ToString()));
|
||||
});
|
||||
}
|
||||
|
||||
private static ProductBindingModel CreateModel(string? id = null, string productName = "name", ProductType productType = ProductType.Burgers, double price = 1)
|
||||
=> new()
|
||||
{
|
||||
Id = id ?? Guid.NewGuid().ToString(),
|
||||
ProductName = productName,
|
||||
ProductType = productType.ToString(),
|
||||
Price = price
|
||||
};
|
||||
|
||||
private static void AssertElement(Product? actual, ProductBindingModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.ProductName, Is.EqualTo(expected.ProductName));
|
||||
Assert.That(actual.ProductType.ToString(), Is.EqualTo(expected.ProductType));
|
||||
Assert.That(actual.Price, Is.EqualTo(expected.Price));
|
||||
Assert.That(!actual.IsDeleted);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
using SPiluSZharuContracts.BindingModels;
|
||||
using SPiluSZharuContracts.ViewModels;
|
||||
using SPiluSZharuDatabase.Models;
|
||||
using SPiluSZharuTests.Infrastructure;
|
||||
using System.Net;
|
||||
|
||||
namespace SPiluSZharuTests.WebApiControllersTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class RestaurantControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
SPiluSZharuDbContext.RemoveRestaurantsFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var restaurant = SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn(restaurantName: "name 1");
|
||||
SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn(restaurantName: "name 2");
|
||||
SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn(restaurantName: "name 3");
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/restaurants");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<RestaurantViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
});
|
||||
AssertElement(data.First(x => x.Id == restaurant.Id), restaurant);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/restaurants");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<RestaurantViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var restaurant = SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/restaurants/{restaurant.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<RestaurantViewModel>(response), restaurant);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/restaurants/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var restaurant = SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/restaurants/{restaurant.RestaurantName}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<RestaurantViewModel>(response), restaurant);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/restaurants/New%20Name");
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByOldName_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var oldName = "old name";
|
||||
var restaurant = SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn(prevRestaurantName: oldName);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/restaurants/{oldName}");
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<RestaurantViewModel>(response), restaurant);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn();
|
||||
var restaurantModel = CreateModel();
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/restaurants", MakeContent(restaurantModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(SPiluSZharuDbContext.GetRestaurantFromDatabase(restaurantModel.Id!), restaurantModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var restaurantModel = CreateModel();
|
||||
SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn(restaurantModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/restaurants", MakeContent(restaurantModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var restaurantModel = CreateModel(restaurantName: "unique name");
|
||||
SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn(restaurantName: restaurantModel.RestaurantName!);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/restaurants", MakeContent(restaurantModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var restaurantModelWithIdIncorrect = new RestaurantBindingModel { Id = "Id", RestaurantName = "name" };
|
||||
var restaurantModelWithNameIncorrect = new RestaurantBindingModel { Id = Guid.NewGuid().ToString(), RestaurantName = string.Empty };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/restaurants", MakeContent(restaurantModelWithIdIncorrect));
|
||||
var responseWithNameIncorrect = await HttpClient.PostAsync($"/api/restaurants", MakeContent(restaurantModelWithNameIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
|
||||
Assert.That(responseWithNameIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/restaurants", MakeContent(string.Empty));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/restaurants", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var restaurantModel = CreateModel();
|
||||
SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn(restaurantModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/restaurants", MakeContent(restaurantModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
SPiluSZharuDbContext.ChangeTracker.Clear();
|
||||
AssertElement(SPiluSZharuDbContext.GetRestaurantFromDatabase(restaurantModel.Id!), restaurantModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_CheckPrevNames_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var restaurantModel1 = CreateModel(restaurantName: "name 1");
|
||||
var restaurantModel2 = CreateModel(id: restaurantModel1.Id, restaurantName: "name 2");
|
||||
var restaurantModel3 = CreateModel(id: restaurantModel1.Id, restaurantName: "name 3");
|
||||
SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn(restaurantModel1.Id);
|
||||
//Act
|
||||
await HttpClient.PutAsync($"/api/restaurants", MakeContent(restaurantModel1));
|
||||
await HttpClient.PutAsync($"/api/restaurants", MakeContent(restaurantModel2));
|
||||
await HttpClient.PutAsync($"/api/restaurants", MakeContent(restaurantModel3));
|
||||
//Assert
|
||||
SPiluSZharuDbContext.ChangeTracker.Clear();
|
||||
var entityModel = SPiluSZharuDbContext.GetRestaurantFromDatabase(restaurantModel1.Id!);
|
||||
Assert.That(entityModel, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(entityModel.RestaurantName, Is.EqualTo(restaurantModel3.RestaurantName));
|
||||
Assert.That(entityModel.PrevRestaurantName, Is.EqualTo(restaurantModel2.RestaurantName));
|
||||
Assert.That(entityModel.PrevPrevRestaurantName, Is.EqualTo(restaurantModel1.RestaurantName));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var restaurantModel = CreateModel();
|
||||
SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/restaurants", MakeContent(restaurantModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var restaurantModel = CreateModel(restaurantName: "unique name");
|
||||
SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn(restaurantModel.Id);
|
||||
SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn(restaurantName: restaurantModel.RestaurantName!);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/restaurants", MakeContent(restaurantModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var restaurantModelWithIdIncorrect = new RestaurantBindingModel { Id = "Id", RestaurantName = "name" };
|
||||
var restaurantModelWithNameIncorrect = new RestaurantBindingModel { Id = Guid.NewGuid().ToString(), RestaurantName = string.Empty };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/restaurants", MakeContent(restaurantModelWithIdIncorrect));
|
||||
var responseWithNameIncorrect = await HttpClient.PutAsync($"/api/restaurants", MakeContent(restaurantModelWithNameIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
|
||||
Assert.That(responseWithNameIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/restaurants", MakeContent(string.Empty));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/restaurants", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var restaurantId = Guid.NewGuid().ToString();
|
||||
SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn(restaurantId);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/restaurants/{restaurantId}");
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(SPiluSZharuDbContext.GetRestaurantFromDatabase(restaurantId), Is.Null);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/restaurants/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/restaurants/id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
private static void AssertElement(RestaurantViewModel? actual, Restaurant expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.RestaurantName, Is.EqualTo(expected.RestaurantName));
|
||||
Assert.That(actual.PrevRestaurantName, Is.EqualTo(expected.PrevRestaurantName));
|
||||
Assert.That(actual.PrevPrevRestaurantName, Is.EqualTo(expected.PrevPrevRestaurantName));
|
||||
});
|
||||
}
|
||||
|
||||
private static RestaurantBindingModel CreateModel(string? id = null, string restaurantName = "name")
|
||||
=> new()
|
||||
{
|
||||
Id = id ?? Guid.NewGuid().ToString(),
|
||||
RestaurantName = restaurantName
|
||||
};
|
||||
|
||||
private static void AssertElement(Restaurant? actual, RestaurantBindingModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.RestaurantName, Is.EqualTo(expected.RestaurantName));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
using SPiluSZharuContracts.BindingModels;
|
||||
using SPiluSZharuContracts.ViewModels;
|
||||
using SPiluSZharuDatabase.Models;
|
||||
using SPiluSZharuTests.Infrastructure;
|
||||
using System.Net;
|
||||
|
||||
namespace SPiluSZharuTests.WebApiControllersTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class SalaryControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
SPiluSZharuDbContext.RemovePostsFromDatabase();
|
||||
SPiluSZharuDbContext.RemoveSalesFromDatabase();
|
||||
SPiluSZharuDbContext.RemoveSalariesFromDatabase();
|
||||
SPiluSZharuDbContext.RemoveWorkersFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
var salary = SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(worker.Id, workerSalary: 100);
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(worker.Id);
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(worker.Id);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salary/getrecords?fromDate={DateTime.UtcNow.AddDays(-10):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(10):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SalaryViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salary/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SalaryViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_OnlyForCertainPeriod_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salary/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SalaryViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenDatesAreIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salary/getrecords?fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByWorker_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker1 = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio", phoneNumber: "+7(555)555-55-55");
|
||||
var worker2 = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "new fio", phoneNumber: "+7(333)333-33-33");
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id);
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id);
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(worker2.Id);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salary/getrecordsbyworker?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&workerId={worker1.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SalaryViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
Assert.That(data.All(x => x.WorkerId == worker1.Id));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByWorker_OnlyForCertainPeriod_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker1 = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio", phoneNumber: "+7(555)555-55-55");
|
||||
var worker2 = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "new fio", phoneNumber: "+7(333)333-33-33");
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(worker2.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(worker2.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
SPiluSZharuDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salary/getrecordsbyworker?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&workerId={worker1.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SalaryViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
Assert.That(data.All(x => x.WorkerId == worker1.Id));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByWorker_WhenDatesAreIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salary/getrecordsbyworker?fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&workerId={worker.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByWorker_WhenIdIsNotGuid_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salary/getrecordsbyworker?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&workerId=id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Calculate_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
//var post = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(salary: 1000);
|
||||
//var worker = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(postId: post.PostId);
|
||||
//var sale = SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(worker.Id);
|
||||
|
||||
//var expectedSum = sale.Sum * 0.1 + post.Salary;
|
||||
////Act
|
||||
//var response = await HttpClient.PostAsync($"/api/salary/calculate?date={DateTime.UtcNow:MM/dd/yyyy}", null);
|
||||
////Assert
|
||||
//Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
//var salaries = SPiluSZharuDbContext.GetSalariesFromDatabaseByWorkerId(worker.Id);
|
||||
//Assert.Multiple(() =>
|
||||
//{
|
||||
// Assert.That(salaries, Has.Length.EqualTo(1));
|
||||
// Assert.That(salaries.First().WorkerSalary, Is.EqualTo(expectedSum));
|
||||
// Assert.That(salaries.First().SalaryDate.Month, Is.EqualTo(DateTime.UtcNow.Month));
|
||||
//});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Calculate_WhenAllWorkersWithoutSales_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/salary/calculate?date={DateTime.UtcNow:MM/dd/yyyy}", null);
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
var salaries = SPiluSZharuDbContext.Salaries.ToArray();
|
||||
Assert.That(salaries, Has.Length.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Calculate_WhenWorkerWithoutSales_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
//var post = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn(salary: 1000);
|
||||
//var worker1 = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: post.PostId, phoneNumber: "+7(555)555-55-55");
|
||||
//var worker2 = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: post.PostId, phoneNumber: "+7(333)333-33-33");
|
||||
//var sale = SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(worker1.Id);
|
||||
////Act
|
||||
//var response = await HttpClient.PostAsync($"/api/salary/calculate?date={DateTime.UtcNow:MM/dd/yyyy}", null);
|
||||
////Assert
|
||||
//Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
//var salary1 = SPiluSZharuDbContext.GetSalariesFromDatabaseByWorkerId(worker1.Id).First().WorkerSalary;
|
||||
//var salary2 = SPiluSZharuDbContext.GetSalariesFromDatabaseByWorkerId(worker2.Id).First().WorkerSalary;
|
||||
//Assert.That(salary1, Is.Not.EqualTo(salary2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Calculate_WhenWorkerWithoutPost_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertPostToDatabaseAndReturn();
|
||||
var worker = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(postId: Guid.NewGuid().ToString());
|
||||
var sale = SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(worker.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/salary/calculate?date={DateTime.UtcNow:MM/dd/yyyy}", null);
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,499 @@
|
||||
using SPiluSZharuContracts.BindingModels;
|
||||
using SPiluSZharuContracts.ViewModels;
|
||||
using SPiluSZharuDatabase.Models;
|
||||
using SPiluSZharuTests.Infrastructure;
|
||||
using System.Net;
|
||||
|
||||
namespace SPiluSZharuTests.WebApiControllersTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class SaleControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
private string _restaurantId;
|
||||
private string _workerId;
|
||||
private string _productId;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_restaurantId = SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn().Id;
|
||||
_workerId = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn().Id;
|
||||
_productId = SPiluSZharuDbContext.InsertProductToDatabaseAndReturn().Id;
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
SPiluSZharuDbContext.RemoveSalesFromDatabase();
|
||||
SPiluSZharuDbContext.RemoveWorkersFromDatabase();
|
||||
SPiluSZharuDbContext.RemoveRestaurantsFromDatabase();
|
||||
SPiluSZharuDbContext.RemoveProductsFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var sale = SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, restaurantId: _restaurantId, sum: 10, products: [(_productId, 10, 1.1)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, products: [(_productId, 10, 1.1)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, products: [(_productId, 10, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
});
|
||||
AssertElement(data.First(x => x.Sum == sale.Sum), sale);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByPeriod_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, _restaurantId, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), products: [(_productId, 1, 1.1)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, _restaurantId, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), products: [(_productId, 1, 1.1)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), products: [(_productId, 1, 1.1)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(3), products: [(_productId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByPeriod_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByWorkerId_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "Other worker", phoneNumber: "+7(555)555-55-55");
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, _restaurantId, products: [(_productId, 1, 1.1)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, _restaurantId, products: [(_productId, 1, 1.1)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(worker.Id, null, products: [(_productId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getworkerrecords?id={_workerId}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
Assert.That(data.All(x => x.WorkerId == _workerId));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByWorkerId_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "Other worker", phoneNumber: "+7(555)555-55-55");
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, _restaurantId, products: [(_productId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getworkerrecords?id={worker.Id}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByWorkerId_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getworkerrecords?id={_workerId}&fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByWorkerId_WhenIdIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getworkerrecords?id=Id&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByRestaurantId_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var restaurant = SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn(restaurantName: "Other name");
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, _restaurantId, products: [(_productId, 1, 1.1)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, _restaurantId, products: [(_productId, 1, 1.1)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, restaurant.Id, products: [(_productId, 1, 1.1)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, null, products: [(_productId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrestaurantrecords?id={_restaurantId}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
Assert.That(data.All(x => x.RestaurantId == _restaurantId));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByRestaurantId_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var restaurant = SPiluSZharuDbContext.InsertRestaurantToDatabaseAndReturn(restaurantName: "Other restaurant");
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, _restaurantId, products: [(_productId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrestaurantrecords?id={restaurant.Id}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByRestaurantId_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrestaurantrecords?id={_restaurantId}&fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByRestaurantId_WhenIdIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrestaurantrecords?id=Id&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByProductId_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var product = SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productName: "Other name");
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, _restaurantId, products: [(_productId, 5, 1.1)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, _restaurantId, products: [(_productId, 1, 1.1), (product.Id, 4, 1.1)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, null, products: [(product.Id, 1, 1.1)]);
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, null, products: [(product.Id, 1, 1.1), (_productId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getproductrecords?id={_productId}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
Assert.That(data.All(x => x.Products.Any(y => y.ProductId == _productId)));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByProductId_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var product = SPiluSZharuDbContext.InsertProductToDatabaseAndReturn(productName: "Other product");
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, _restaurantId, products: [(_productId, 1, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getproductrecords?id={product.Id}&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByProductId_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getproductrecords?id={_productId}&fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByProductId_WhenIdIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getproductrecords?id=Id&fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var sale = SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, _restaurantId, products: [(_productId, 5, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecord/{sale.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<SaleViewModel>(response), sale);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, _restaurantId, products: [(_productId, 5, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecord/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenRecordHasCanceled_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var sale = SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, _restaurantId, products: [(_productId, 1, 1.2)], isCancel: true);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecord/{sale.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenIdIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/sales/getrecord/Id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, null, products: [(_productId, 5, 1.1)]);
|
||||
var saleModel = CreateModel(_workerId, _restaurantId, _productId);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(SPiluSZharuDbContext.GetSalesByRestaurantId(_restaurantId)[0], saleModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenNoRestaurant_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, _restaurantId, products: [(_productId, 5, 1.1)]);
|
||||
var saleModel = CreateModel(_workerId, null, _productId);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(SPiluSZharuDbContext.GetSalesByRestaurantId(null)[0], saleModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var saleId = Guid.NewGuid().ToString();
|
||||
var saleModelWithIdIncorrect = new SaleBindingModel { Id = "Id", WorkerId = _workerId, RestaurantId = _restaurantId, Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = _productId, Count = 10, Price = 1.1 }] };
|
||||
var saleModelWithWorkerIdIncorrect = new SaleBindingModel { Id = saleId, WorkerId = "Id", RestaurantId = _restaurantId, Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = _productId, Count = 10, Price = 1.1 }] };
|
||||
var saleModelWithRestaurantIdIncorrect = new SaleBindingModel { Id = saleId, WorkerId = _workerId, RestaurantId = "Id", Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = _productId, Count = 10, Price = 1.1 }] };
|
||||
var saleModelWithProductsIncorrect = new SaleBindingModel { Id = saleId, WorkerId = _workerId, RestaurantId = _restaurantId, Products = null };
|
||||
var saleModelWithProductIdIncorrect = new SaleBindingModel { Id = saleId, WorkerId = _workerId, RestaurantId = _restaurantId, Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = "Id", Count = 10, Price = 1.1 }] };
|
||||
var saleModelWithCountIncorrect = new SaleBindingModel { Id = saleId, WorkerId = _workerId, RestaurantId = _restaurantId, Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = _productId, Count = -10, Price = 1.1 }] };
|
||||
var saleModelWithPriceIncorrect = new SaleBindingModel { Id = saleId, WorkerId = _workerId, RestaurantId = _restaurantId, Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = _productId, Count = 10, Price = -1.1 }] };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithIdIncorrect));
|
||||
var responseWithWorkerIdIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithWorkerIdIncorrect));
|
||||
var responseWithRestaurantIdIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithRestaurantIdIncorrect));
|
||||
var responseWithProductsIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithProductsIncorrect));
|
||||
var responseWithProductIdIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithProductIdIncorrect));
|
||||
var responseWithCountIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithCountIncorrect));
|
||||
var responseWithPriceIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithPriceIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "WorkerId is incorrect");
|
||||
Assert.That(responseWithWorkerIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "WorkerId is incorrect");
|
||||
Assert.That(responseWithRestaurantIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "RestaurantId is incorrect");
|
||||
Assert.That(responseWithProductsIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Products is incorrect");
|
||||
Assert.That(responseWithProductIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "ProductId is incorrect");
|
||||
Assert.That(responseWithCountIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Count is incorrect");
|
||||
Assert.That(responseWithPriceIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Price is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(string.Empty));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var sale = SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, _restaurantId, products: [(_productId, 5, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/sales/cancel/{sale.Id}");
|
||||
SPiluSZharuDbContext.ChangeTracker.Clear();
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(SPiluSZharuDbContext.GetSaleFromDatabaseById(sale.Id)!.IsCancel);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, _restaurantId, products: [(_productId, 5, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/sales/cancel/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenIsCanceled_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var sale = SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, _restaurantId, products: [(_productId, 5, 1.1)], isCancel: true);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/sales/cancel/{sale.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/sales/cancel/id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
private static void AssertElement(SaleViewModel? actual, Sale expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.WorkerFIO, Is.EqualTo(expected.Worker!.FIO));
|
||||
Assert.That(actual.RestaurantName, Is.EqualTo(expected.Restaurant?.RestaurantName));
|
||||
Assert.That(actual.IsCancel, Is.EqualTo(expected.IsCancel));
|
||||
});
|
||||
|
||||
if (expected.SaleProducts is not null)
|
||||
{
|
||||
Assert.That(actual.Products, Is.Not.Null);
|
||||
Assert.That(actual.Products, Has.Count.EqualTo(expected.SaleProducts.Count));
|
||||
for (int i = 0; i < actual.Products.Count; ++i)
|
||||
{
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Products[i].ProductName, Is.EqualTo(expected.SaleProducts[i].Product!.ProductName));
|
||||
Assert.That(actual.Products[i].Count, Is.EqualTo(expected.SaleProducts[i].Count));
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.That(actual.Products, Is.Null);
|
||||
}
|
||||
}
|
||||
|
||||
private static SaleBindingModel CreateModel(string workerId, string? restaurantId, string productId, string? id = null, int count = 1, double price = 1.1)
|
||||
{
|
||||
var saleId = id ?? Guid.NewGuid().ToString();
|
||||
return new()
|
||||
{
|
||||
Id = saleId,
|
||||
WorkerId = workerId,
|
||||
RestaurantId = restaurantId,
|
||||
Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = productId, Count = count, Price = price }]
|
||||
};
|
||||
}
|
||||
|
||||
private static void AssertElement(Sale? actual, SaleBindingModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
|
||||
Assert.That(actual.RestaurantId, Is.EqualTo(expected.RestaurantId));
|
||||
Assert.That(!actual.IsCancel);
|
||||
});
|
||||
|
||||
if (expected.Products is not null)
|
||||
{
|
||||
Assert.That(actual.SaleProducts, Is.Not.Null);
|
||||
Assert.That(actual.SaleProducts, Has.Count.EqualTo(expected.Products.Count));
|
||||
for (int i = 0; i < actual.SaleProducts.Count; ++i)
|
||||
{
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.SaleProducts[i].ProductId, Is.EqualTo(expected.Products[i].ProductId));
|
||||
Assert.That(actual.SaleProducts[i].Count, Is.EqualTo(expected.Products[i].Count));
|
||||
Assert.That(actual.SaleProducts[i].Price, Is.EqualTo(expected.Products[i].Price));
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.That(actual.SaleProducts, Is.Null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,576 @@
|
||||
using SPiluSZharuContracts.BindingModels;
|
||||
using SPiluSZharuContracts.ViewModels;
|
||||
using SPiluSZharuDatabase.Models;
|
||||
using SPiluSZharuTests.Infrastructure;
|
||||
using System.Net;
|
||||
|
||||
namespace SPiluSZharuTests.WebApiControllersTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class WorkerControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
private Post _post;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_post = SPiluSZharuDbContext.InsertPostToDatabaseAndReturn();
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
SPiluSZharuDbContext.RemovePostsFromDatabase();
|
||||
SPiluSZharuDbContext.RemoveWorkersFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId, phoneNumber: "+7(555)555-55-55")
|
||||
.AddPost(_post);
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: _post.PostId, phoneNumber: "+7(333)333-33-33");
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", postId: _post.PostId, phoneNumber: "+7(111)111-11-11");
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/workers/getrecords");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
});
|
||||
AssertElement(data.First(x => x.Id == worker.Id), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/workers/getrecords");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_OnlyActual_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId, phoneNumber: "+7(555)555-55-55", isDeleted: true);
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: _post.PostId, phoneNumber: "+7(333)333-33-33", isDeleted: false);
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", postId: _post.PostId, phoneNumber: "+7(111)111-11-11", isDeleted: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/workers/getrecords?includeDeleted=false");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
Assert.That(data.All(x => !x.IsDeleted));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_IncludeNoActual_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId, phoneNumber: "+7(555)555-55-55", isDeleted: true);
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: _post.PostId, phoneNumber: "+7(333)333-33-33", isDeleted: true);
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", postId: _post.PostId, phoneNumber: "+7(111)111-11-11", isDeleted: false);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/workers/getrecords?includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
Assert.That(data.Any(x => x.IsDeleted));
|
||||
Assert.That(data.Any(x => !x.IsDeleted));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByPostId_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId, phoneNumber: "+7(555)555-55-55");
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: _post.PostId, phoneNumber: "+7(333)333-33-33");
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", postId: _post.PostId, phoneNumber: "+7(111)111-11-11", isDeleted: true);
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4");
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getpostrecords?id={_post.PostId}&includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
Assert.That(data.All(x => x.PostId == _post.PostId));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByPostId_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId, phoneNumber: "+7(555)555-55-55");
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", phoneNumber: "+7(333)333-33-33");
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getpostrecords?id={Guid.NewGuid()}&includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByPostId_WhenIdIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getpostrecords?id=id&includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByBirthDate_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", phoneNumber: "+7(555)555-55-55", birthDate: DateTime.UtcNow.AddYears(-25));
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", phoneNumber: "+7(333)333-33-33", birthDate: DateTime.UtcNow.AddYears(-21));
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", phoneNumber: "+7(111)111-11-11", birthDate: DateTime.UtcNow.AddYears(-20), isDeleted: true);
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", phoneNumber: "+7(999)999-99-99", birthDate: DateTime.UtcNow.AddYears(-19));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getbirthdaterecords?fromDate={DateTime.UtcNow.AddYears(-21).AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddYears(-20).AddMinutes(1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByBirthDate_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getbirthdaterecords?fromDate={DateTime.UtcNow.AddMinutes(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByEmploymentDate_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", phoneNumber: "+7(555)555-55-55", employmentDate: DateTime.UtcNow.AddDays(-2));
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", phoneNumber: "+7(333)333-33-33", employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", phoneNumber: "+7(111)111-11-11", employmentDate: DateTime.UtcNow.AddDays(1), isDeleted: true);
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", phoneNumber: "+7(999)999-99-99", employmentDate: DateTime.UtcNow.AddDays(2));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getemploymentrecords?fromDate={DateTime.UtcNow.AddDays(-1).AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1).AddMinutes(1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByEmploymentDate_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getemploymentrecords?fromDate={DateTime.UtcNow.AddMinutes(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(postId: _post.PostId).AddPost(_post);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getrecord/{worker.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<WorkerViewModel>(response), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getrecord/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenRecordWasDeleted_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(postId: _post.PostId, isDeleted: true);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getrecord/{worker.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByFIO_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(postId: _post.PostId).AddPost(_post);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getrecord/{worker.FIO}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<WorkerViewModel>(response), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByFIO_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getrecord/New%20Fio");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByFIO_WhenRecordWasDeleted_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(postId: _post.PostId, isDeleted: true);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getrecord/{worker.FIO}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByPhoneNumber_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(postId: _post.PostId).AddPost(_post);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getrecord/{worker.PhoneNumber}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<WorkerViewModel>(response), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByPhoneNumber_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/+7(777)777-77-77");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByPhoneNumber_WhenRecordWasDeleted_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(postId: _post.PostId, isDeleted: true);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/workers/getrecord/{worker.PhoneNumber}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
var workerModel = CreateModel(postId: _post.Id, phoneNumber: "+7(555)555-55-55");
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/workers/register", MakeContent(workerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(SPiluSZharuDbContext.GetWorkerFromDatabaseById(workerModel.Id!), workerModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerModel = CreateModel(_post.Id);
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(workerModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/workers/register", MakeContent(workerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSamePhoneNumber_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerModel = CreateModel(_post.Id);
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(phoneNumber: workerModel.PhoneNumber!);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/workers/register", MakeContent(workerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerModelWithIdIncorrect = new WorkerBindingModel { Id = "Id", FIO = "fio", PhoneNumber = "+7(777)777-77-77", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
var workerModelWithFioIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = string.Empty, PhoneNumber = "+7(555)555-55-55", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
var workerModelWithPostIdIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", PhoneNumber = "+7(333)333-33-33", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = "Id" };
|
||||
var workerModelWithBirthDateIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", PhoneNumber = "+7(111)111-11-11", BirthDate = DateTime.UtcNow.AddYears(-15), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
var workerModelWithPhoneNumberIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", PhoneNumber = "71", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/workers/register", MakeContent(workerModelWithIdIncorrect));
|
||||
var responseWithFioIncorrect = await HttpClient.PostAsync($"/api/workers/register", MakeContent(workerModelWithFioIncorrect));
|
||||
var responseWithPostIdIncorrect = await HttpClient.PostAsync($"/api/workers/register", MakeContent(workerModelWithPostIdIncorrect));
|
||||
var responseWithBirthDateIncorrect = await HttpClient.PostAsync($"/api/workers/register", MakeContent(workerModelWithBirthDateIncorrect));
|
||||
var responseWithPhoneNumberIncorrect = await HttpClient.PostAsync($"/api/workers/register", MakeContent(workerModelWithPhoneNumberIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
|
||||
Assert.That(responseWithFioIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Fio is incorrect");
|
||||
Assert.That(responseWithPostIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "PostId is incorrect");
|
||||
Assert.That(responseWithBirthDateIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "BirthDate is incorrect");
|
||||
Assert.That(responseWithPhoneNumberIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "PhoneNumber is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/workers/register", MakeContent(string.Empty));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/workers/register", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerModel = CreateModel(_post.Id);
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(workerModel.Id, phoneNumber: "+7(555)555-55-55");
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
SPiluSZharuDbContext.ChangeTracker.Clear();
|
||||
AssertElement(SPiluSZharuDbContext.GetWorkerFromDatabaseById(workerModel.Id!), workerModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerModel = CreateModel(_post.Id, fio: "new fio");
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(phoneNumber: "+7(555)555-55-55");
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenRecordWasDeleted_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerModel = CreateModel(_post.Id, fio: "new fio");
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(workerModel.Id, phoneNumber: "+7(555)555-55-55", isDeleted: true);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenHaveRecordWithSamePhoneNumber_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerModel = CreateModel(_post.Id, fio: "new fio");
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(workerModel.Id, phoneNumber: "+7(555)555-55-55");
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(phoneNumber: workerModel.PhoneNumber!);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerModelWithIdIncorrect = new WorkerBindingModel { Id = "Id", FIO = "fio", PhoneNumber = "+7(777)777-77-77", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
var workerModelWithFioIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = string.Empty, PhoneNumber = "+7(555)555-55-55", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
var workerModelWithPostIdIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", PhoneNumber = "+7(333)333-33-33", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = "Id" };
|
||||
var workerModelWithBirthDateIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", PhoneNumber = "+7(111)111-11-11", BirthDate = DateTime.UtcNow.AddYears(-15), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
var workerModelWithPhoneNumberIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", PhoneNumber = "71", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModelWithIdIncorrect));
|
||||
var responseWithFioIncorrect = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModelWithFioIncorrect));
|
||||
var responseWithPostIdIncorrect = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModelWithPostIdIncorrect));
|
||||
var responseWithBirthDateIncorrect = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModelWithBirthDateIncorrect));
|
||||
var responseWithPhoneNumberIncorrect = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModelWithPhoneNumberIncorrect));
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
|
||||
Assert.That(responseWithFioIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Fio is incorrect");
|
||||
Assert.That(responseWithPostIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "PostId is incorrect");
|
||||
Assert.That(responseWithBirthDateIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "BirthDate is incorrect");
|
||||
Assert.That(responseWithPhoneNumberIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "PhoneNumber is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(string.Empty));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(workerId);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/workers/delete/{workerId}");
|
||||
SPiluSZharuDbContext.ChangeTracker.Clear();
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(SPiluSZharuDbContext.GetWorkerFromDatabaseById(workerId)!.IsDeleted);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/workers/delete/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenSendWrongFormatData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/workers/delete/id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenRecordWasDeleted_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerId = SPiluSZharuDbContext.InsertWorkerToDatabaseAndReturn(isDeleted: true).Id;
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/workers/delete/{workerId}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
private static void AssertElement(WorkerViewModel? actual, Worker expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.PostId, Is.EqualTo(expected.PostId));
|
||||
Assert.That(actual.PostName, Is.EqualTo(expected.Post!.PostName));
|
||||
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
|
||||
Assert.That(actual.PhoneNumber, Is.EqualTo(expected.PhoneNumber));
|
||||
Assert.That(actual.BirthDate.ToString(), Is.EqualTo(expected.BirthDate.ToString()));
|
||||
Assert.That(actual.EmploymentDate.ToString(), Is.EqualTo(expected.EmploymentDate.ToString()));
|
||||
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
|
||||
});
|
||||
}
|
||||
|
||||
private static WorkerBindingModel CreateModel(string postId, string? id = null, string fio = "fio", string phoneNumber = "+7(777)777-77-77", DateTime? birthDate = null, DateTime? employmentDate = null)
|
||||
{
|
||||
return new()
|
||||
{
|
||||
Id = id ?? Guid.NewGuid().ToString(),
|
||||
FIO = fio,
|
||||
PhoneNumber = phoneNumber,
|
||||
BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-22),
|
||||
EmploymentDate = employmentDate ?? DateTime.UtcNow.AddDays(-5),
|
||||
PostId = postId
|
||||
};
|
||||
}
|
||||
|
||||
private static void AssertElement(Worker? actual, WorkerBindingModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.PostId, Is.EqualTo(expected.PostId));
|
||||
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
|
||||
Assert.That(actual.PhoneNumber, Is.EqualTo(expected.PhoneNumber));
|
||||
Assert.That(actual.BirthDate.ToString(), Is.EqualTo(expected.BirthDate.ToString()));
|
||||
Assert.That(actual.EmploymentDate.ToString(), Is.EqualTo(expected.EmploymentDate.ToString()));
|
||||
Assert.That(!actual.IsDeleted);
|
||||
});
|
||||
}
|
||||
}
|
||||
24
SPiluSZharuProject/SPiluSZharuTests/appsettings.json
Normal file
24
SPiluSZharuProject/SPiluSZharuTests/appsettings.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": {
|
||||
"Default": "Information"
|
||||
},
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": {
|
||||
"path": "../logs/spiluszharu-.log",
|
||||
"rollingInterval": "Day",
|
||||
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {CorrelationId} {Level:u3} {Username} {Message:lj}{Exception}{NewLine}"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
271
SPiluSZharuProject/SPiluSZharuWebApi/Adapters/PostAdapter.cs
Normal file
271
SPiluSZharuProject/SPiluSZharuWebApi/Adapters/PostAdapter.cs
Normal file
@@ -0,0 +1,271 @@
|
||||
using AutoMapper;
|
||||
using SPiluSZharuContracts.AdapterContracts.OperationResponses;
|
||||
using SPiluSZharuContracts.AdapterContracts;
|
||||
using SPiluSZharuContracts.BindingModels;
|
||||
using SPiluSZharuContracts.DataModels;
|
||||
using SPiluSZharuContracts.Exceptions;
|
||||
using SPiluSZharuContracts.ViewModels;
|
||||
using SPiluSZharuContracts.BuisnessLogicContracts;
|
||||
using Moq;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace SPiluSZharuWebApi.Adapters;
|
||||
|
||||
public class PostAdapter : IPostAdapter
|
||||
{
|
||||
private readonly IPostBuisnessLogicContract _postBuisnessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
private readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
public PostAdapter(IPostBuisnessLogicContract postBuisnessLogicContract, ILogger<PostAdapter> logger)
|
||||
{
|
||||
_postBuisnessLogicContract = postBuisnessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<PostBindingModel, PostDataModel>();
|
||||
cfg.CreateMap<PostDataModel, PostViewModel>()
|
||||
.ForMember(x => x.Configuration, x => x.MapFrom(src => JsonSerializer.Serialize(src.ConfigurationModel, JsonSerializerOptions)));
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public PostOperationResponse GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return PostOperationResponse.OK([.. _postBuisnessLogicContract.GetAllPosts().Select(x => _mapper.Map<PostViewModel>(x))]);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return PostOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PostOperationResponse GetHistory(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return PostOperationResponse.OK([.. _postBuisnessLogicContract.GetAllDataOfPost(id).Select(x => _mapper.Map<PostViewModel>(x))]);
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return PostOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PostOperationResponse GetElement(string data)
|
||||
{
|
||||
try
|
||||
{
|
||||
return PostOperationResponse.OK(_mapper.Map<PostViewModel>(_postBuisnessLogicContract.GetPostByData(data)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return PostOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return PostOperationResponse.NotFound($"Not found element by data {data}");
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return PostOperationResponse.BadRequest($"Element by data: {data} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PostOperationResponse RegisterPost(PostBindingModel postModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_postBuisnessLogicContract.InsertPost(_mapper.Map<PostDataModel>(postModel));
|
||||
return PostOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return PostOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return PostOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PostOperationResponse ChangePostInfo(PostBindingModel postModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_postBuisnessLogicContract.UpdatePost(_mapper.Map<PostDataModel>(postModel));
|
||||
return PostOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return PostOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return PostOperationResponse.BadRequest($"Not found element by Id {postModel.Id}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return PostOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return PostOperationResponse.BadRequest($"Element by id: {postModel.Id} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PostOperationResponse RemovePost(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
_postBuisnessLogicContract.DeletePost(id);
|
||||
return PostOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return PostOperationResponse.BadRequest("Id is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return PostOperationResponse.BadRequest($"Not found element by id: {id}");
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return PostOperationResponse.BadRequest($"Element by id: {id} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PostOperationResponse RestorePost(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
_postBuisnessLogicContract.RestorePost(id);
|
||||
return PostOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return PostOperationResponse.BadRequest("Id is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return PostOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return PostOperationResponse.BadRequest($"Not found element by id: {id}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PostOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
233
SPiluSZharuProject/SPiluSZharuWebApi/Adapters/ProductAdapter.cs
Normal file
233
SPiluSZharuProject/SPiluSZharuWebApi/Adapters/ProductAdapter.cs
Normal file
@@ -0,0 +1,233 @@
|
||||
using AutoMapper;
|
||||
using SPiluSZharuContracts.AdapterContracts.OperationResponses;
|
||||
using SPiluSZharuContracts.AdapterContracts;
|
||||
using SPiluSZharuContracts.BindingModels;
|
||||
using SPiluSZharuContracts.DataModels;
|
||||
using SPiluSZharuContracts.Exceptions;
|
||||
using SPiluSZharuContracts.ViewModels;
|
||||
using SPiluSZharuContracts.BuisnessLogicContracts;
|
||||
|
||||
namespace SPiluSZharuWebApi.Adapters;
|
||||
|
||||
public class ProductAdapter : IProductAdapter
|
||||
{
|
||||
private readonly IProductBuisnessLogicContract _productBuisnessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public ProductAdapter(IProductBuisnessLogicContract productBuisnessLogicContract, ILogger<ProductAdapter> logger)
|
||||
{
|
||||
_productBuisnessLogicContract = productBuisnessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<ProductBindingModel, ProductDataModel>();
|
||||
cfg.CreateMap<ProductDataModel, ProductViewModel>();
|
||||
cfg.CreateMap<ProductHistoryDataModel, ProductHistoryViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public ProductOperationResponse GetList(bool includeDeleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ProductOperationResponse.OK([.. _productBuisnessLogicContract.GetAllProducts(!includeDeleted).Select(x => _mapper.Map<ProductViewModel>(x))]);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return ProductOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ProductOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ProductOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ProductOperationResponse GetHistory(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ProductOperationResponse.OK([.. _productBuisnessLogicContract.GetProductHistoryByProduct(id).Select(x => _mapper.Map<ProductHistoryViewModel>(x))]);
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return ProductOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return ProductOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ProductOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ProductOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ProductOperationResponse GetElement(string data)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ProductOperationResponse.OK(_mapper.Map<ProductViewModel>(_productBuisnessLogicContract.GetProductByData(data)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ProductOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return ProductOperationResponse.NotFound($"Not found element by data {data}");
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return ProductOperationResponse.BadRequest($"Element by data: {data} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ProductOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ProductOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ProductOperationResponse RegisterProduct(ProductBindingModel productModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_productBuisnessLogicContract.InsertProduct(_mapper.Map<ProductDataModel>(productModel));
|
||||
return ProductOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ProductOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return ProductOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return ProductOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ProductOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ProductOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ProductOperationResponse ChangeProductInfo(ProductBindingModel productModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_productBuisnessLogicContract.UpdateProduct(_mapper.Map<ProductDataModel>(productModel));
|
||||
return ProductOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ProductOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return ProductOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return ProductOperationResponse.BadRequest($"Not found element by Id {productModel.Id}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return ProductOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return ProductOperationResponse.BadRequest($"Element by id: {productModel.Id} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ProductOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ProductOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ProductOperationResponse RemoveProduct(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
_productBuisnessLogicContract.DeleteProduct(id);
|
||||
return ProductOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ProductOperationResponse.BadRequest("Id is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return ProductOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return ProductOperationResponse.BadRequest($"Not found element by id: {id}");
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return ProductOperationResponse.BadRequest($"Element by id: {id} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ProductOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ProductOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
using AutoMapper;
|
||||
using SPiluSZharuContracts.AdapterContracts;
|
||||
using SPiluSZharuContracts.AdapterContracts.OperationResponses;
|
||||
using SPiluSZharuContracts.BindingModels;
|
||||
using SPiluSZharuContracts.BuisnessLogicContracts;
|
||||
using SPiluSZharuContracts.DataModels;
|
||||
using SPiluSZharuContracts.Exceptions;
|
||||
using SPiluSZharuContracts.ViewModels;
|
||||
using SPiluSZharuDatabase;
|
||||
|
||||
namespace SPiluSZharuWebApi.Adapters;
|
||||
|
||||
public class RestaurantAdapter : IRestaurantAdapter
|
||||
{
|
||||
private readonly IRestaurantBuisnessLogicContract _restaurantBuisnessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public RestaurantAdapter(IRestaurantBuisnessLogicContract restaurantBuisnessLogicContract, ILogger<RestaurantAdapter> logger)
|
||||
{
|
||||
_restaurantBuisnessLogicContract = restaurantBuisnessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<RestaurantBindingModel, RestaurantDataModel>();
|
||||
cfg.CreateMap<RestaurantDataModel, RestaurantViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public RestaurantOperationResponse GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return RestaurantOperationResponse.OK([.. _restaurantBuisnessLogicContract.GetAllRestaurants().Select(x => _mapper.Map<RestaurantViewModel>(x))]);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return RestaurantOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return RestaurantOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return RestaurantOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public RestaurantOperationResponse GetElement(string data)
|
||||
{
|
||||
try
|
||||
{
|
||||
return RestaurantOperationResponse.OK(_mapper.Map<RestaurantViewModel>(_restaurantBuisnessLogicContract.GetRestaurantByData(data)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return RestaurantOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return RestaurantOperationResponse.NotFound($"Not found element by data {data}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return RestaurantOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return RestaurantOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public RestaurantOperationResponse RegisterRestaurant(RestaurantBindingModel restaurantModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_restaurantBuisnessLogicContract.InsertRestaurant(_mapper.Map<RestaurantDataModel>(restaurantModel));
|
||||
return RestaurantOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return RestaurantOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return RestaurantOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return RestaurantOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return RestaurantOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return RestaurantOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public RestaurantOperationResponse ChangeRestaurantInfo(RestaurantBindingModel restaurantModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_restaurantBuisnessLogicContract.UpdateRestaurant(_mapper.Map<RestaurantDataModel>(restaurantModel));
|
||||
return RestaurantOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return RestaurantOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return RestaurantOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return RestaurantOperationResponse.BadRequest($"Not found element by Id {restaurantModel.Id}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return RestaurantOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return RestaurantOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return RestaurantOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public RestaurantOperationResponse RemoveRestaurant(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
_restaurantBuisnessLogicContract.DeleteRestaurant(id);
|
||||
return RestaurantOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return RestaurantOperationResponse.BadRequest("Id is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return RestaurantOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return RestaurantOperationResponse.BadRequest($"Not found element by id: {id}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return RestaurantOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return RestaurantOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
125
SPiluSZharuProject/SPiluSZharuWebApi/Adapters/SalaryAdapter.cs
Normal file
125
SPiluSZharuProject/SPiluSZharuWebApi/Adapters/SalaryAdapter.cs
Normal file
@@ -0,0 +1,125 @@
|
||||
using AutoMapper;
|
||||
using SPiluSZharuContracts.AdapterContracts;
|
||||
using SPiluSZharuContracts.AdapterContracts.OperationResponses;
|
||||
using SPiluSZharuContracts.BuisnessLogicContracts;
|
||||
using SPiluSZharuContracts.DataModels;
|
||||
using SPiluSZharuContracts.Exceptions;
|
||||
using SPiluSZharuContracts.ViewModels;
|
||||
|
||||
namespace SPiluSZharuWebApi.Adapters;
|
||||
|
||||
public class SalaryAdapter : ISalaryAdapter
|
||||
{
|
||||
private readonly ISalaryBuisnessLogicContract _salaryBuisnessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public SalaryAdapter(ISalaryBuisnessLogicContract salaryBuisnessLogicContract, ILogger<SalaryAdapter> logger)
|
||||
{
|
||||
_salaryBuisnessLogicContract = salaryBuisnessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<SalaryDataModel, SalaryViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public SalaryOperationResponse GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SalaryOperationResponse.OK([.. _salaryBuisnessLogicContract.GetAllSalariesByPeriod(fromDate, toDate).Select(x => _mapper.Map<SalaryViewModel>(x))]);
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return SalaryOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return SalaryOperationResponse.BadRequest($"The end date must be later than the start date: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return SalaryOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SalaryOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SalaryOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SalaryOperationResponse GetAllSalariesByPeriodByWorker(DateTime fromDate, DateTime toDate, string workerId)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SalaryOperationResponse.OK([.. _salaryBuisnessLogicContract.GetAllSalariesByPeriodByWorker(fromDate, toDate, workerId).Select(x => _mapper.Map<SalaryViewModel>(x))]);
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return SalaryOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return SalaryOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return SalaryOperationResponse.BadRequest($"The end date must be later than the start date: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return SalaryOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SalaryOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SalaryOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SalaryOperationResponse CalculateSalaryByMounth(DateTime date)
|
||||
{
|
||||
try
|
||||
{
|
||||
_salaryBuisnessLogicContract.CalculateSalaryByMounth(date);
|
||||
return SalaryOperationResponse.NoContent();
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return SalaryOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SalaryOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SalaryOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
262
SPiluSZharuProject/SPiluSZharuWebApi/Adapters/SaleAdapter.cs
Normal file
262
SPiluSZharuProject/SPiluSZharuWebApi/Adapters/SaleAdapter.cs
Normal file
@@ -0,0 +1,262 @@
|
||||
using AutoMapper;
|
||||
using SPiluSZharuContracts.AdapterContracts.OperationResponses;
|
||||
using SPiluSZharuContracts.AdapterContracts;
|
||||
using SPiluSZharuContracts.BindingModels;
|
||||
using SPiluSZharuContracts.DataModels;
|
||||
using SPiluSZharuContracts.Exceptions;
|
||||
using SPiluSZharuContracts.ViewModels;
|
||||
using SPiluSZharuContracts.BuisnessLogicContracts;
|
||||
|
||||
namespace SPiluSZharuWebApi.Adapters;
|
||||
|
||||
public class SaleAdapter : ISaleAdapter
|
||||
{
|
||||
private readonly ISaleBuisnessLogicContract _saleBuisnessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public SaleAdapter(ISaleBuisnessLogicContract saleBuisnessLogicContract, ILogger<SaleAdapter> logger)
|
||||
{
|
||||
_saleBuisnessLogicContract = saleBuisnessLogicContract;
|
||||
_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([.. _saleBuisnessLogicContract.GetAllSalesByPeriod(fromDate, toDate).Select(x => _mapper.Map<SaleViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return SaleOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SaleOperationResponse GetWorkerList(string id, DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SaleOperationResponse.OK([.. _saleBuisnessLogicContract.GetAllSalesByWorkerByPeriod(id, fromDate, toDate).Select(x => _mapper.Map<SaleViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect dates: {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");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SaleOperationResponse GetRestaurantList(string id, DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SaleOperationResponse.OK([.. _saleBuisnessLogicContract.GetAllSalesByRestaurantByPeriod(id, fromDate, toDate).Select(x => _mapper.Map<SaleViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect dates: {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");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SaleOperationResponse GetProductList(string id, DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SaleOperationResponse.OK([.. _saleBuisnessLogicContract.GetAllSalesByProductByPeriod(id, fromDate, toDate).Select(x => _mapper.Map<SaleViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect dates: {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");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SaleOperationResponse GetElement(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SaleOperationResponse.OK(_mapper.Map<SaleViewModel>(_saleBuisnessLogicContract.GetSaleByData(id)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return SaleOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return SaleOperationResponse.NotFound($"Not found element by data {id}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SaleOperationResponse MakeSale(SaleBindingModel saleModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
var data = _mapper.Map<SaleDataModel>(saleModel);
|
||||
_saleBuisnessLogicContract.InsertSale(_mapper.Map<SaleDataModel>(saleModel));
|
||||
return SaleOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return SaleOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public SaleOperationResponse CancelSale(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
_saleBuisnessLogicContract.CancelSale(id);
|
||||
return SaleOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return SaleOperationResponse.BadRequest("Id is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return SaleOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return SaleOperationResponse.BadRequest($"Not found element by id: {id}");
|
||||
}
|
||||
catch (ElementDeletedException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementDeletedException");
|
||||
return SaleOperationResponse.BadRequest($"Element by id: {id} was deleted");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return SaleOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return SaleOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
278
SPiluSZharuProject/SPiluSZharuWebApi/Adapters/WorkerAdapter.cs
Normal file
278
SPiluSZharuProject/SPiluSZharuWebApi/Adapters/WorkerAdapter.cs
Normal file
@@ -0,0 +1,278 @@
|
||||
using AutoMapper;
|
||||
using SPiluSZharuContracts.AdapterContracts.OperationResponses;
|
||||
using SPiluSZharuContracts.AdapterContracts;
|
||||
using SPiluSZharuContracts.BindingModels;
|
||||
using SPiluSZharuContracts.DataModels;
|
||||
using SPiluSZharuContracts.Exceptions;
|
||||
using SPiluSZharuContracts.ViewModels;
|
||||
using SPiluSZharuContracts.BuisnessLogicContracts;
|
||||
|
||||
namespace SPiluSZharuWebApi.Adapters;
|
||||
|
||||
public class WorkerAdapter : IWorkerAdapter
|
||||
{
|
||||
private readonly IWorkerBuisnessLogicContract _workerBuisnessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public WorkerAdapter(IWorkerBuisnessLogicContract workerBuisnessLogicContract, ILogger<WorkerAdapter> logger)
|
||||
{
|
||||
_workerBuisnessLogicContract = workerBuisnessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<WorkerBindingModel, WorkerDataModel>();
|
||||
cfg.CreateMap<WorkerDataModel, WorkerViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public WorkerOperationResponse GetList(bool includeDeleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
return WorkerOperationResponse.OK([.. _workerBuisnessLogicContract.GetAllWorkers(!includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return WorkerOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return WorkerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return WorkerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public WorkerOperationResponse GetPostList(string id, bool includeDeleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
return WorkerOperationResponse.OK([.. _workerBuisnessLogicContract.GetAllWorkersByPost(id, !includeDeleted).Select(x => _mapper.Map<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");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return WorkerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return WorkerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public WorkerOperationResponse GetListByBirthDate(DateTime fromDate, DateTime toDate, bool includeDeleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
return WorkerOperationResponse.OK([.. _workerBuisnessLogicContract.GetAllWorkersByBirthDate(fromDate, toDate, !includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return WorkerOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return WorkerOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return WorkerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return WorkerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public WorkerOperationResponse GetListByEmploymentDate(DateTime fromDate, DateTime toDate, bool includeDeleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
return WorkerOperationResponse.OK([.. _workerBuisnessLogicContract.GetAllWorkersByEmploymentDate(fromDate, toDate, !includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return WorkerOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return WorkerOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return WorkerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return WorkerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public WorkerOperationResponse GetElement(string data)
|
||||
{
|
||||
try
|
||||
{
|
||||
return WorkerOperationResponse.OK(_mapper.Map<WorkerViewModel>(_workerBuisnessLogicContract.GetWorkerByData(data)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return WorkerOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return WorkerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return WorkerOperationResponse.NotFound($"Not found element by data {data}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return WorkerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return WorkerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public WorkerOperationResponse RegisterWorker(WorkerBindingModel workerModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_workerBuisnessLogicContract.InsertWorker(_mapper.Map<WorkerDataModel>(workerModel));
|
||||
return WorkerOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return WorkerOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return WorkerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return WorkerOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return WorkerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return WorkerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public WorkerOperationResponse ChangeWorkerInfo(WorkerBindingModel workerModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_workerBuisnessLogicContract.UpdateWorker(_mapper.Map<WorkerDataModel>(workerModel));
|
||||
return WorkerOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return WorkerOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return WorkerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return WorkerOperationResponse.BadRequest($"Not found element by Id {workerModel.Id}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return WorkerOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return WorkerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return WorkerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public WorkerOperationResponse RemoveWorker(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
_workerBuisnessLogicContract.DeleteWorker(id);
|
||||
return WorkerOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return WorkerOperationResponse.BadRequest("Id is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return WorkerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return WorkerOperationResponse.BadRequest($"Not found element by id: {id}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return WorkerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return WorkerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user