Compare commits
9 Commits
LabWork03_
...
LabWork05_
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2d06a51a2d | ||
|
|
ec71832652 | ||
|
|
c26b7017dc | ||
|
|
d725cfc544 | ||
|
|
0c05d06346 | ||
|
|
806490a3a4 | ||
|
|
1f354d36bc | ||
|
|
1217527e35 | ||
|
|
56ac4a9851 |
@@ -11,6 +11,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FurnitureAssemblyBusinessLo
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FurnitureAssemblyDatebase", "FurnitureAssemblyDatebase\FurnitureAssemblyDatebase.csproj", "{BDE6EBBB-E735-408D-B34B-490C2AE9201B}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FurnitureAssemblyWebApi", "FurnitureAssemblyWebApi\FurnitureAssemblyWebApi.csproj", "{17E280FB-248B-4B86-9CAF-40FCE2570BA0}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -33,6 +35,10 @@ Global
|
||||
{BDE6EBBB-E735-408D-B34B-490C2AE9201B}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{BDE6EBBB-E735-408D-B34B-490C2AE9201B}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{BDE6EBBB-E735-408D-B34B-490C2AE9201B}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{17E280FB-248B-4B86-9CAF-40FCE2570BA0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{17E280FB-248B-4B86-9CAF-40FCE2570BA0}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{17E280FB-248B-4B86-9CAF-40FCE2570BA0}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{17E280FB-248B-4B86-9CAF-40FCE2570BA0}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="FurnitureAssemblyTests" />
|
||||
<InternalsVisibleTo Include="FurnitureAssemblyWebApi" />
|
||||
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -27,10 +27,10 @@ internal class PostBusinessLogicContract(IPostStorageContract postStorageContrac
|
||||
return _postStorageContract.GetPostWithHistory(postId) ?? throw new NullListException();
|
||||
}
|
||||
|
||||
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 PostDataModel GetPostByData(string data)
|
||||
|
||||
@@ -2,19 +2,22 @@
|
||||
using FurnitureAssemblyContracts.DataModels;
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using FurnitureAssemblyContracts.Extentions;
|
||||
using FurnitureAssemblyContracts.Infrastructure;
|
||||
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
|
||||
using FurnitureAssemblyContracts.StoragesContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace FurnitureAssemblyBusinessLogic.Implementations;
|
||||
|
||||
internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract, IManifacturingStorageContract manifacturingStorageContract, IPostStorageContract
|
||||
postStorageContract, IWorkerStorageContract workerStorageContract, ILogger logger) : ISalaryBusinessLogicContract
|
||||
internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract, IManifacturingStorageContract manifacturingStorageContract,
|
||||
IWorkerStorageContract workerStorageContract, ILogger logger, IConfigurationSalary сonfiguration) : ISalaryBusinessLogicContract
|
||||
{
|
||||
private readonly ILogger _logger = logger;
|
||||
private readonly ISalaryStorageContract _salaryStorageContract = salaryStorageContract;
|
||||
private readonly IManifacturingStorageContract _manifacturingStorageContract = manifacturingStorageContract;
|
||||
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,11 +55,69 @@ internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageC
|
||||
var workers = _workerStorageContract.GetList() ?? throw new NullListException();
|
||||
foreach (var worker in workers)
|
||||
{
|
||||
var sales = _manifacturingStorageContract.GetList(startDate, finishDate, workerId: worker.Id)?.Sum(x => x.Count) ?? throw new NullListException();
|
||||
var post = _postStorageContract.GetElementById(worker.PostId) ?? throw new NullListException();
|
||||
var salary = post.Salary + sales * 0.1;
|
||||
_logger.LogDebug("The employee {workerId} was paid a salary of { salary}", worker.Id, salary);
|
||||
_salaryStorageContract.AddElement(new SalaryDataModel(worker.Id, finishDate, salary));
|
||||
var sales = _manifacturingStorageContract.GetList(startDate, finishDate, workerId: worker.Id) ?? throw new NullListException();
|
||||
var salary = worker.ConfigurationModel switch
|
||||
{
|
||||
null => 0,
|
||||
BuilderPostConfiguration cpc => CalculateSalaryForBuilder(sales, startDate, finishDate, cpc),
|
||||
ChiefPostConfiguration spc => CalculateSalaryForChief(startDate, finishDate, spc),
|
||||
PostConfiguration pc => pc.Rate,
|
||||
};
|
||||
_logger.LogDebug("The employee {workerId} was paid a salary of {salary}", worker.Id, salary);
|
||||
_logger.LogDebug("The employee {workerId} was paid a salary of { salary}", worker.Id, salary);
|
||||
_salaryStorageContract.AddElement(new SalaryDataModel(worker.Id, finishDate, salary));
|
||||
}
|
||||
}
|
||||
|
||||
private double CalculateSalaryForBuilder(List<ManifacturingFurnitureDataModel> sales, DateTime startDate, DateTime finishDate, BuilderPostConfiguration 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.ProductuionDate.Date == date.Date).ToArray();
|
||||
if (salesInDay.Length > 0)
|
||||
{
|
||||
lock (_lockObject)
|
||||
{
|
||||
calcPercent += (salesInDay.Sum(x => x.Count) / salesInDay.Length);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
double calcBonusTask = 0;
|
||||
try
|
||||
{
|
||||
calcBonusTask = sales.Where(x => x.Count > _salaryConfiguration.ExtraMadeSum).Sum(x => x.Count) * config.PersonalCount;
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error in bonus calculation");
|
||||
}
|
||||
return config.Rate + calcPercent + calcBonusTask;
|
||||
}
|
||||
|
||||
private double CalculateSalaryForChief(DateTime startDate, DateTime finishDate, ChiefPostConfiguration config)
|
||||
{
|
||||
try
|
||||
{
|
||||
return config.Rate + config.PersonalCountTrendPremium * _workerStorageContract.GetWorkerTrend(startDate, finishDate);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error in the supervisor payroll process");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,38 +10,19 @@ namespace FurnitureAssemblyBusinessLogic.Implementations;
|
||||
|
||||
internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageContract, ILogger logger) : IWorkerBusinessLogicContract
|
||||
{
|
||||
private readonly IWorkerStorageContract _workerStorageContract = workerStorageContract;
|
||||
|
||||
private readonly ILogger _logger = logger;
|
||||
private readonly IWorkerStorageContract _workerStorageContract = workerStorageContract;
|
||||
|
||||
public List<WorkerDataModel> GetAllWorkers(bool onlyActive = true)
|
||||
{
|
||||
logger.LogInformation("GetAllWorkers params: {onlyActive}", onlyActive);
|
||||
_logger.LogInformation("GetAllWorkers params: {onlyActive}", onlyActive);
|
||||
return _workerStorageContract.GetList(onlyActive) ?? throw new NullListException();
|
||||
}
|
||||
|
||||
public List<WorkerDataModel> GetAllWorkersByBirthDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
|
||||
{
|
||||
_logger.LogInformation("GetAllWorkers params: {onlyActive}, { fromDate}, { toDate}", onlyActive, fromDate, toDate);
|
||||
if (fromDate.IsDateNotOlder(toDate))
|
||||
{
|
||||
throw new IncorrectDatesException(fromDate, toDate);
|
||||
}
|
||||
return _workerStorageContract.GetList(onlyActive, fromBirthDate: fromDate, toBirthDate: toDate) ?? throw new NullListException();
|
||||
}
|
||||
|
||||
public List<WorkerDataModel> GetAllWorkersByEmploymentDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
|
||||
{
|
||||
logger.LogInformation("GetAllWorkers params: {onlyActive}, { fromDate}, { toDate}", onlyActive, fromDate, toDate);
|
||||
if (fromDate.IsDateNotOlder(toDate))
|
||||
{
|
||||
throw new IncorrectDatesException(fromDate, toDate);
|
||||
}
|
||||
return _workerStorageContract.GetList(onlyActive, fromEmploymentDate: fromDate, toEmploymentDate: toDate) ?? throw new NullListException();
|
||||
}
|
||||
|
||||
public List<WorkerDataModel> GetAllWorkersByPost(string postId, bool onlyActive = true)
|
||||
{
|
||||
_logger.LogInformation("GetAllWorkers params: {postId}, { onlyActive},", postId, onlyActive);
|
||||
_logger.LogInformation("GetAllWorkers params: {postId}, {onlyActive},", postId, onlyActive);
|
||||
if (postId.IsEmpty())
|
||||
{
|
||||
throw new ArgumentNullException(nameof(postId));
|
||||
@@ -53,6 +34,26 @@ internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageC
|
||||
return _workerStorageContract.GetList(onlyActive, postId) ?? throw new NullListException();
|
||||
}
|
||||
|
||||
public List<WorkerDataModel> GetAllWorkersByBirthDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
|
||||
{
|
||||
_logger.LogInformation("GetAllWorkers params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
|
||||
if (fromDate.IsDateNotOlder(toDate))
|
||||
{
|
||||
throw new IncorrectDatesException(fromDate, toDate);
|
||||
}
|
||||
return _workerStorageContract.GetList(onlyActive, fromBirthDate: fromDate, toBirthDate: toDate) ?? throw new NullListException();
|
||||
}
|
||||
|
||||
public List<WorkerDataModel> GetAllWorkersByEmploymentDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
|
||||
{
|
||||
_logger.LogInformation("GetAllWorkers params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
|
||||
if (fromDate.IsDateNotOlder(toDate))
|
||||
{
|
||||
throw new IncorrectDatesException(fromDate, toDate);
|
||||
}
|
||||
return _workerStorageContract.GetList(onlyActive, fromEmploymentDate: fromDate, toEmploymentDate: toDate) ?? throw new NullListException();
|
||||
}
|
||||
|
||||
public WorkerDataModel GetWorkerByData(string data)
|
||||
{
|
||||
_logger.LogInformation("Get element by data: {data}", data);
|
||||
@@ -78,7 +79,7 @@ internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageC
|
||||
|
||||
public void UpdateWorker(WorkerDataModel workerDataModel)
|
||||
{
|
||||
logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(workerDataModel));
|
||||
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(workerDataModel));
|
||||
ArgumentNullException.ThrowIfNull(workerDataModel);
|
||||
workerDataModel.Validate();
|
||||
_workerStorageContract.UpdElement(workerDataModel);
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
using FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
|
||||
using FurnitureAssemblyContracts.BindingModels;
|
||||
|
||||
namespace FurnitureAssemblyContracts.AdapterContracts;
|
||||
|
||||
public interface IComponentAdapter
|
||||
{
|
||||
ComponentOperationResponse GetAllComponents();
|
||||
ComponentOperationResponse GetComponentByData(string data);
|
||||
ComponentOperationResponse InsertComponent(ComponentBindingModel componentDataModel);
|
||||
ComponentOperationResponse UpdateComponent(ComponentBindingModel componentDataModel);
|
||||
ComponentOperationResponse DeleteComponent(string id);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
|
||||
using FurnitureAssemblyContracts.BindingModels;
|
||||
using FurnitureAssemblyContracts.DataModels;
|
||||
|
||||
namespace FurnitureAssemblyContracts.AdapterContracts;
|
||||
|
||||
public interface IFurnitureAdapter
|
||||
{
|
||||
FurnitureOperationResponse GetAllFurnitures();
|
||||
FurnitureOperationResponse GetFurnitureByData(string data);
|
||||
FurnitureOperationResponse InsertFurniture(FurnitureBindingModel furnitureDataModel);
|
||||
FurnitureOperationResponse UpdateFurniture(FurnitureBindingModel furnitureDataModel);
|
||||
FurnitureOperationResponse DeleteFurniture(string id);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
|
||||
using FurnitureAssemblyContracts.BindingModels;
|
||||
|
||||
namespace FurnitureAssemblyContracts.AdapterContracts;
|
||||
|
||||
public interface IManifacturingFurnitureAdapter
|
||||
{
|
||||
ManifacturingFurnitureOperationResponse GetList(DateTime fromDate, DateTime toDate);
|
||||
ManifacturingFurnitureOperationResponse GetAllManifacturingByWorkerByPeriod(string workerId, DateTime fromDate, DateTime toDate);
|
||||
ManifacturingFurnitureOperationResponse GetAllManifacturingByFurnitureByPeriod(string furnitureId, DateTime fromDate, DateTime toDate);
|
||||
ManifacturingFurnitureOperationResponse GetElement(string data);
|
||||
ManifacturingFurnitureOperationResponse RegisterManifacturingFurniture(ManifacturingFurnitureBindingModel model);
|
||||
ManifacturingFurnitureOperationResponse ChangeManifacturingFurniture(ManifacturingFurnitureBindingModel model);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
|
||||
using FurnitureAssemblyContracts.BindingModels;
|
||||
|
||||
namespace FurnitureAssemblyContracts.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,10 @@
|
||||
using FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
namespace FurnitureAssemblyContracts.AdapterContracts;
|
||||
|
||||
public interface ISalaryAdapter
|
||||
{
|
||||
SalaryOperationResponse GetListByPeriod(DateTime fromDate, DateTime toDate);
|
||||
SalaryOperationResponse GetListByPeriodByWorker(DateTime fromDate, DateTime toDate, string workerId);
|
||||
SalaryOperationResponse CalculateSalary(DateTime date);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
|
||||
using FurnitureAssemblyContracts.BindingModels;
|
||||
|
||||
namespace FurnitureAssemblyContracts.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 FurnitureAssemblyContracts.Infrastructure;
|
||||
using FurnitureAssemblyContracts.ViewModels;
|
||||
|
||||
namespace FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class ComponentOperationResponse : OperationResponse
|
||||
{
|
||||
public static ComponentOperationResponse OK(List<ComponentViewModel> data) => OK<ComponentOperationResponse, List<ComponentViewModel>>(data);
|
||||
|
||||
public static ComponentOperationResponse OK(ComponentViewModel data) => OK<ComponentOperationResponse, ComponentViewModel>(data);
|
||||
|
||||
public static ComponentOperationResponse NoContent() => NoContent<ComponentOperationResponse>();
|
||||
|
||||
public static ComponentOperationResponse NotFound(string message) => NotFound<ComponentOperationResponse>(message);
|
||||
|
||||
public static ComponentOperationResponse BadRequest(string message) => BadRequest<ComponentOperationResponse>(message);
|
||||
|
||||
public static ComponentOperationResponse InternalServerError(string message) => InternalServerError<ComponentOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using FurnitureAssemblyContracts.Infrastructure;
|
||||
using FurnitureAssemblyContracts.ViewModels;
|
||||
|
||||
namespace FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class FurnitureOperationResponse : OperationResponse
|
||||
{
|
||||
public static FurnitureOperationResponse OK(List<FurnitureViewModel> data) => OK<FurnitureOperationResponse, List<FurnitureViewModel>>(data);
|
||||
|
||||
public static FurnitureOperationResponse OK(FurnitureViewModel data) => OK<FurnitureOperationResponse, FurnitureViewModel>(data);
|
||||
|
||||
public static FurnitureOperationResponse NoContent() => NoContent<FurnitureOperationResponse>();
|
||||
|
||||
public static FurnitureOperationResponse NotFound(string message) => NotFound<FurnitureOperationResponse>(message);
|
||||
|
||||
public static FurnitureOperationResponse BadRequest(string message) => BadRequest<FurnitureOperationResponse>(message);
|
||||
|
||||
public static FurnitureOperationResponse InternalServerError(string message) => InternalServerError<FurnitureOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using FurnitureAssemblyContracts.Infrastructure;
|
||||
using FurnitureAssemblyContracts.ViewModels;
|
||||
|
||||
namespace FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class ManifacturingFurnitureOperationResponse : OperationResponse
|
||||
{
|
||||
public static ManifacturingFurnitureOperationResponse OK(List<ManifacturingFurnitureViewModel> data) =>
|
||||
OK<ManifacturingFurnitureOperationResponse, List<ManifacturingFurnitureViewModel>>(data);
|
||||
|
||||
public static ManifacturingFurnitureOperationResponse OK(ManifacturingFurnitureViewModel data) =>
|
||||
OK<ManifacturingFurnitureOperationResponse, ManifacturingFurnitureViewModel>(data);
|
||||
|
||||
public static ManifacturingFurnitureOperationResponse NoContent() =>
|
||||
NoContent<ManifacturingFurnitureOperationResponse>();
|
||||
|
||||
public static ManifacturingFurnitureOperationResponse NotFound(string message) =>
|
||||
NotFound<ManifacturingFurnitureOperationResponse>(message);
|
||||
|
||||
public static ManifacturingFurnitureOperationResponse BadRequest(string message) =>
|
||||
BadRequest<ManifacturingFurnitureOperationResponse>(message);
|
||||
|
||||
public static ManifacturingFurnitureOperationResponse InternalServerError(string message) =>
|
||||
InternalServerError<ManifacturingFurnitureOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using FurnitureAssemblyContracts.Infrastructure;
|
||||
using FurnitureAssemblyContracts.ViewModels;
|
||||
|
||||
namespace FurnitureAssemblyContracts.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,13 @@
|
||||
using FurnitureAssemblyContracts.Infrastructure;
|
||||
using FurnitureAssemblyContracts.ViewModels;
|
||||
|
||||
namespace FurnitureAssemblyContracts.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 FurnitureAssemblyContracts.Infrastructure;
|
||||
using FurnitureAssemblyContracts.ViewModels;
|
||||
|
||||
namespace FurnitureAssemblyContracts.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,11 @@
|
||||
using FurnitureAssemblyContracts.Enums;
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace FurnitureAssemblyContracts.BindingModels;
|
||||
|
||||
public class ComponentBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? Name { get; set; }
|
||||
public ComponentType? Type { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace FurnitureAssemblyContracts.BindingModels;
|
||||
|
||||
public class FurnitureBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? Name { get; set; }
|
||||
public int Weight { get; set; }
|
||||
public List<FurnitureComponentBindingModel>? Components { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace FurnitureAssemblyContracts.BindingModels;
|
||||
|
||||
public class FurnitureComponentBindingModel
|
||||
{
|
||||
public string? FurnitureId { get; set; }
|
||||
public string? ComponentId { get; set; }
|
||||
public int Count { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace FurnitureAssemblyContracts.BindingModels;
|
||||
|
||||
public class ManifacturingFurnitureBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? FurnitureId { get; set; }
|
||||
public int Count { get; set; }
|
||||
public DateTime ProductionDate { get; set; }
|
||||
public string? WorkerId { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace FurnitureAssemblyContracts.BindingModels;
|
||||
|
||||
public class PostBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? PostId => Id;
|
||||
public string? PostName { get; set; }
|
||||
public string? PostType { get; set; }
|
||||
public double Salary { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace FurnitureAssemblyContracts.BindingModels;
|
||||
|
||||
public class WorkerBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? FIO { get; set; }
|
||||
public string? PostId { get; set; }
|
||||
public DateTime BirthDate { get; set; }
|
||||
public DateTime EmploymentDate { get; set; }
|
||||
public string? ConfigurationJson { get; set; }
|
||||
}
|
||||
@@ -4,7 +4,7 @@ namespace FurnitureAssemblyContracts.BusinessLogicsContracts;
|
||||
|
||||
public interface IPostBusinessLogicContract
|
||||
{
|
||||
List<PostDataModel> GetAllPosts(bool onlyActive);
|
||||
List<PostDataModel> GetAllPosts();
|
||||
List<PostDataModel> GetAllDataOfPost(string postId);
|
||||
PostDataModel GetPostByData(string data);
|
||||
void InsertPost(PostDataModel postDataModel);
|
||||
|
||||
@@ -4,13 +4,32 @@ using FurnitureAssemblyContracts.Infrastructure;
|
||||
|
||||
namespace FurnitureAssemblyContracts.DataModels;
|
||||
|
||||
public class ManifacturingFurnitureDataModel(string id, string furnitureId, int count, string workerId) : IValidation
|
||||
public class ManifacturingFurnitureDataModel : IValidation
|
||||
{
|
||||
public string Id { get; private set; } = id;
|
||||
public string FurnitureId { get; private set; } = furnitureId;
|
||||
public int Count { get; private set; } = count;
|
||||
private readonly WorkerDataModel? _worker;
|
||||
private readonly FurnitureDataModel? _furniture;
|
||||
public string Id { get; private set; }
|
||||
public string FurnitureId { get; private set; }
|
||||
public int Count { get; private set; }
|
||||
public DateTime ProductuionDate { get; private set; } = DateTime.UtcNow;
|
||||
public string WorkerId { get; private set; } = workerId;
|
||||
public string WorkerId { get; private set; }
|
||||
public string WorkerFIO => _worker?.FIO ?? string.Empty;
|
||||
public string FurnitureName => _furniture?.Name ?? string.Empty;
|
||||
|
||||
public ManifacturingFurnitureDataModel(string id, string furnitureId, int count, string workerId)
|
||||
{
|
||||
Id = id;
|
||||
FurnitureId = furnitureId;
|
||||
Count = count;
|
||||
WorkerId = workerId;
|
||||
}
|
||||
|
||||
public ManifacturingFurnitureDataModel(string id, string furnitureId, int count, string workerId, WorkerDataModel worker, FurnitureDataModel furniture)
|
||||
: this(id, furnitureId, count, workerId)
|
||||
{
|
||||
_worker = worker;
|
||||
_furniture = furniture;
|
||||
}
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
|
||||
@@ -5,14 +5,12 @@ using FurnitureAssemblyContracts.Infrastructure;
|
||||
|
||||
namespace FurnitureAssemblyContracts.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, double salary) : IValidation
|
||||
{
|
||||
public string Id { get; private set; } = postid;
|
||||
public string PostName { get; private set; } = postName;
|
||||
public PostType PostType { get; private set; } = postType;
|
||||
public double Salary { get; private set; } = salary;
|
||||
public bool IsActual { get; private set; } = isActual;
|
||||
public DateTime ChangeDate { get; private set; } = changeDate;
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
|
||||
@@ -6,9 +6,16 @@ namespace FurnitureAssemblyContracts.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 WorkerFIO => _worker?.FIO ?? string.Empty;
|
||||
|
||||
public SalaryDataModel(string workerId, DateTime salaryDate, double workerSalary, WorkerDataModel worker) : this(workerId, salaryDate, workerSalary)
|
||||
{
|
||||
_worker = worker;
|
||||
}
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
|
||||
@@ -2,37 +2,84 @@
|
||||
using FurnitureAssemblyContracts.Infrastructure;
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using System.Text.RegularExpressions;
|
||||
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace FurnitureAssemblyContracts.DataModels;
|
||||
|
||||
public class WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted) : IValidation
|
||||
public class WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted, PostConfiguration configuration) : IValidation
|
||||
{
|
||||
private readonly PostDataModel? _post;
|
||||
|
||||
public string Id { get; private set; } = id;
|
||||
|
||||
public string FIO { get; private set; } = fio;
|
||||
|
||||
public string PostId { get; private set; } = postId;
|
||||
|
||||
public DateTime BirthDate { get; private set; } = birthDate;
|
||||
|
||||
public DateTime EmploymentDate { get; private set; } = employmentDate;
|
||||
|
||||
public bool IsDeleted { get; private set; } = isDeleted;
|
||||
|
||||
public string PostName => _post?.PostName ?? string.Empty;
|
||||
public PostConfiguration ConfigurationModel { get; private set; } = configuration;
|
||||
|
||||
|
||||
public WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted, PostConfiguration configuration, PostDataModel post) : this(id, fio, postId, birthDate, employmentDate, isDeleted, configuration)
|
||||
{
|
||||
_post = post;
|
||||
}
|
||||
|
||||
public WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate, string configurationJson) : this(id, fio, postId, birthDate, employmentDate, false, (PostConfiguration)null)
|
||||
{
|
||||
var obj = JToken.Parse(configurationJson);
|
||||
if (obj is not null)
|
||||
{
|
||||
ConfigurationModel = obj.Value<string>("Type") switch
|
||||
{
|
||||
nameof(BuilderPostConfiguration) => JsonConvert.DeserializeObject<BuilderPostConfiguration>(configurationJson)!,
|
||||
nameof(ChiefPostConfiguration) => JsonConvert.DeserializeObject<ChiefPostConfiguration>(configurationJson)!,
|
||||
_ => JsonConvert.DeserializeObject<PostConfiguration>(configurationJson)!,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (Id.IsEmpty())
|
||||
throw new ValidationException("Field Id is empty");
|
||||
|
||||
if (!Id.IsGuid())
|
||||
throw new ValidationException("The value in the field Id is not a unique identifier");
|
||||
|
||||
if (FIO.IsEmpty())
|
||||
throw new ValidationException("Field FIO is empty");
|
||||
|
||||
if (!Regex.IsMatch(FIO, @"^([А-ЯЁ][а-яё]*(-[А-ЯЁ][а-яё]*)?)\s([А-ЯЁ]\.?\s?([А-ЯЁ]\.?\s?)?)?$"))
|
||||
throw new ValidationException("Field FIO is not a fio");
|
||||
|
||||
if (PostId.IsEmpty())
|
||||
throw new ValidationException("Field PostId is empty");
|
||||
|
||||
if (!PostId.IsGuid())
|
||||
throw new ValidationException("The value in the field PostId is not a unique identifier");
|
||||
|
||||
if (BirthDate.Date > DateTime.Now.AddYears(-14).Date)
|
||||
throw new ValidationException($"Minors cannot be hired (BirthDate = {BirthDate.ToShortDateString()})");
|
||||
|
||||
if (EmploymentDate.Date < BirthDate.Date)
|
||||
throw new ValidationException("The date of employment cannot be less than the date of birth");
|
||||
if ((EmploymentDate - BirthDate).TotalDays / 365 < 14)
|
||||
throw new ValidationException($"Minors cannot be hired (EmploymentDate - {EmploymentDate.ToShortDateString()}, BirthDate -{BirthDate.ToShortDateString()})");
|
||||
|
||||
if ((EmploymentDate - BirthDate).TotalDays / 365 < 14) // EmploymentDate.Year - BirthDate.Year
|
||||
throw new ValidationException($"Minors cannot be hired (EmploymentDate - {EmploymentDate.ToShortDateString()}, BirthDate - {BirthDate.ToShortDateString()})");
|
||||
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,5 +5,5 @@ public enum PostType
|
||||
None = 0,
|
||||
ComponentMaker = 1,
|
||||
Builder = 2,
|
||||
Loader = 3
|
||||
Chief = 3
|
||||
}
|
||||
|
||||
@@ -6,4 +6,10 @@
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.3.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.3.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace FurnitureAssemblyContracts.Infrastructure;
|
||||
|
||||
|
||||
public interface IConfigurationSalary
|
||||
{
|
||||
double ExtraMadeSum { get; }
|
||||
int MaxConcurrentThreads { get; }
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Net;
|
||||
|
||||
namespace FurnitureAssemblyContracts.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,16 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
|
||||
namespace FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
|
||||
|
||||
public class BuilderPostConfiguration : PostConfiguration
|
||||
{
|
||||
public override string Type => nameof(BuilderPostConfiguration);
|
||||
public double PersonalCount { get; set; }
|
||||
public BuilderPostConfiguration(IConfiguration? config = null)
|
||||
{
|
||||
if (config != null)
|
||||
{
|
||||
config.GetSection("BuilderSettings");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
|
||||
|
||||
public class ChiefPostConfiguration : PostConfiguration
|
||||
{
|
||||
public override string Type => nameof(ChiefPostConfiguration);
|
||||
public double PersonalCountTrendPremium { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
|
||||
|
||||
public class PostConfiguration
|
||||
{
|
||||
public virtual string Type => nameof(PostConfiguration);
|
||||
public double Rate { get; set; }
|
||||
}
|
||||
@@ -4,7 +4,7 @@ namespace FurnitureAssemblyContracts.StoragesContracts;
|
||||
|
||||
public interface IPostStorageContract
|
||||
{
|
||||
List<PostDataModel> GetList(bool onlyActual = true);
|
||||
List<PostDataModel> GetList();
|
||||
List<PostDataModel> GetPostWithHistory(string postId);
|
||||
PostDataModel? GetElementById(string id);
|
||||
PostDataModel? GetElementByName(string name);
|
||||
|
||||
@@ -11,4 +11,5 @@ public interface IWorkerStorageContract
|
||||
void AddElement(WorkerDataModel workerDataModel);
|
||||
void UpdElement(WorkerDataModel workerDataModel);
|
||||
void DelElement(string id);
|
||||
int GetWorkerTrend(DateTime fromPeriod, DateTime toPeriod);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
using FurnitureAssemblyContracts.Enums;
|
||||
|
||||
namespace FurnitureAssemblyContracts.ViewModels;
|
||||
|
||||
public class ComponentViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
public required string Name { get; set; }
|
||||
public string? PrevName { get; set; }
|
||||
public string? PrevPrevName { get; set; }
|
||||
public ComponentType Type { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace FurnitureAssemblyContracts.ViewModels;
|
||||
|
||||
public class FurnitureComponentViewModel
|
||||
{
|
||||
public required string FurnitureId { get; set; }
|
||||
public required string ComponentId { get; set; }
|
||||
public int Count { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace FurnitureAssemblyContracts.ViewModels;
|
||||
|
||||
public class FurnitureViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
public required string Name { get; set; }
|
||||
public int Weight { get; set; }
|
||||
public List<FurnitureComponentViewModel>? Components { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace FurnitureAssemblyContracts.ViewModels;
|
||||
|
||||
public class ManifacturingFurnitureViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
public required string FurnitureId { get; set; }
|
||||
public required int Count { get; set; }
|
||||
public DateTime ProductionDate { get; set; }
|
||||
public required string WorkerId { get; set; }
|
||||
public string? WorkerFIO { get; set; }
|
||||
public string? FurnitureName { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace FurnitureAssemblyContracts.ViewModels;
|
||||
|
||||
public class PostViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
public required string PostName { get; set; }
|
||||
public required string PostType { get; set; }
|
||||
public double Salary { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace FurnitureAssemblyContracts.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,13 @@
|
||||
namespace FurnitureAssemblyContracts.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 bool IsDeleted { get; set; }
|
||||
public DateTime BirthDate { get; set; }
|
||||
public DateTime EmploymentDate { get; set; }
|
||||
public required string Configuration { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using FurnitureAssemblyContracts.Infrastructure;
|
||||
|
||||
namespace FurnitureAssemblyDatebase;
|
||||
|
||||
class DefaultConfigurationDatabase : IConfigurationDatabase
|
||||
{
|
||||
public string ConnectionString => "";
|
||||
}
|
||||
@@ -9,6 +9,11 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoMapper" Version="14.0.0" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.2" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.2">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Newtonsoft.Json" Version="9.0.1" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -16,4 +21,10 @@
|
||||
<ProjectReference Include="..\FurnitureAssemblyContracts\FurnitureAssemblyContracts.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="FurnitureAssemblyTests" />
|
||||
<InternalVisibleTo Include="FurnitureAssemblyWebApi" />
|
||||
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -1,12 +1,22 @@
|
||||
using FurnitureAssemblyContracts.Infrastructure;
|
||||
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace FurnitureAssemblyDatebase;
|
||||
|
||||
public class FurnitureAssemblyDbContext(IConfigurationDatabase configurationDatabase) : DbContext
|
||||
public class FurnitureAssemblyDbContext : DbContext
|
||||
{
|
||||
private readonly IConfigurationDatabase? _configurationDatabase = configurationDatabase;
|
||||
private readonly IConfigurationDatabase? _configurationDatabase;
|
||||
|
||||
public FurnitureAssemblyDbContext(IConfigurationDatabase configurationDatabase)
|
||||
{
|
||||
_configurationDatabase = configurationDatabase;
|
||||
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
|
||||
AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);
|
||||
}
|
||||
|
||||
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
||||
{
|
||||
@@ -40,6 +50,13 @@ public class FurnitureAssemblyDbContext(IConfigurationDatabase configurationData
|
||||
.WithMany(f => f.Components)
|
||||
.HasForeignKey(fc => fc.FurnitureId)
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
|
||||
modelBuilder.Entity<Worker>()
|
||||
.Property(x => x.Configuration)
|
||||
.HasColumnType("jsonb")
|
||||
.HasConversion(
|
||||
x => SerializePostConfiguration(x),
|
||||
x => DeserialzePostConfiguration(x));
|
||||
}
|
||||
|
||||
public DbSet<ManifacturingFurniture> Manufacturing { get; set; }
|
||||
@@ -49,4 +66,13 @@ public class FurnitureAssemblyDbContext(IConfigurationDatabase configurationData
|
||||
public DbSet<Furniture> Furnitures { get; set; }
|
||||
public DbSet<FurnitureComponent> FurnitureComponents { 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(BuilderPostConfiguration) => JsonConvert.DeserializeObject<BuilderPostConfiguration>(jsonString)!,
|
||||
nameof(ChiefPostConfiguration) => JsonConvert.DeserializeObject<ChiefPostConfiguration>(jsonString)!,
|
||||
_ => JsonConvert.DeserializeObject<PostConfiguration>(jsonString)!,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -20,6 +20,8 @@ public class FurnitureStorageContract : IFurnitureStorageContract
|
||||
{
|
||||
cfg.CreateMap<Furniture, FurnitureDataModel>();
|
||||
cfg.CreateMap<FurnitureDataModel, Furniture>();
|
||||
cfg.CreateMap<FurnitureComponent, FurnitureComponentDataModel>();
|
||||
cfg.CreateMap<FurnitureComponentDataModel, FurnitureComponent>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
@@ -18,6 +18,8 @@ public class ManifacturingStorageContract : IManifacturingStorageContract
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Worker, WorkerDataModel>();
|
||||
cfg.CreateMap<Furniture, FurnitureDataModel>();
|
||||
cfg.CreateMap<ManifacturingFurniture, ManifacturingFurnitureDataModel>();
|
||||
cfg.CreateMap<ManifacturingFurnitureDataModel, ManifacturingFurniture>();
|
||||
});
|
||||
@@ -102,5 +104,5 @@ public class ManifacturingStorageContract : IManifacturingStorageContract
|
||||
}
|
||||
}
|
||||
|
||||
private ManifacturingFurniture? GetManifacturingById(string id) => _dbContext.Manufacturing.FirstOrDefault(x => x.Id == id);
|
||||
private ManifacturingFurniture? GetManifacturingById(string id) => _dbContext.Manufacturing.Include(x => x.Worker).Include(x => x.Furniture).FirstOrDefault(x => x.Id == id);
|
||||
}
|
||||
|
||||
@@ -20,7 +20,8 @@ public class PostStorageContract : IPostStorageContract
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Post, PostDataModel>()
|
||||
.ForMember(x => x.Id, x => x.MapFrom(src => src.PostId));
|
||||
.ForMember(x => x.Id, x => x.MapFrom(src =>
|
||||
src.PostId));
|
||||
cfg.CreateMap<PostDataModel, Post>()
|
||||
.ForMember(x => x.Id, x => x.Ignore())
|
||||
.ForMember(x => x.PostId, x => x.MapFrom(src => src.Id))
|
||||
@@ -30,23 +31,17 @@ public class PostStorageContract : IPostStorageContract
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<PostDataModel> GetList(bool onlyActual = true)
|
||||
public List<PostDataModel> GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
var query = _dbContext.Posts.AsQueryable();
|
||||
if (onlyActual)
|
||||
{
|
||||
query = query.Where(x => x.IsActual);
|
||||
}
|
||||
return [.. query.Select(x => _mapper.Map<PostDataModel>(x))];
|
||||
return [.._dbContext.Posts.Select(x => _mapper.Map<PostDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public PostDataModel? GetElementById(string id)
|
||||
@@ -122,7 +117,8 @@ public class PostStorageContract : IPostStorageContract
|
||||
var element = GetPostById(postDataModel.Id) ?? throw new ElementNotFoundException(postDataModel.Id);
|
||||
if (!element.IsActual)
|
||||
{
|
||||
throw new ElementDeletedException(postDataModel.Id);
|
||||
throw new
|
||||
ElementDeletedException(postDataModel.Id);
|
||||
}
|
||||
element.IsActual = false;
|
||||
_dbContext.SaveChanges();
|
||||
|
||||
@@ -3,6 +3,7 @@ using FurnitureAssemblyContracts.DataModels;
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using FurnitureAssemblyContracts.StoragesContracts;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace FurnitureAssemblyDatebase.Implementations;
|
||||
|
||||
@@ -16,6 +17,7 @@ public 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));
|
||||
@@ -26,7 +28,7 @@ public class SalaryStorageContract : ISalaryStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
var query = _dbContext.Salaries.Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate);
|
||||
var query = _dbContext.Salaries.Include(x => x.Worker).Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate);
|
||||
if (workerId is not null)
|
||||
{
|
||||
query = query.Where(x => x.WorkerId == workerId);
|
||||
|
||||
@@ -16,9 +16,13 @@ public 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.CreateMap<Worker, WorkerDataModel>();
|
||||
cfg.CreateMap<WorkerDataModel, Worker>();
|
||||
});
|
||||
cfg.CreateMap<WorkerDataModel, Worker>()
|
||||
.ForMember(x => x.Configuration, x => x.MapFrom(src => src.ConfigurationModel));
|
||||
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
@@ -43,7 +47,7 @@ public 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)
|
||||
{
|
||||
@@ -69,8 +73,7 @@ public 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)
|
||||
{
|
||||
@@ -122,9 +125,9 @@ public class WorkerStorageContract : IWorkerStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
var element = GetWorkerById(id) ?? throw new
|
||||
ElementNotFoundException(id);
|
||||
var element = GetWorkerById(id) ?? throw new ElementNotFoundException(id);
|
||||
element.IsDeleted = true;
|
||||
element.DateOfDelete = DateTime.UtcNow;
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (ElementNotFoundException)
|
||||
@@ -139,5 +142,27 @@ public 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));
|
||||
}
|
||||
|
||||
278
FurnitureAssembly/FurnitureAssemblyDatebase/Migrations/20250404123937_FirstMigration.Designer.cs
generated
Normal file
278
FurnitureAssembly/FurnitureAssemblyDatebase/Migrations/20250404123937_FirstMigration.Designer.cs
generated
Normal file
@@ -0,0 +1,278 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using FurnitureAssemblyDatebase;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace FurnitureAssemblyDatebase.Migrations
|
||||
{
|
||||
[DbContext(typeof(FurnitureAssemblyDbContext))]
|
||||
[Migration("20250404123937_FirstMigration")]
|
||||
partial class FirstMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "9.0.2")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Component", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PrevName")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PrevPrevName")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Type")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Name")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Components");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Furniture", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Weight")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Name")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Furnitures");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.FurnitureComponent", b =>
|
||||
{
|
||||
b.Property<string>("FurnitureId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ComponentId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Count")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("FurnitureId", "ComponentId");
|
||||
|
||||
b.HasIndex("ComponentId");
|
||||
|
||||
b.ToTable("FurnitureComponents");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.ManifacturingFurniture", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Count")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("FurnitureId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("ProductuionDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<string>("WorkerId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("FurnitureId");
|
||||
|
||||
b.HasIndex("WorkerId");
|
||||
|
||||
b.ToTable("Manufacturing");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.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("FurnitureAssemblyDatebase.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("FurnitureAssemblyDatebase.Models.Worker", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("BirthDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<DateTime>("ChangeDate")
|
||||
.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>("PostId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Workers");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.FurnitureComponent", b =>
|
||||
{
|
||||
b.HasOne("FurnitureAssemblyDatebase.Models.Component", "Component")
|
||||
.WithMany("FurnitureComponents")
|
||||
.HasForeignKey("ComponentId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("FurnitureAssemblyDatebase.Models.Furniture", "Furniture")
|
||||
.WithMany("Components")
|
||||
.HasForeignKey("FurnitureId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Component");
|
||||
|
||||
b.Navigation("Furniture");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.ManifacturingFurniture", b =>
|
||||
{
|
||||
b.HasOne("FurnitureAssemblyDatebase.Models.Furniture", "Furniture")
|
||||
.WithMany()
|
||||
.HasForeignKey("FurnitureId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("FurnitureAssemblyDatebase.Models.Worker", "Worker")
|
||||
.WithMany("ManifacturingFurniture")
|
||||
.HasForeignKey("WorkerId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Furniture");
|
||||
|
||||
b.Navigation("Worker");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Salary", b =>
|
||||
{
|
||||
b.HasOne("FurnitureAssemblyDatebase.Models.Worker", "Worker")
|
||||
.WithMany("Salaries")
|
||||
.HasForeignKey("WorkerId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Worker");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Component", b =>
|
||||
{
|
||||
b.Navigation("FurnitureComponents");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Furniture", b =>
|
||||
{
|
||||
b.Navigation("Components");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Worker", b =>
|
||||
{
|
||||
b.Navigation("ManifacturingFurniture");
|
||||
|
||||
b.Navigation("Salaries");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace FurnitureAssemblyDatebase.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class FirstMigration : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Components",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<string>(type: "text", nullable: false),
|
||||
Name = table.Column<string>(type: "text", nullable: false),
|
||||
PrevName = table.Column<string>(type: "text", nullable: true),
|
||||
PrevPrevName = table.Column<string>(type: "text", nullable: true),
|
||||
Type = table.Column<int>(type: "integer", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Components", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Furnitures",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<string>(type: "text", nullable: false),
|
||||
Name = table.Column<string>(type: "text", nullable: false),
|
||||
Weight = table.Column<int>(type: "integer", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Furnitures", x => x.Id);
|
||||
});
|
||||
|
||||
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: "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),
|
||||
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),
|
||||
ChangeDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Workers", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "FurnitureComponents",
|
||||
columns: table => new
|
||||
{
|
||||
FurnitureId = table.Column<string>(type: "text", nullable: false),
|
||||
ComponentId = table.Column<string>(type: "text", nullable: false),
|
||||
Count = table.Column<int>(type: "integer", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_FurnitureComponents", x => new { x.FurnitureId, x.ComponentId });
|
||||
table.ForeignKey(
|
||||
name: "FK_FurnitureComponents_Components_ComponentId",
|
||||
column: x => x.ComponentId,
|
||||
principalTable: "Components",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
table.ForeignKey(
|
||||
name: "FK_FurnitureComponents_Furnitures_FurnitureId",
|
||||
column: x => x.FurnitureId,
|
||||
principalTable: "Furnitures",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Manufacturing",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<string>(type: "text", nullable: false),
|
||||
FurnitureId = table.Column<string>(type: "text", nullable: false),
|
||||
Count = table.Column<int>(type: "integer", nullable: false),
|
||||
ProductuionDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
|
||||
WorkerId = table.Column<string>(type: "text", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Manufacturing", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_Manufacturing_Furnitures_FurnitureId",
|
||||
column: x => x.FurnitureId,
|
||||
principalTable: "Furnitures",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
table.ForeignKey(
|
||||
name: "FK_Manufacturing_Workers_WorkerId",
|
||||
column: x => x.WorkerId,
|
||||
principalTable: "Workers",
|
||||
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),
|
||||
WorkerSalary = table.Column<double>(type: "double precision", nullable: false),
|
||||
SalaryDate = table.Column<DateTime>(type: "timestamp without time zone", 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.CreateIndex(
|
||||
name: "IX_Components_Name",
|
||||
table: "Components",
|
||||
column: "Name",
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_FurnitureComponents_ComponentId",
|
||||
table: "FurnitureComponents",
|
||||
column: "ComponentId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Furnitures_Name",
|
||||
table: "Furnitures",
|
||||
column: "Name",
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Manufacturing_FurnitureId",
|
||||
table: "Manufacturing",
|
||||
column: "FurnitureId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Manufacturing_WorkerId",
|
||||
table: "Manufacturing",
|
||||
column: "WorkerId");
|
||||
|
||||
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_Salaries_WorkerId",
|
||||
table: "Salaries",
|
||||
column: "WorkerId");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "FurnitureComponents");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Manufacturing");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Posts");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Salaries");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Components");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Furnitures");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Workers");
|
||||
}
|
||||
}
|
||||
}
|
||||
285
FurnitureAssembly/FurnitureAssemblyDatebase/Migrations/20250415132953_ChangeWorker.Designer.cs
generated
Normal file
285
FurnitureAssembly/FurnitureAssemblyDatebase/Migrations/20250415132953_ChangeWorker.Designer.cs
generated
Normal file
@@ -0,0 +1,285 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using FurnitureAssemblyDatebase;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace FurnitureAssemblyDatebase.Migrations
|
||||
{
|
||||
[DbContext(typeof(FurnitureAssemblyDbContext))]
|
||||
[Migration("20250415132953_ChangeWorker")]
|
||||
partial class ChangeWorker
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "9.0.2")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Component", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PrevName")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PrevPrevName")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Type")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Name")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Components");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Furniture", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Weight")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Name")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Furnitures");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.FurnitureComponent", b =>
|
||||
{
|
||||
b.Property<string>("FurnitureId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ComponentId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Count")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("FurnitureId", "ComponentId");
|
||||
|
||||
b.HasIndex("ComponentId");
|
||||
|
||||
b.ToTable("FurnitureComponents");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.ManifacturingFurniture", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Count")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("FurnitureId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("ProductuionDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<string>("WorkerId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("FurnitureId");
|
||||
|
||||
b.HasIndex("WorkerId");
|
||||
|
||||
b.ToTable("Manufacturing");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.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("FurnitureAssemblyDatebase.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("FurnitureAssemblyDatebase.Models.Worker", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("BirthDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<DateTime>("ChangeDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<string>("Configuration")
|
||||
.IsRequired()
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
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>("PostId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Workers");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.FurnitureComponent", b =>
|
||||
{
|
||||
b.HasOne("FurnitureAssemblyDatebase.Models.Component", "Component")
|
||||
.WithMany("FurnitureComponents")
|
||||
.HasForeignKey("ComponentId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("FurnitureAssemblyDatebase.Models.Furniture", "Furniture")
|
||||
.WithMany("Components")
|
||||
.HasForeignKey("FurnitureId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Component");
|
||||
|
||||
b.Navigation("Furniture");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.ManifacturingFurniture", b =>
|
||||
{
|
||||
b.HasOne("FurnitureAssemblyDatebase.Models.Furniture", "Furniture")
|
||||
.WithMany()
|
||||
.HasForeignKey("FurnitureId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("FurnitureAssemblyDatebase.Models.Worker", "Worker")
|
||||
.WithMany("ManifacturingFurniture")
|
||||
.HasForeignKey("WorkerId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Furniture");
|
||||
|
||||
b.Navigation("Worker");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Salary", b =>
|
||||
{
|
||||
b.HasOne("FurnitureAssemblyDatebase.Models.Worker", "Worker")
|
||||
.WithMany("Salaries")
|
||||
.HasForeignKey("WorkerId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Worker");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Component", b =>
|
||||
{
|
||||
b.Navigation("FurnitureComponents");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Furniture", b =>
|
||||
{
|
||||
b.Navigation("Components");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Worker", b =>
|
||||
{
|
||||
b.Navigation("ManifacturingFurniture");
|
||||
|
||||
b.Navigation("Salaries");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace FurnitureAssemblyDatebase.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class ChangeWorker : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "Configuration",
|
||||
table: "Workers",
|
||||
type: "jsonb",
|
||||
nullable: false,
|
||||
defaultValue: "");
|
||||
|
||||
migrationBuilder.AddColumn<DateTime>(
|
||||
name: "DateOfDelete",
|
||||
table: "Workers",
|
||||
type: "timestamp without time zone",
|
||||
nullable: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "Configuration",
|
||||
table: "Workers");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "DateOfDelete",
|
||||
table: "Workers");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using FurnitureAssemblyDatebase;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace FurnitureAssemblyDatebase.Migrations
|
||||
{
|
||||
[DbContext(typeof(FurnitureAssemblyDbContext))]
|
||||
partial class FurnitureAssemblyDbContextModelSnapshot : ModelSnapshot
|
||||
{
|
||||
protected override void BuildModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "9.0.2")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Component", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PrevName")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PrevPrevName")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Type")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Name")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Components");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Furniture", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Weight")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Name")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Furnitures");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.FurnitureComponent", b =>
|
||||
{
|
||||
b.Property<string>("FurnitureId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ComponentId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Count")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("FurnitureId", "ComponentId");
|
||||
|
||||
b.HasIndex("ComponentId");
|
||||
|
||||
b.ToTable("FurnitureComponents");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.ManifacturingFurniture", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Count")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("FurnitureId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("ProductuionDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<string>("WorkerId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("FurnitureId");
|
||||
|
||||
b.HasIndex("WorkerId");
|
||||
|
||||
b.ToTable("Manufacturing");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.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("FurnitureAssemblyDatebase.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("FurnitureAssemblyDatebase.Models.Worker", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("BirthDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<DateTime>("ChangeDate")
|
||||
.HasColumnType("timestamp without time zone");
|
||||
|
||||
b.Property<string>("Configuration")
|
||||
.IsRequired()
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
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>("PostId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Workers");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.FurnitureComponent", b =>
|
||||
{
|
||||
b.HasOne("FurnitureAssemblyDatebase.Models.Component", "Component")
|
||||
.WithMany("FurnitureComponents")
|
||||
.HasForeignKey("ComponentId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("FurnitureAssemblyDatebase.Models.Furniture", "Furniture")
|
||||
.WithMany("Components")
|
||||
.HasForeignKey("FurnitureId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Component");
|
||||
|
||||
b.Navigation("Furniture");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.ManifacturingFurniture", b =>
|
||||
{
|
||||
b.HasOne("FurnitureAssemblyDatebase.Models.Furniture", "Furniture")
|
||||
.WithMany()
|
||||
.HasForeignKey("FurnitureId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("FurnitureAssemblyDatebase.Models.Worker", "Worker")
|
||||
.WithMany("ManifacturingFurniture")
|
||||
.HasForeignKey("WorkerId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Furniture");
|
||||
|
||||
b.Navigation("Worker");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Salary", b =>
|
||||
{
|
||||
b.HasOne("FurnitureAssemblyDatebase.Models.Worker", "Worker")
|
||||
.WithMany("Salaries")
|
||||
.HasForeignKey("WorkerId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Worker");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Component", b =>
|
||||
{
|
||||
b.Navigation("FurnitureComponents");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Furniture", b =>
|
||||
{
|
||||
b.Navigation("Components");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Worker", b =>
|
||||
{
|
||||
b.Navigation("ManifacturingFurniture");
|
||||
|
||||
b.Navigation("Salaries");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using FurnitureAssemblyContracts.Enums;
|
||||
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace FurnitureAssemblyDatebase.Models;
|
||||
@@ -16,4 +17,14 @@ public class Worker
|
||||
public List<Salary>? Salaries { get; set; }
|
||||
[ForeignKey("WorkerId")]
|
||||
public List<ManifacturingFurniture>? ManifacturingFurniture { get; set; }
|
||||
[NotMapped]
|
||||
public Post? Post { get; set; }
|
||||
public Worker AddPost(Post? post)
|
||||
{
|
||||
Post = post;
|
||||
return this;
|
||||
}
|
||||
public DateTime? DateOfDelete { get; set; }
|
||||
public required PostConfiguration Configuration { get; set; }
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
using Microsoft.EntityFrameworkCore.Design;
|
||||
|
||||
namespace FurnitureAssemblyDatebase;
|
||||
|
||||
internal class SampleContextFactory : IDesignTimeDbContextFactory<FurnitureAssemblyDbContext>
|
||||
{
|
||||
public FurnitureAssemblyDbContext CreateDbContext(string[] args)
|
||||
{
|
||||
return new FurnitureAssemblyDbContext(new DefaultConfigurationDatabase());
|
||||
}
|
||||
}
|
||||
@@ -32,61 +32,53 @@ internal class PostBusinessLogicContractTests
|
||||
//Arrange
|
||||
var listOriginal = new List<PostDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(),"name 1", PostType.Builder, 10, true, DateTime.UtcNow),
|
||||
new(Guid.NewGuid().ToString(), "name 2", PostType.Builder, 10, false, DateTime.UtcNow),
|
||||
new(Guid.NewGuid().ToString(), "name 3", PostType.Builder, 10, true, DateTime.UtcNow),
|
||||
new(Guid.NewGuid().ToString(), "name 1", PostType.Builder, 10),
|
||||
new(Guid.NewGuid().ToString(), "name 2", PostType.Builder, 10),
|
||||
new(Guid.NewGuid().ToString(), "name 3", PostType.Builder, 10),
|
||||
};
|
||||
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Returns(listOriginal);
|
||||
_postStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
|
||||
//Act
|
||||
var listOnlyActive = _postBusinessLogicContract.GetAllPosts(true);
|
||||
var listAll = _postBusinessLogicContract.GetAllPosts(false);
|
||||
var list = _postBusinessLogicContract.GetAllPosts();
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(listOnlyActive, Is.Not.Null);
|
||||
Assert.That(listAll, Is.Not.Null);
|
||||
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
|
||||
Assert.That(listAll, Is.EquivalentTo(listOriginal));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.EquivalentTo(listOriginal));
|
||||
});
|
||||
_postStorageContract.Verify(x => x.GetList(true), Times.Once);
|
||||
_postStorageContract.Verify(x => x.GetList(false), Times.Once);
|
||||
_postStorageContract.Verify(x => x.GetList(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllPosts_ReturnEmptyList_Test()
|
||||
{
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Returns([]);
|
||||
_postStorageContract.Setup(x => x.GetList()).Returns([]);
|
||||
//Act
|
||||
var listOnlyActive = _postBusinessLogicContract.GetAllPosts(true);
|
||||
var listAll = _postBusinessLogicContract.GetAllPosts(false);
|
||||
var list = _postBusinessLogicContract.GetAllPosts();
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(listOnlyActive, Is.Not.Null);
|
||||
Assert.That(listAll, Is.Not.Null);
|
||||
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
|
||||
Assert.That(listAll, Has.Count.EqualTo(0));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(0));
|
||||
});
|
||||
_postStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Exactly(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllPosts_ReturnNull_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.GetAllPosts(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
|
||||
_postStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Once);
|
||||
Assert.That(() => _postBusinessLogicContract.GetAllPosts(), Throws.TypeOf<NullListException>());
|
||||
_postStorageContract.Verify(x => x.GetList(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllPosts_StorageThrowError_ThrowException_Test()
|
||||
{
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
_postStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.GetAllPosts(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
|
||||
_postStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Once);
|
||||
Assert.That(() => _postBusinessLogicContract.GetAllPosts(), Throws.TypeOf<StorageException>());
|
||||
_postStorageContract.Verify(x => x.GetList(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -96,8 +88,8 @@ internal class PostBusinessLogicContractTests
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
var listOriginal = new List<PostDataModel>()
|
||||
{
|
||||
new(postId, "name 1", PostType.Builder, 10, true, DateTime.UtcNow),
|
||||
new(postId, "name 2", PostType.Builder, 10, false, DateTime.UtcNow)
|
||||
new(postId, "name 1", PostType.Builder, 10),
|
||||
new(postId, "name 2", PostType.Builder, 10)
|
||||
};
|
||||
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -161,7 +153,7 @@ internal class PostBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var id = Guid.NewGuid().ToString();
|
||||
var record = new PostDataModel(id, "name", PostType.Builder, 10, true, DateTime.UtcNow);
|
||||
var record = new PostDataModel(id, "name", PostType.Builder, 10);
|
||||
_postStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
|
||||
//Act
|
||||
var element = _postBusinessLogicContract.GetPostByData(id);
|
||||
@@ -176,7 +168,7 @@ internal class PostBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var postName = "name";
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.Builder, 10, true, DateTime.UtcNow);
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.Builder, 10);
|
||||
_postStorageContract.Setup(x => x.GetElementByName(postName)).Returns(record);
|
||||
//Act
|
||||
var element = _postBusinessLogicContract.GetPostByData(postName);
|
||||
@@ -232,11 +224,11 @@ internal class PostBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var flag = false;
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 10, true, DateTime.UtcNow.AddDays(-1));
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 10);
|
||||
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>()))
|
||||
.Callback((PostDataModel x) =>
|
||||
{
|
||||
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary && x.ChangeDate == record.ChangeDate;
|
||||
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary;
|
||||
});
|
||||
|
||||
//Act
|
||||
@@ -252,7 +244,7 @@ internal class PostBusinessLogicContractTests
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementExistsException>());
|
||||
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, 10)), Throws.TypeOf<ElementExistsException>());
|
||||
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -268,7 +260,7 @@ internal class PostBusinessLogicContractTests
|
||||
public void InsertPost_InvalidRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Builder, 10, true, DateTime.UtcNow)), Throws.TypeOf<ValidationException>());
|
||||
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Builder, 10)), Throws.TypeOf<ValidationException>());
|
||||
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
@@ -278,7 +270,7 @@ internal class PostBusinessLogicContractTests
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, 10, true, DateTime.UtcNow)), Throws.TypeOf<StorageException>());
|
||||
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, 10)), Throws.TypeOf<StorageException>());
|
||||
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -287,10 +279,10 @@ internal class PostBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var flag = false;
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 10, true, DateTime.UtcNow.AddDays(-1));
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 10);
|
||||
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Callback((PostDataModel x) =>
|
||||
{
|
||||
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary && x.ChangeDate == record.ChangeDate;
|
||||
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary;
|
||||
});
|
||||
//Act
|
||||
_postBusinessLogicContract.UpdatePost(record);
|
||||
@@ -305,7 +297,7 @@ internal class PostBusinessLogicContractTests
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementNotFoundException(""));
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementNotFoundException>());
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, 10)), Throws.TypeOf<ElementNotFoundException>());
|
||||
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -315,7 +307,7 @@ internal class PostBusinessLogicContractTests
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.Builder, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementExistsException>());
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.Builder, 10)), Throws.TypeOf<ElementExistsException>());
|
||||
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -331,7 +323,7 @@ internal class PostBusinessLogicContractTests
|
||||
public void UpdatePost_InvalidRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Builder, 10, true, DateTime.UtcNow)), Throws.TypeOf<ValidationException>());
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Builder, 10)), Throws.TypeOf<ValidationException>());
|
||||
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
@@ -341,7 +333,7 @@ internal class PostBusinessLogicContractTests
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, 10, true, DateTime.UtcNow)), Throws.TypeOf<StorageException>());
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, 10)), Throws.TypeOf<StorageException>());
|
||||
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
using FurnitureAssemblyBusinessLogic.Implementations;
|
||||
using FurnitureAssemblyContracts.DataModels;
|
||||
using FurnitureAssemblyContracts.Enums;
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
|
||||
using FurnitureAssemblyContracts.StoragesContracts;
|
||||
using FurnitureAssemblyTests.Infrastructure;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
|
||||
@@ -13,18 +14,17 @@ internal class SalaryBuisnessLogicContractTests
|
||||
private SalaryBusinessLogicContract _salaryBusinessLogicContract;
|
||||
private Mock<ISalaryStorageContract> _salaryStorageContract;
|
||||
private Mock<IManifacturingStorageContract> _manifacturingStorageContract;
|
||||
private Mock<IPostStorageContract> _postStorageContract;
|
||||
private Mock<IWorkerStorageContract> _workerStorageContract;
|
||||
private readonly ConfigurationSalaryTest _salaryConfigurationTest = new();
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
_salaryStorageContract = new Mock<ISalaryStorageContract>();
|
||||
_manifacturingStorageContract = new Mock<IManifacturingStorageContract>();
|
||||
_postStorageContract = new Mock<IPostStorageContract>();
|
||||
_workerStorageContract = new Mock<IWorkerStorageContract>();
|
||||
_salaryBusinessLogicContract = new SalaryBusinessLogicContract(_salaryStorageContract.Object,
|
||||
_manifacturingStorageContract.Object, _postStorageContract.Object, _workerStorageContract.Object, new Mock<ILogger>().Object);
|
||||
_manifacturingStorageContract.Object, _workerStorageContract.Object, new Mock<ILogger>().Object, _salaryConfigurationTest);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
@@ -32,7 +32,6 @@ internal class SalaryBuisnessLogicContractTests
|
||||
{
|
||||
_salaryStorageContract.Reset();
|
||||
_manifacturingStorageContract.Reset();
|
||||
_postStorageContract.Reset();
|
||||
_workerStorageContract.Reset();
|
||||
}
|
||||
|
||||
@@ -186,15 +185,12 @@ internal class SalaryBuisnessLogicContractTests
|
||||
//Arrange
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
var saleSum = 200;
|
||||
var postSalary = 2000;
|
||||
var rate = 10.0;
|
||||
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns([new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), saleSum, workerId)]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, postSalary, true, DateTime.UtcNow));
|
||||
_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(), DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false, new PostConfiguration() { Rate = rate })]);
|
||||
var sum = 0.0;
|
||||
var expectedSum = postSalary + saleSum * 0.1;
|
||||
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
|
||||
.Callback((SalaryDataModel x) =>
|
||||
{
|
||||
@@ -203,7 +199,7 @@ internal class SalaryBuisnessLogicContractTests
|
||||
//Act
|
||||
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
|
||||
//Assert
|
||||
Assert.That(sum, Is.EqualTo(expectedSum));
|
||||
Assert.That(sum, Is.EqualTo(rate));
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -214,9 +210,9 @@ internal class SalaryBuisnessLogicContractTests
|
||||
var worker2Id = Guid.NewGuid().ToString();
|
||||
var worker3Id = Guid.NewGuid().ToString();
|
||||
var list = new List<WorkerDataModel>() {
|
||||
new(worker1Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
|
||||
new(worker2Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
|
||||
new(worker3Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)
|
||||
new(worker1Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false, new PostConfiguration() { Rate = 10 }),
|
||||
new(worker2Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false, new PostConfiguration() { Rate = 10 }),
|
||||
new(worker3Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false, new PostConfiguration() { Rate = 10 })
|
||||
};
|
||||
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns([new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, worker1Id),
|
||||
@@ -224,8 +220,6 @@ internal class SalaryBuisnessLogicContractTests
|
||||
new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, worker2Id),
|
||||
new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, worker3Id),
|
||||
new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, worker3Id)]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 2000, true, DateTime.UtcNow));
|
||||
_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
|
||||
@@ -238,14 +232,12 @@ internal class SalaryBuisnessLogicContractTests
|
||||
public void CalculateSalaryByMounth_WithoitSalesByWorker_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postSalary = 2000.0;
|
||||
var postSalary = 10;
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns([]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, postSalary, true, DateTime.UtcNow));
|
||||
_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(), DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false, new PostConfiguration() { Rate = 10 })]);
|
||||
var sum = 0.0;
|
||||
var expectedSum = postSalary;
|
||||
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
|
||||
@@ -264,23 +256,8 @@ 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.Builder, 2000, true, DateTime.UtcNow));
|
||||
_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(), DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
//Act&Assert
|
||||
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CalculateSalaryByMounth_PostStorageReturnNull_ThrowException_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns([new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, workerId)]);
|
||||
_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(), DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false, new PostConfiguration() { Rate = 10 })]);
|
||||
//Act&Assert
|
||||
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
|
||||
}
|
||||
@@ -292,8 +269,6 @@ internal class SalaryBuisnessLogicContractTests
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns([new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, workerId)]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 2000, true, DateTime.UtcNow));
|
||||
//Act&Assert
|
||||
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
|
||||
}
|
||||
@@ -305,25 +280,8 @@ internal class SalaryBuisnessLogicContractTests
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), 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.Builder, 2000, true, DateTime.UtcNow));
|
||||
_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(), DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
//Act&Assert
|
||||
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CalculateSalaryByMounth_PostStorageThrowException_ThrowException_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns([new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, workerId)]);
|
||||
_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?>()))
|
||||
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false, new PostConfiguration() { Rate = 10 })]);
|
||||
//Act&Assert
|
||||
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
|
||||
}
|
||||
@@ -335,11 +293,67 @@ internal class SalaryBuisnessLogicContractTests
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns([new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, workerId)]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 2000, true, DateTime.UtcNow));
|
||||
_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(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CalculateSalaryByMountht_WithBuilderPostConfiguration_CalculateSalary_Test()
|
||||
{
|
||||
//Arrange
|
||||
var furnitureId = Guid.NewGuid().ToString();
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
var rate = 2000.0;
|
||||
var bonus = 0.1;
|
||||
var sales = new List<ManifacturingFurnitureDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), furnitureId, 10, workerId),
|
||||
new(Guid.NewGuid().ToString(), furnitureId, 15, workerId),
|
||||
new(Guid.NewGuid().ToString(), furnitureId, 10, workerId)
|
||||
};
|
||||
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(sales);
|
||||
_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(), DateTime.UtcNow, DateTime.UtcNow, false, new BuilderPostConfiguration() { Rate = rate, PersonalCount = bonus })]);
|
||||
var sum = 0.0;
|
||||
var expectedSum = rate + (sales.Sum(x => x.Count) / sales.Count) + sales.Where(x => x.Count > _salaryConfigurationTest.ExtraMadeSum).Sum(x => x.Count) * bonus;
|
||||
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
|
||||
.Callback((SalaryDataModel x) =>
|
||||
{
|
||||
sum = x.Salary;
|
||||
});
|
||||
//Act
|
||||
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
|
||||
//Assert
|
||||
Assert.That(sum, Is.EqualTo(expectedSum));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CalculateSalaryByMountht_WithChiefPostConfiguration_CalculateSalary_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
var rate = 2000.0;
|
||||
var trend = 3;
|
||||
var bonus = 100;
|
||||
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns([new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, workerId)]);
|
||||
_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(), DateTime.UtcNow, DateTime.UtcNow, false, new ChiefPostConfiguration() { Rate = rate, PersonalCountTrendPremium = bonus })]);
|
||||
_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
|
||||
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
|
||||
//Assert
|
||||
Assert.That(sum, Is.EqualTo(expectedSum));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using FurnitureAssemblyBusinessLogic.Implementations;
|
||||
using FurnitureAssemblyContracts.DataModels;
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
|
||||
using FurnitureAssemblyContracts.StoragesContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
@@ -31,9 +32,9 @@ internal class WorkerBusinessLogicContractTests
|
||||
//Arrange
|
||||
var listOriginal = new List<WorkerDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), "Иванов И.И.1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
|
||||
new(Guid.NewGuid().ToString(), "Иванов И.И.2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true),
|
||||
new(Guid.NewGuid().ToString(), "Иванов И.И.3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
|
||||
new(Guid.NewGuid().ToString(), "Иванов И.И.1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 }),
|
||||
new(Guid.NewGuid().ToString(), "Иванов И.И.2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true, new PostConfiguration() { Rate = 10 }),
|
||||
new(Guid.NewGuid().ToString(), "Иванов И.И.3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 }),
|
||||
};
|
||||
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -95,9 +96,9 @@ internal class WorkerBusinessLogicContractTests
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
var listOriginal = new List<WorkerDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), "Иванов И.И.1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
|
||||
new(Guid.NewGuid().ToString(), "Иванов И.И.2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true),
|
||||
new(Guid.NewGuid().ToString(), "Иванов И.И.3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
|
||||
new(Guid.NewGuid().ToString(), "Иванов И.И.1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 }),
|
||||
new(Guid.NewGuid().ToString(), "Иванов И.И.2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true, new PostConfiguration() { Rate = 10 }),
|
||||
new(Guid.NewGuid().ToString(), "Иванов И.И.3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 }),
|
||||
};
|
||||
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -176,9 +177,9 @@ internal class WorkerBusinessLogicContractTests
|
||||
var date = DateTime.UtcNow;
|
||||
var listOriginal = new List<WorkerDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), "Иванов И.И.1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
|
||||
new(Guid.NewGuid().ToString(), "Иванов И.И.2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true),
|
||||
new(Guid.NewGuid().ToString(), "Иванов И.И.3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
|
||||
new(Guid.NewGuid().ToString(), "Иванов И.И.1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 }),
|
||||
new(Guid.NewGuid().ToString(), "Иванов И.И.2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true, new PostConfiguration() { Rate = 10 }),
|
||||
new(Guid.NewGuid().ToString(), "Иванов И.И.3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 }),
|
||||
};
|
||||
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -252,9 +253,9 @@ internal class WorkerBusinessLogicContractTests
|
||||
var date = DateTime.UtcNow;
|
||||
var listOriginal = new List<WorkerDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), "Иванов И.И.1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
|
||||
new(Guid.NewGuid().ToString(), "Иванов И.И.2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true),
|
||||
new(Guid.NewGuid().ToString(), "Иванов И.И.3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
|
||||
new(Guid.NewGuid().ToString(), "Иванов И.И.1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 }),
|
||||
new(Guid.NewGuid().ToString(), "Иванов И.И.2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true, new PostConfiguration() { Rate = 10 }),
|
||||
new(Guid.NewGuid().ToString(), "Иванов И.И.3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 }),
|
||||
};
|
||||
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -326,7 +327,7 @@ internal class WorkerBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var id = Guid.NewGuid().ToString();
|
||||
var record = new WorkerDataModel(id, "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false);
|
||||
var record = new WorkerDataModel(id, "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 });
|
||||
_workerStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
|
||||
//Act
|
||||
var element = _workerBusinessLogicContract.GetWorkerByData(id);
|
||||
@@ -341,7 +342,7 @@ internal class WorkerBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var fio = "Иванов И.И.";
|
||||
var record = new WorkerDataModel(Guid.NewGuid().ToString(), fio, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false);
|
||||
var record = new WorkerDataModel(Guid.NewGuid().ToString(), fio, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 });
|
||||
_workerStorageContract.Setup(x => x.GetElementByFIO(fio)).Returns(record);
|
||||
//Act
|
||||
var element = _workerBusinessLogicContract.GetWorkerByData(fio);
|
||||
@@ -397,7 +398,7 @@ internal class WorkerBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var flag = false;
|
||||
var record = new WorkerDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false);
|
||||
var record = new WorkerDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 1 });
|
||||
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>()))
|
||||
.Callback((WorkerDataModel x) =>
|
||||
{
|
||||
@@ -417,7 +418,7 @@ internal class WorkerBusinessLogicContractTests
|
||||
//Arrange
|
||||
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>())).Throws(new ElementExistsException("Data", "Data"));
|
||||
//Act&Assert
|
||||
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-14).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementExistsException>());
|
||||
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-14).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementExistsException>());
|
||||
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -433,7 +434,7 @@ internal class WorkerBusinessLogicContractTests
|
||||
public void InsertWorker_InvalidRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new WorkerDataModel("id", "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ValidationException>());
|
||||
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new WorkerDataModel("id", "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ValidationException>());
|
||||
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
@@ -443,7 +444,7 @@ internal class WorkerBusinessLogicContractTests
|
||||
//Arrange
|
||||
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>());
|
||||
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<StorageException>());
|
||||
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -452,7 +453,7 @@ internal class WorkerBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var flag = false;
|
||||
var record = new WorkerDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false);
|
||||
var record = new WorkerDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 });
|
||||
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>()))
|
||||
.Callback((WorkerDataModel x) =>
|
||||
{
|
||||
@@ -472,7 +473,7 @@ internal class WorkerBusinessLogicContractTests
|
||||
//Arrange
|
||||
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>())).Throws(new ElementNotFoundException(""));
|
||||
//Act&Assert
|
||||
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementNotFoundException>());
|
||||
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementNotFoundException>());
|
||||
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -488,7 +489,7 @@ internal class WorkerBusinessLogicContractTests
|
||||
public void UpdateWorker_InvalidRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new WorkerDataModel("id", "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ValidationException>());
|
||||
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new WorkerDataModel("id", "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ValidationException>());
|
||||
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
@@ -498,7 +499,7 @@ internal class WorkerBusinessLogicContractTests
|
||||
//Arrange
|
||||
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>());
|
||||
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<StorageException>());
|
||||
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
|
||||
@@ -10,43 +10,43 @@ internal class PostDataModelTests
|
||||
[Test]
|
||||
public void IdIsNullOrEmptyTest()
|
||||
{
|
||||
var model = CreateDataModel(null, "name", PostType.Builder, 100, true, DateTime.Now);
|
||||
var model = CreateDataModel(null, "name", PostType.Builder, 100);
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
|
||||
model = CreateDataModel(string.Empty, "name", PostType.Builder, 100, true, DateTime.Now);
|
||||
model = CreateDataModel(string.Empty, "name", PostType.Builder, 100);
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void IdIsNotGuidTest()
|
||||
{
|
||||
var model = CreateDataModel("id", "name", PostType.Builder, 100, true, DateTime.Now);
|
||||
var model = CreateDataModel("id", "name", PostType.Builder, 100);
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PostNameIsNullOrEmptyTest()
|
||||
{
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Builder, 100, true, DateTime.Now);
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Builder, 100);
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
|
||||
model = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Builder, 100, true, DateTime.Now);
|
||||
model = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Builder, 100);
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PostTypeIsNoneTest()
|
||||
{
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.None, 100, true, DateTime.Now);
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.None, 100);
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SalaryIsZeroNegativeTest()
|
||||
{
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 0, true, DateTime.Now);
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 0);
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
model = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, -1, true, DateTime.Now);
|
||||
model = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, -1);
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@ internal class PostDataModelTests
|
||||
var salary = 100.50;
|
||||
var isActual = true;
|
||||
var changeDate = DateTime.Now;
|
||||
var model = CreateDataModel(id, postName, postType, salary, isActual, changeDate);
|
||||
var model = CreateDataModel(id, postName, postType, salary);
|
||||
|
||||
Assert.That(() => model.Validate(), Throws.Nothing);
|
||||
Assert.Multiple(() =>
|
||||
@@ -68,11 +68,9 @@ internal class PostDataModelTests
|
||||
Assert.That(model.PostName, Is.EqualTo(postName));
|
||||
Assert.That(model.PostType, Is.EqualTo(postType));
|
||||
Assert.That(model.Salary, Is.EqualTo(salary));
|
||||
Assert.That(model.IsActual, Is.EqualTo(isActual));
|
||||
Assert.That(model.ChangeDate, Is.EqualTo(changeDate));
|
||||
});
|
||||
}
|
||||
|
||||
private static PostDataModel CreateDataModel(string? id, string? postName, PostType postType, double salary, bool isActual, DateTime changeDate)
|
||||
=> new(id, postName, postType, salary, isActual, changeDate);
|
||||
private static PostDataModel CreateDataModel(string? id, string? postName, PostType postType, double salary)
|
||||
=> new(id, postName, postType, salary);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using FurnitureAssemblyContracts.DataModels;
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
|
||||
|
||||
namespace FurnitureAssemblyTests.DataModelsTests;
|
||||
|
||||
@@ -9,67 +10,67 @@ internal class WorkerDataModelTests
|
||||
[Test]
|
||||
public void IdIsNullOrEmptyTest()
|
||||
{
|
||||
var model = CreateDataModel(null, "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now, false);
|
||||
var model = CreateDataModel(null, "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now, false, new PostConfiguration() { Rate = 0 });
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
|
||||
model = CreateDataModel(string.Empty, "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now, false);
|
||||
model = CreateDataModel(string.Empty, "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now, false, new PostConfiguration() { Rate = 0 });
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void IdIsNotGuidTest()
|
||||
{
|
||||
var model = CreateDataModel("not a guid", "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now, false);
|
||||
var model = CreateDataModel("not a guid", "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now, false, new PostConfiguration() { Rate = 0 });
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FioIsNullOrEmptyTest()
|
||||
{
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), null, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now, false);
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), null, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now, false, new PostConfiguration() { Rate = 0 });
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
|
||||
model = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now, false);
|
||||
model = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now, false, new PostConfiguration() { Rate = 0 });
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FioIsNotCorrectTest()
|
||||
{
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now, false);
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now, false, new PostConfiguration() { Rate = 0 });
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PostIdIsNullOrEmptyTest()
|
||||
{
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", null, DateTime.Now.AddYears(-20), DateTime.Now, false);
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", null, DateTime.Now.AddYears(-20), DateTime.Now, false, new PostConfiguration() { Rate = 0 });
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
|
||||
model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", string.Empty, DateTime.Now.AddYears(-20), DateTime.Now, false);
|
||||
model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", string.Empty, DateTime.Now.AddYears(-20), DateTime.Now, false, new PostConfiguration() { Rate = 0 });
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PostIdIsNotGuidTest()
|
||||
{
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", "not a guid", DateTime.Now.AddYears(-20), DateTime.Now, false);
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", "not a guid", DateTime.Now.AddYears(-20), DateTime.Now, false, new PostConfiguration() { Rate = 0 });
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void BirthDateIsFutureTest()
|
||||
{
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-14).AddDays(1), DateTime.Now, false);
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-14).AddDays(1), DateTime.Now, false, new PostConfiguration() { Rate = 0 });
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void BirthDateAndEmploymentDateIsNotCorrectTest()
|
||||
{
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now.AddYears(-20).AddDays(-1), false);
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now.AddYears(-20).AddDays(-1), false, new PostConfiguration() { Rate = 0 });
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now.AddYears(-16), false);
|
||||
model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now.AddYears(-16), false, new PostConfiguration() { Rate = 0 });
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
@@ -82,7 +83,8 @@ internal class WorkerDataModelTests
|
||||
var birthDate = DateTime.Now.AddYears(-20);
|
||||
var employmentDate = DateTime.Now;
|
||||
var isDeleted = false;
|
||||
var model = CreateDataModel(id, fio, postId, birthDate, employmentDate, isDeleted);
|
||||
var configuration = new PostConfiguration() { Rate = 10 };
|
||||
var model = CreateDataModel(id, fio, postId, birthDate, employmentDate, isDeleted, configuration);
|
||||
Assert.That(() => model.Validate(), Throws.Nothing);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
@@ -92,9 +94,11 @@ internal class WorkerDataModelTests
|
||||
Assert.That(model.BirthDate, Is.EqualTo(birthDate));
|
||||
Assert.That(model.EmploymentDate, Is.EqualTo(employmentDate));
|
||||
Assert.That(model.IsDeleted, Is.EqualTo(isDeleted));
|
||||
Assert.That(model.ConfigurationModel, Is.EqualTo(configuration));
|
||||
Assert.That(model.ConfigurationModel.Rate, Is.EqualTo(configuration.Rate));
|
||||
});
|
||||
}
|
||||
|
||||
private static WorkerDataModel CreateDataModel(string? id, string? fio, string? postId, DateTime birthDate, DateTime employmentDate, bool isDeleted)
|
||||
=> new(id, fio, postId, birthDate, employmentDate, isDeleted);
|
||||
private static WorkerDataModel CreateDataModel(string? id, string? fio, string? postId, DateTime birthDate, DateTime employmentDate, bool isDeleted, PostConfiguration configuration)
|
||||
=> new(id, fio, postId, birthDate, employmentDate, isDeleted, configuration);
|
||||
}
|
||||
|
||||
@@ -8,8 +8,17 @@
|
||||
<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.2" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="9.0.3" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
|
||||
<PackageReference Include="Moq" Version="4.20.72" />
|
||||
<PackageReference Include="NUnit" Version="4.2.2" />
|
||||
@@ -21,6 +30,7 @@
|
||||
<ProjectReference Include="..\FurnitureAssemblyBusinessLogic\FurnitureAssemblyBusinessLogic.csproj" />
|
||||
<ProjectReference Include="..\FurnitureAssemblyContracts\FurnitureAssemblyContracts.csproj" />
|
||||
<ProjectReference Include="..\FurnitureAssemblyDatebase\FurnitureAssemblyDatebase.csproj" />
|
||||
<ProjectReference Include="..\FurnitureAssemblyWebApi\FurnitureAssemblyWebApi.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
using FurnitureAssemblyContracts.Infrastructure;
|
||||
|
||||
namespace FurnitureAssemblyTests.Infrastructure;
|
||||
|
||||
class ConfigurationSalaryTest : IConfigurationSalary
|
||||
{
|
||||
public double ExtraMadeSum => 10;
|
||||
|
||||
public int MaxConcurrentThreads => 4;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using FurnitureAssemblyContracts.Infrastructure;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace FurnitureAssemblyTests.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, ConfigurationDateBaseTest>();
|
||||
});
|
||||
builder.UseEnvironment("Development");
|
||||
base.ConfigureWebHost(builder);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
using FurnitureAssemblyContracts.Enums;
|
||||
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
|
||||
using FurnitureAssemblyDatebase;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
|
||||
namespace FurnitureAssemblyTests.Infrastructure;
|
||||
|
||||
internal static class FurnitureAssemblyDbContextExtensions
|
||||
{
|
||||
public static Post InsertPostToDatabaseAndReturn(this FurnitureAssemblyDbContext dbContext, string? id = null, string postName = "test", PostType postType = PostType.Builder, double salary = 10, bool isActual = true, DateTime? changeDate = null)
|
||||
{
|
||||
var post = new Post() { Id = Guid.NewGuid().ToString(), PostId = id ?? Guid.NewGuid().ToString(), PostName = postName, PostType = postType, Salary = salary, IsActual = isActual, ChangeDate = changeDate ?? DateTime.UtcNow };
|
||||
dbContext.Posts.Add(post);
|
||||
dbContext.SaveChanges();
|
||||
return post;
|
||||
}
|
||||
|
||||
public static Worker InsertWorkerToDatabaseAndReturn(this FurnitureAssemblyDbContext dbContext, string? id = null, string fio = "Иванов И.И.", string? postId = null, PostConfiguration? config = null, 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(), Configuration = config ?? new PostConfiguration() { Rate = 100 }, BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-20), EmploymentDate = employmentDate ?? DateTime.UtcNow, IsDeleted = isDeleted, DateOfDelete = dateDelete };
|
||||
dbContext.Workers.Add(worker);
|
||||
dbContext.SaveChanges();
|
||||
return worker;
|
||||
}
|
||||
|
||||
public static Component InsertComponentToDatabaseAndReturn(this FurnitureAssemblyDbContext dbContext, string? id = null, string name = "test", ComponentType type = ComponentType.Panel, string? prevName = null, string? prevPrevName = null)
|
||||
{
|
||||
var component = new Component() { Id = id ?? Guid.NewGuid().ToString(), Name = name, Type = type, PrevName = prevName, PrevPrevName = prevPrevName};
|
||||
dbContext.Components.Add(component);
|
||||
dbContext.SaveChanges();
|
||||
return component;
|
||||
}
|
||||
|
||||
public static Furniture InsertFurnitureToDatabaseAndReturn(this FurnitureAssemblyDbContext dbContext, string? id = null, string? name = "test", int weight = 5, List<(string, int)>? components = null)
|
||||
{
|
||||
var furniture = new Furniture() { Id = id ?? Guid.NewGuid().ToString(), Name = name!, Weight = weight, Components = [] };
|
||||
if (components is not null)
|
||||
{
|
||||
foreach (var elem in components)
|
||||
{
|
||||
furniture.Components.Add(new FurnitureComponent { FurnitureId = furniture.Id, ComponentId = elem.Item1, Count = elem.Item2 });
|
||||
}
|
||||
}
|
||||
dbContext.Furnitures.Add(furniture);
|
||||
dbContext.SaveChanges();
|
||||
return furniture;
|
||||
}
|
||||
public static ManifacturingFurniture InsertManifacturingToDatabaseAndReturn(this FurnitureAssemblyDbContext dbContext, string workerId, string furnitureId, string? id = null, int count = 5)
|
||||
{
|
||||
var manifacturing = new ManifacturingFurniture() { Id = id ?? Guid.NewGuid().ToString(), WorkerId = workerId, FurnitureId = furnitureId, Count = count, ProductuionDate = DateTime.UtcNow };
|
||||
dbContext.Manufacturing.Add(manifacturing);
|
||||
dbContext.SaveChanges();
|
||||
return manifacturing;
|
||||
}
|
||||
public static Salary InsertSalaryToDatabaseAndReturn(this FurnitureAssemblyDbContext 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 Post? GetPostFromDatabaseByPostId(this FurnitureAssemblyDbContext dbContext, string id) => dbContext.Posts.FirstOrDefault(x => x.PostId == id && x.IsActual);
|
||||
public static Post[] GetPostsFromDatabaseByPostId(this FurnitureAssemblyDbContext dbContext, string id) => [.. dbContext.Posts.Where(x => x.PostId == id).OrderByDescending(x => x.ChangeDate)];
|
||||
public static Worker? GetWorkerFromDatabaseById(this FurnitureAssemblyDbContext dbContext, string id) => dbContext.Workers.FirstOrDefault(x => x.Id == id);
|
||||
public static Component? GetComponentFromDatabaseById(this FurnitureAssemblyDbContext dbContext, string id) => dbContext.Components.FirstOrDefault(x => x.Id == id);
|
||||
public static Furniture? GetFurnitureFromDatabaseById(this FurnitureAssemblyDbContext dbContext, string id) => dbContext.Furnitures.FirstOrDefault(x => x.Id == id);
|
||||
public static ManifacturingFurniture? GetManifacturingFromDatabaseById(this FurnitureAssemblyDbContext dbContext, string id) => dbContext.Manufacturing.FirstOrDefault(x => x.Id == id);
|
||||
public static Salary[] GetSalariesFromDatabaseByWorkerId(this FurnitureAssemblyDbContext dbContext, string id) => [.. dbContext.Salaries.Where(x => x.WorkerId == id)];
|
||||
|
||||
public static void RemovePostsFromDatabase(this FurnitureAssemblyDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Posts\" CASCADE;");
|
||||
public static void RemoveWorkersFromDatabase(this FurnitureAssemblyDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Workers\" CASCADE;");
|
||||
public static void RemoveComponentsFromDatabase(this FurnitureAssemblyDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Components\" CASCADE;");
|
||||
public static void RemoveFurnituresFromDatabase(this FurnitureAssemblyDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Furnitures\" CASCADE;");
|
||||
public static void RemoveManifacturingFromDatabase(this FurnitureAssemblyDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Manufacturing\" CASCADE;");
|
||||
public static void RemoveSalariesFromDatabase(this FurnitureAssemblyDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Salaries\" CASCADE;");
|
||||
|
||||
private static void ExecuteSqlRaw(this FurnitureAssemblyDbContext dbContext, string command) => dbContext.Database.ExecuteSqlRaw(command);
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
using Castle.Components.DictionaryAdapter.Xml;
|
||||
using FurnitureAssemblyContracts.DataModels;
|
||||
using FurnitureAssemblyContracts.DataModels;
|
||||
using FurnitureAssemblyContracts.Enums;
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using FurnitureAssemblyDatebase.Implementations;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using FurnitureAssemblyTests.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace FurnitureAssemblyTests.StorageContractTests;
|
||||
@@ -23,15 +23,14 @@ internal class ComponentStorageContractTests : BaseStorageContractTest
|
||||
public void TearDown()
|
||||
{
|
||||
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Components\" CASCADE; ");
|
||||
//FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE\"Manufacturers\" CASCADE;");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var component = InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), "Component 1");
|
||||
InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), "Component 2");
|
||||
InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), "Component 3");
|
||||
var component = FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), "Component 1");
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), "Component 2");
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(name: "Component 3");
|
||||
var list = _componentStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
@@ -49,35 +48,35 @@ internal class ComponentStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var component = InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var component = FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn();
|
||||
AssertElement(_componentStorageContract.GetElementById(component.Id), component);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn();
|
||||
Assert.That(() => _componentStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenHaveRecord_Test()
|
||||
{
|
||||
var component = InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), "Unique Name");
|
||||
var component = FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn();
|
||||
AssertElement(_componentStorageContract.GetElementByName(component.Name), component);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenNoRecord_Test()
|
||||
{
|
||||
InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn();
|
||||
Assert.That(() => _componentStorageContract.GetElementByName("Non-existent Name"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByOldName_WhenHaveRecord_Test()
|
||||
{
|
||||
var component = InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), "Current Name", ComponentType.Panel, "Previous Name", "Old Name");
|
||||
var component = FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(name: "Current Name", prevName: "Previous Name", prevPrevName: "Old Name");
|
||||
AssertElement(_componentStorageContract.GetElementByOldName(component.PrevName!), component);
|
||||
AssertElement(_componentStorageContract.GetElementByOldName(component.PrevPrevName!), component);
|
||||
}
|
||||
@@ -85,7 +84,7 @@ internal class ComponentStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetElementByOldName_WhenNoRecord_Test()
|
||||
{
|
||||
InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn();
|
||||
Assert.That(() => _componentStorageContract.GetElementByOldName("Non-existent Old Name"), Is.Null);
|
||||
}
|
||||
|
||||
@@ -94,14 +93,14 @@ internal class ComponentStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
var component = CreateModel(Guid.NewGuid().ToString(), "New Component");
|
||||
_componentStorageContract.AddElement(component);
|
||||
AssertElement(GetComponentFromDatabase(component.Id), component);
|
||||
AssertElement(FurnitureAssemblyDbContext.GetComponentFromDatabaseById(component.Id), component);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
|
||||
{
|
||||
var component = CreateModel(Guid.NewGuid().ToString(), "Unique Name");
|
||||
InsertComponentToDatabaseAndReturn(component.Id);
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(component.Id);
|
||||
Assert.That(() => _componentStorageContract.AddElement(component), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
@@ -109,7 +108,7 @@ internal class ComponentStorageContractTests : BaseStorageContractTest
|
||||
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var component = CreateModel(Guid.NewGuid().ToString(), "Duplicate Name");
|
||||
InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), component.Name);
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), component.Name);
|
||||
Assert.That(() => _componentStorageContract.AddElement(component), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
@@ -117,9 +116,9 @@ internal class ComponentStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var component = CreateModel(Guid.NewGuid().ToString(), "Old Name", ComponentType.Panel, "Previous Name", "Old Name");
|
||||
InsertComponentToDatabaseAndReturn(component.Id, name: component.Name!, type: component.Type!, prevName: component.PrevName!, prevPrevName: component.PrevPrevName!);
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(component.Id, name: component.Name!, type: component.Type!, prevName: component.PrevName!, prevPrevName: component.PrevPrevName!);
|
||||
_componentStorageContract.UpdElement(component);
|
||||
AssertElement(GetComponentFromDatabase(component.Id), component);
|
||||
AssertElement(FurnitureAssemblyDbContext.GetComponentFromDatabaseById(component.Id), component);
|
||||
|
||||
}
|
||||
|
||||
@@ -127,9 +126,9 @@ internal class ComponentStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_WhenNoChangeName_Test()
|
||||
{
|
||||
var component = CreateModel(Guid.NewGuid().ToString(), "Same Name", ComponentType.Panel, "Previous Name", "Old Name");
|
||||
InsertComponentToDatabaseAndReturn(component.Id, component.Name, component.Type, component.PrevName, component.PrevPrevName);
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(component.Id, component.Name, component.Type, component.PrevName, component.PrevPrevName);
|
||||
_componentStorageContract.UpdElement(component);
|
||||
AssertElement(GetComponentFromDatabase(component.Id), component);
|
||||
AssertElement(FurnitureAssemblyDbContext.GetComponentFromDatabaseById(component.Id), component);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -142,17 +141,17 @@ internal class ComponentStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var component = CreateModel(Guid.NewGuid().ToString(), "Duplicate Name");
|
||||
InsertComponentToDatabaseAndReturn(component.Id, "Old Name");
|
||||
InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), component.Name);
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(component.Id, "Old Name");
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(name: component.Name);
|
||||
Assert.That(() => _componentStorageContract.UpdElement(component), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var component = InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var component = FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn();
|
||||
_componentStorageContract.DelElement(component.Id);
|
||||
var element = GetComponentFromDatabase(component.Id);
|
||||
var element = FurnitureAssemblyDbContext.GetComponentFromDatabaseById(component.Id);
|
||||
Assert.That(element, Is.Null);
|
||||
}
|
||||
|
||||
@@ -162,14 +161,6 @@ internal class ComponentStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(() => _componentStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private Component InsertComponentToDatabaseAndReturn(string id, string name = "test", ComponentType type = ComponentType.Panel, string prevName = "prevname", string prevPrevName = "prevprevname")
|
||||
{
|
||||
var component = new Component { Id = id, Name = name, Type = type, PrevName = prevName, PrevPrevName = prevPrevName };
|
||||
FurnitureAssemblyDbContext.Components.Add(component);
|
||||
FurnitureAssemblyDbContext.SaveChanges();
|
||||
return component;
|
||||
}
|
||||
|
||||
private static void AssertElement(ComponentDataModel? actual, Component expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
@@ -186,8 +177,6 @@ internal class ComponentStorageContractTests : BaseStorageContractTest
|
||||
private static ComponentDataModel CreateModel(string id, string name = "test", ComponentType type = ComponentType.Panel, string prevName = "prevname", string prevPrevName = "prevprevname")
|
||||
=> new(id, name, type, prevName, prevPrevName);
|
||||
|
||||
private Component? GetComponentFromDatabase(string id) => FurnitureAssemblyDbContext.Components.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
private static void AssertElement(Component? actual, ComponentDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using FurnitureAssemblyDatebase;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using FurnitureAssemblyTests.Infrastructure;
|
||||
|
||||
namespace FurnitureAssemblyTests.StorageContractTests;
|
||||
|
||||
@@ -20,15 +20,15 @@ internal class FurnitureStorageContractTests : BaseStorageContractTest
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Furnitures\" CASCADE;");
|
||||
FurnitureAssemblyDbContext.RemoveFurnituresFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var furniture = InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString(), "Furniture 1");
|
||||
InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString(), "Furniture 2");
|
||||
InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString(), "Furniture 3");
|
||||
var furniture = FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(name: "Furniture 1");
|
||||
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(name: "Furniture 2");
|
||||
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(name: "Furniture 3");
|
||||
var list = _furnitureStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
@@ -46,29 +46,29 @@ internal class FurnitureStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var furniture = InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var furniture = FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn();
|
||||
AssertElement(_furnitureStorageContract.GetElementById(furniture.Id), furniture);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
Assert.That(() => _furnitureStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn();
|
||||
Assert.That(() => FurnitureAssemblyDbContext.GetFurnitureFromDatabaseById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenHaveRecord_Test()
|
||||
{
|
||||
var furniture = InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString(), "Unique Name");
|
||||
var furniture = FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(name: "Unique Name");
|
||||
AssertElement(_furnitureStorageContract.GetElementByName(furniture.Name), furniture);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenNoRecord_Test()
|
||||
{
|
||||
InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
Assert.That(() => _furnitureStorageContract.GetElementByName("Non-existent Name"), Is.Null);
|
||||
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn();
|
||||
Assert.That(() => FurnitureAssemblyDbContext.GetFurnitureFromDatabaseById("Non-existent Name"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -76,14 +76,14 @@ internal class FurnitureStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
var furniture = CreateModel(Guid.NewGuid().ToString(), "New Furniture");
|
||||
_furnitureStorageContract.AddElement(furniture);
|
||||
AssertElement(GetFurnitureFromDatabase(furniture.Id), furniture);
|
||||
AssertElement(FurnitureAssemblyDbContext.GetFurnitureFromDatabaseById(furniture.Id), furniture);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
|
||||
{
|
||||
var furniture = CreateModel(Guid.NewGuid().ToString(), "Unique Name");
|
||||
InsertFurnitureToDatabaseAndReturn(furniture.Id);
|
||||
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(furniture.Id);
|
||||
Assert.That(() => _furnitureStorageContract.AddElement(furniture), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
@@ -91,7 +91,7 @@ internal class FurnitureStorageContractTests : BaseStorageContractTest
|
||||
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var furniture = CreateModel(Guid.NewGuid().ToString(), "Duplicate Name");
|
||||
InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString(), furniture.Name);
|
||||
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString(), furniture.Name);
|
||||
Assert.That(() => _furnitureStorageContract.AddElement(furniture), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
@@ -99,18 +99,18 @@ internal class FurnitureStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var furniture = CreateModel(Guid.NewGuid().ToString(), "Old Name");
|
||||
InsertFurnitureToDatabaseAndReturn(furniture.Id, name: furniture.Name!);
|
||||
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(furniture.Id, name: furniture.Name!);
|
||||
_furnitureStorageContract.UpdElement(furniture);
|
||||
AssertElement(GetFurnitureFromDatabase(furniture.Id), furniture);
|
||||
AssertElement(FurnitureAssemblyDbContext.GetFurnitureFromDatabaseById(furniture.Id), furniture);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenNoChangeName_Test()
|
||||
{
|
||||
var furniture = CreateModel(Guid.NewGuid().ToString(), "Same Name");
|
||||
InsertFurnitureToDatabaseAndReturn(furniture.Id, furniture.Name);
|
||||
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(furniture.Id, furniture.Name);
|
||||
_furnitureStorageContract.UpdElement(furniture);
|
||||
AssertElement(GetFurnitureFromDatabase(furniture.Id), furniture);
|
||||
AssertElement(FurnitureAssemblyDbContext.GetFurnitureFromDatabaseById(furniture.Id), furniture);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -123,17 +123,17 @@ internal class FurnitureStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var furniture = CreateModel(Guid.NewGuid().ToString(), "Duplicate Name");
|
||||
InsertFurnitureToDatabaseAndReturn(furniture.Id, "Old Name");
|
||||
InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString(), furniture.Name);
|
||||
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(furniture.Id, "Old Name");
|
||||
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString(), furniture.Name);
|
||||
Assert.That(() => _furnitureStorageContract.UpdElement(furniture), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var furniture = InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var furniture = FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
_furnitureStorageContract.DelElement(furniture.Id);
|
||||
var element = GetFurnitureFromDatabase(furniture.Id);
|
||||
var element = FurnitureAssemblyDbContext.GetFurnitureFromDatabaseById(furniture.Id);
|
||||
Assert.That(element, Is.Null);
|
||||
}
|
||||
|
||||
@@ -143,14 +143,6 @@ internal class FurnitureStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(() => _furnitureStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private Furniture InsertFurnitureToDatabaseAndReturn(string id, string name = "test")
|
||||
{
|
||||
var furniture = new Furniture { Id = id, Name = name };
|
||||
FurnitureAssemblyDbContext.Furnitures.Add(furniture);
|
||||
FurnitureAssemblyDbContext.SaveChanges();
|
||||
return furniture;
|
||||
}
|
||||
|
||||
private static void AssertElement(FurnitureDataModel? actual, Furniture expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
@@ -164,8 +156,6 @@ internal class FurnitureStorageContractTests : BaseStorageContractTest
|
||||
private static FurnitureDataModel CreateModel(string id, string name = "test", int weight = 0)
|
||||
=> new(id, name, weight, []);
|
||||
|
||||
private Furniture? GetFurnitureFromDatabase(string id) => FurnitureAssemblyDbContext.Furnitures.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
private static void AssertElement(Furniture? actual, FurnitureDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using FurnitureAssemblyDatebase.Implementations;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using FurnitureAssemblyTests.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace FurnitureAssemblyTests.StorageContractTests;
|
||||
@@ -17,24 +18,24 @@ internal class ManifacturingStorageContractTests : BaseStorageContractTest
|
||||
public void SetUp()
|
||||
{
|
||||
_manifacturingStorageContract = new ManifacturingStorageContract(FurnitureAssemblyDbContext);
|
||||
_worker = InsertWorkerToDatabaseAndReturn();
|
||||
_furniture = InsertFurnitureToDatabaseAndReturn();
|
||||
_worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
_furniture = FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn();
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Furnitures\" CASCADE;");
|
||||
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Manufacturing\" CASCADE;");
|
||||
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Workers\" CASCADE;");
|
||||
FurnitureAssemblyDbContext.RemoveComponentsFromDatabase();
|
||||
FurnitureAssemblyDbContext.RemoveFurnituresFromDatabase();
|
||||
FurnitureAssemblyDbContext.RemoveWorkersFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var manufacturing = InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
|
||||
InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
|
||||
InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
|
||||
var manufacturing = FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, _furniture.Id);
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, _furniture.Id);
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, _furniture.Id);
|
||||
var list = _manifacturingStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
@@ -52,10 +53,9 @@ internal class ManifacturingStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByWorker_Test()
|
||||
{
|
||||
var worker = InsertWorkerToDatabaseAndReturn("Other worker");
|
||||
InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
|
||||
InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
|
||||
InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, worker.Id);
|
||||
var worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "Other worker");
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, _furniture.Id);
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, _furniture.Id);
|
||||
var list = _manifacturingStorageContract.GetList(workerId: _worker.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
@@ -65,10 +65,10 @@ internal class ManifacturingStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByFurniture_Test()
|
||||
{
|
||||
var furniture = InsertFurnitureToDatabaseAndReturn("Other furniture");
|
||||
InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
|
||||
InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
|
||||
InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), furniture.Id, 5, _worker.Id);
|
||||
var furniture = FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(name: "Other furniture");
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, _furniture.Id);
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, _furniture.Id);
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, furniture.Id);
|
||||
var list = _manifacturingStorageContract.GetList(furnitureId: _furniture.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
@@ -78,14 +78,14 @@ internal class ManifacturingStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var manufacturing = InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
|
||||
var manufacturing = FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, _furniture.Id);
|
||||
AssertElement(_manifacturingStorageContract.GetElementById(manufacturing.Id), manufacturing);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
InsertManufacturingToDatabaseAndReturn(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, _furniture.Id);
|
||||
Assert.That(() => _manifacturingStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
@@ -94,14 +94,14 @@ internal class ManifacturingStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
var manufacturing = CreateModel(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
|
||||
_manifacturingStorageContract.AddElement(manufacturing);
|
||||
AssertElement(GetManufacturingFromDatabaseById(manufacturing.Id), manufacturing);
|
||||
AssertElement(FurnitureAssemblyDbContext.GetManifacturingFromDatabaseById(manufacturing.Id), manufacturing);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
|
||||
{
|
||||
var manufacturing = CreateModel(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
|
||||
InsertManufacturingToDatabaseAndReturn(manufacturing.Id, _furniture.Id, 5, _worker.Id);
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, _furniture.Id, id: manufacturing.Id);
|
||||
Assert.That(() => _manifacturingStorageContract.AddElement(manufacturing), Throws.TypeOf<StorageException>());
|
||||
}
|
||||
|
||||
@@ -109,9 +109,9 @@ internal class ManifacturingStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var manufacturing = CreateModel(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
|
||||
InsertManufacturingToDatabaseAndReturn(manufacturing.Id, _furniture.Id, 5, _worker.Id);
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, _furniture.Id, id: manufacturing.Id);
|
||||
_manifacturingStorageContract.UpdElement(manufacturing);
|
||||
AssertElement(GetManufacturingFromDatabaseById(manufacturing.Id), manufacturing);
|
||||
AssertElement(FurnitureAssemblyDbContext.GetManifacturingFromDatabaseById(manufacturing.Id), manufacturing);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -120,30 +120,6 @@ internal class ManifacturingStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(() => _manifacturingStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id)), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private Worker InsertWorkerToDatabaseAndReturn(string workerFIO = "fio")
|
||||
{
|
||||
var worker = new Worker() { Id = Guid.NewGuid().ToString(), PostId = Guid.NewGuid().ToString(), FIO = workerFIO, IsDeleted = false };
|
||||
FurnitureAssemblyDbContext.Workers.Add(worker);
|
||||
FurnitureAssemblyDbContext.SaveChanges();
|
||||
return worker;
|
||||
}
|
||||
|
||||
private Furniture InsertFurnitureToDatabaseAndReturn(string furnitureName = "furniture", int weight = 5)
|
||||
{
|
||||
var furniture = new Furniture() { Id = Guid.NewGuid().ToString(), Name = furnitureName, Weight = weight };
|
||||
FurnitureAssemblyDbContext.Furnitures.Add(furniture);
|
||||
FurnitureAssemblyDbContext.SaveChanges();
|
||||
return furniture;
|
||||
}
|
||||
|
||||
private ManifacturingFurniture InsertManufacturingToDatabaseAndReturn(string id, string furnitureId, int count, string workerId)
|
||||
{
|
||||
var manufacturing = new ManifacturingFurniture() { Id = id, FurnitureId = furnitureId, Count = count, WorkerId = workerId };
|
||||
FurnitureAssemblyDbContext.Manufacturing.Add(manufacturing);
|
||||
FurnitureAssemblyDbContext.SaveChanges();
|
||||
return manufacturing;
|
||||
}
|
||||
|
||||
private static void AssertElement(ManifacturingFurnitureDataModel? actual, ManifacturingFurniture expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
@@ -161,9 +137,6 @@ internal class ManifacturingStorageContractTests : BaseStorageContractTest
|
||||
return new(id, furnitureId, count, workerId);
|
||||
}
|
||||
|
||||
private ManifacturingFurniture? GetManufacturingFromDatabaseById(string id) =>
|
||||
FurnitureAssemblyDbContext.Manufacturing.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
private static void AssertElement(ManifacturingFurniture? actual, ManifacturingFurnitureDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
|
||||
@@ -3,7 +3,7 @@ using FurnitureAssemblyContracts.Enums;
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using FurnitureAssemblyDatebase.Implementations;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using FurnitureAssemblyTests.Infrastructure;
|
||||
|
||||
namespace FurnitureAssemblyTests.StorageContractTests;
|
||||
|
||||
@@ -21,16 +21,15 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Posts\"CASCADE; ");
|
||||
FurnitureAssemblyDbContext.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 = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postName: "name 1");
|
||||
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postName: "name 2");
|
||||
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postName: "name 3");
|
||||
var list = _postStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
@@ -45,44 +44,13 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_OnlyActual_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);
|
||||
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));
|
||||
});
|
||||
}
|
||||
|
||||
[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);
|
||||
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
|
||||
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
|
||||
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
|
||||
var list = _postStorageContract.GetPostWithHistory(postId);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
@@ -92,9 +60,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);
|
||||
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
|
||||
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
|
||||
FurnitureAssemblyDbContext.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));
|
||||
@@ -103,148 +71,118 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn();
|
||||
AssertElement(_postStorageContract.GetElementById(post.PostId), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn();
|
||||
Assert.That(() => _postStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenRecordHasDeleted_Test()
|
||||
public void Try_GetElementById_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
|
||||
var post = FurnitureAssemblyDbContext.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 = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn();
|
||||
Assert.That(() => _postStorageContract.GetElementById(post.Id), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenHaveRecord_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
AssertElement(_postStorageContract.GetElementByName(post.PostName),
|
||||
post);
|
||||
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn();
|
||||
AssertElement(_postStorageContract.GetElementByName(post.PostName), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenNoRecord_Test()
|
||||
{
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn();
|
||||
Assert.That(() => _postStorageContract.GetElementByName("name"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenRecordHasDeleted_Test()
|
||||
public void Try_GetElementByName_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
|
||||
var post = FurnitureAssemblyDbContext.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(FurnitureAssemblyDbContext.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);
|
||||
Assert.That(() => _postStorageContract.AddElement(post),
|
||||
Throws.TypeOf<ElementExistsException>());
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), "name unique");
|
||||
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postName: post.PostName, isActual: true);
|
||||
Assert.That(() => _postStorageContract.AddElement(post), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void
|
||||
Try_AddElement_WhenHaveRecordWithSamePostIdAndActualIsTrue_Test()
|
||||
public void Try_AddElement_WhenHaveRecordWithSamePostId_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), isActual: true);
|
||||
InsertPostToDatabaseAndReturn(post.Id, isActual: true);
|
||||
Assert.That(() => _postStorageContract.AddElement(post),
|
||||
Throws.TypeOf<ElementExistsException>());
|
||||
var post = CreateModel(Guid.NewGuid().ToString());
|
||||
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: true);
|
||||
Assert.That(() => _postStorageContract.AddElement(post), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertPostToDatabaseAndReturn(post.Id, isActual: true);
|
||||
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: true);
|
||||
_postStorageContract.UpdElement(post);
|
||||
var posts = FurnitureAssemblyDbContext.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 = FurnitureAssemblyDbContext.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]
|
||||
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _postStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())),
|
||||
Throws.TypeOf<ElementNotFoundException>());
|
||||
Assert.That(() => _postStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
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);
|
||||
Assert.That(() => _postStorageContract.UpdElement(post),
|
||||
Throws.TypeOf<ElementExistsException>());
|
||||
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(post.Id, postName: "name");
|
||||
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postName: post.PostName);
|
||||
Assert.That(() => _postStorageContract.UpdElement(post), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertPostToDatabaseAndReturn(post.Id, isActual: false);
|
||||
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: false);
|
||||
Assert.That(() => _postStorageContract.UpdElement(post), Throws.TypeOf<ElementDeletedException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: true);
|
||||
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(isActual: true);
|
||||
_postStorageContract.DelElement(post.PostId);
|
||||
var element = GetPostFromDatabaseByPostId(post.PostId);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.That(!element!.IsActual);
|
||||
});
|
||||
Assert.That(FurnitureAssemblyDbContext.GetPostFromDatabaseByPostId(post.PostId), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -256,16 +194,16 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_DelElement_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
|
||||
var post = FurnitureAssemblyDbContext.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 = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
_postStorageContract.ResElement(post.PostId);
|
||||
var element = GetPostFromDatabaseByPostId(post.PostId);
|
||||
var element = FurnitureAssemblyDbContext.GetPostFromDatabaseByPostId(post.PostId);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element, Is.Not.Null);
|
||||
@@ -276,51 +214,30 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_ResElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _postStorageContract.ResElement(Guid.NewGuid().ToString()),
|
||||
Throws.TypeOf<ElementNotFoundException>());
|
||||
Assert.That(() => _postStorageContract.ResElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_ResElement_WhenRecordNotWasDeleted_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: true);
|
||||
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(isActual: true);
|
||||
Assert.That(() => _postStorageContract.ResElement(post.PostId), Throws.Nothing);
|
||||
}
|
||||
|
||||
private Post InsertPostToDatabaseAndReturn(string id, string postName = "test", PostType postType = PostType.Builder, 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
|
||||
};
|
||||
FurnitureAssemblyDbContext.Posts.Add(post);
|
||||
FurnitureAssemblyDbContext.SaveChanges();
|
||||
return post;
|
||||
}
|
||||
|
||||
private static void AssertElement(PostDataModel? actual, Post expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.PostId));
|
||||
Assert.That(actual.PostName, Is.EqualTo(expected.PostName)); Assert.That(actual.PostType, Is.EqualTo(expected.PostType));
|
||||
Assert.That(actual.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));
|
||||
});
|
||||
}
|
||||
|
||||
private static PostDataModel CreateModel(string postId, string postName = "test", PostType postType = PostType.Builder, double salary = 10, bool isActual = false, DateTime? changeDate = null)
|
||||
=> new(postId, postName, postType, salary, isActual, changeDate ?? DateTime.UtcNow);
|
||||
|
||||
private Post? GetPostFromDatabaseByPostId(string id) => FurnitureAssemblyDbContext.Posts
|
||||
.Where(x => x.PostId == id).OrderByDescending(x => x.ChangeDate).FirstOrDefault();
|
||||
private static PostDataModel CreateModel(string postId, string postName = "test", PostType postType = PostType.Builder, double salary = 10)
|
||||
=> new(postId, postName, postType, salary);
|
||||
|
||||
private static void AssertElement(Post? actual, PostDataModel expected)
|
||||
{
|
||||
@@ -331,7 +248,6 @@ internal class PostStorageContractTests : BaseStorageContractTest
|
||||
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));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
using FurnitureAssemblyDatebase;
|
||||
using FurnitureAssemblyDatebase.Implementations;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using FurnitureAssemblyTests.Infrastructure;
|
||||
|
||||
namespace FurnitureAssemblyTests.StorageContractTests;
|
||||
|
||||
@@ -16,26 +16,26 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
|
||||
public void SetUp()
|
||||
{
|
||||
_salaryStorageContract = new SalaryStorageContract(FurnitureAssemblyDbContext);
|
||||
_worker = InsertWorkerToDatabaseAndReturn();
|
||||
_worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Salaries\"CASCADE; ");
|
||||
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Workers\"CASCADE; ");
|
||||
FurnitureAssemblyDbContext.RemoveWorkersFromDatabase();
|
||||
FurnitureAssemblyDbContext.RemoveSalariesFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var salary = InsertSalaryToDatabaseAndReturn(_worker.Id, workerSalary: 100);
|
||||
InsertSalaryToDatabaseAndReturn(_worker.Id);
|
||||
InsertSalaryToDatabaseAndReturn(_worker.Id);
|
||||
var salary = FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, workerSalary: 100);
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id);
|
||||
FurnitureAssemblyDbContext.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]
|
||||
@@ -49,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));
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-5));
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(5));
|
||||
FurnitureAssemblyDbContext.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(() =>
|
||||
@@ -66,10 +66,10 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByWorker_Test()
|
||||
{
|
||||
var worker = InsertWorkerToDatabaseAndReturn("name 2");
|
||||
InsertSalaryToDatabaseAndReturn(_worker.Id);
|
||||
InsertSalaryToDatabaseAndReturn(_worker.Id);
|
||||
InsertSalaryToDatabaseAndReturn(worker.Id);
|
||||
var worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id);
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id);
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(worker.Id);
|
||||
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-
|
||||
1), DateTime.UtcNow.AddDays(1), _worker.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
@@ -83,18 +83,18 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByWorkerOnlyInDatePeriod_Test()
|
||||
{
|
||||
var worker = InsertWorkerToDatabaseAndReturn("name 2");
|
||||
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate:
|
||||
var worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn("name 2");
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate:
|
||||
DateTime.UtcNow.AddDays(-2));
|
||||
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate:
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate:
|
||||
DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate:
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate:
|
||||
DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate:
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate:
|
||||
DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate:
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate:
|
||||
DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate:
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate:
|
||||
DateTime.UtcNow.AddDays(-2));
|
||||
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-
|
||||
1), DateTime.UtcNow.AddDays(1), _worker.Id);
|
||||
@@ -111,35 +111,7 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
var salary = CreateModel(_worker.Id);
|
||||
_salaryStorageContract.AddElement(salary);
|
||||
AssertElement(GetSalaryFromDatabaseByWorkerId(_worker.Id), salary);
|
||||
}
|
||||
|
||||
private Worker InsertWorkerToDatabaseAndReturn(string workerFIO = "fio")
|
||||
{
|
||||
var worker = new Worker()
|
||||
{
|
||||
Id = Guid.NewGuid().ToString(),
|
||||
PostId = Guid.NewGuid().ToString(),
|
||||
FIO = workerFIO,
|
||||
IsDeleted = false
|
||||
};
|
||||
FurnitureAssemblyDbContext.Workers.Add(worker);
|
||||
FurnitureAssemblyDbContext.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
|
||||
};
|
||||
FurnitureAssemblyDbContext.Salaries.Add(salary);
|
||||
FurnitureAssemblyDbContext.SaveChanges();
|
||||
return salary;
|
||||
AssertElement(FurnitureAssemblyDbContext.GetSalariesFromDatabaseByWorkerId(_worker.Id).FirstOrDefault(), salary);
|
||||
}
|
||||
|
||||
private static void AssertElement(SalaryDataModel? actual, Salary expected)
|
||||
@@ -154,8 +126,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) => FurnitureAssemblyDbContext.Salaries.FirstOrDefault(x => x.WorkerId == id);
|
||||
|
||||
private static void AssertElement(Salary? actual, SalaryDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
using FurnitureAssemblyContracts.DataModels;
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
|
||||
using FurnitureAssemblyContracts.StoragesContracts;
|
||||
using FurnitureAssemblyDatebase.Implementations;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using FurnitureAssemblyTests.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace FurnitureAssemblyTests.StorageContractTests;
|
||||
@@ -20,19 +23,19 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Workers\"CASCADE; ");
|
||||
FurnitureAssemblyDbContext.RemoveWorkersFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1");
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2");
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3");
|
||||
var worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1");
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2");
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3");
|
||||
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,11 +50,9 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
public void Try_GetList_ByPostId_Test()
|
||||
{
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1",
|
||||
postId);
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2",
|
||||
postId);
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3");
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: postId);
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: postId);
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3");
|
||||
var list = _workerStorageContract.GetList(postId: postId);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
@@ -61,14 +62,10 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByBirthDate_Test()
|
||||
{
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1",
|
||||
birthDate: DateTime.UtcNow.AddYears(-25));
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2",
|
||||
birthDate: DateTime.UtcNow.AddYears(-21));
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3",
|
||||
birthDate: DateTime.UtcNow.AddYears(-20));
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4",
|
||||
birthDate: DateTime.UtcNow.AddYears(-19));
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", birthDate: DateTime.UtcNow.AddYears(-25));
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", birthDate: DateTime.UtcNow.AddYears(-21));
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", birthDate: DateTime.UtcNow.AddYears(-20));
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", birthDate: DateTime.UtcNow.AddYears(-19));
|
||||
var list = _workerStorageContract.GetList(fromBirthDate: DateTime.UtcNow.AddYears(-21).AddMinutes(-1), toBirthDate: DateTime.UtcNow.AddYears(-20).AddMinutes(1));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
@@ -77,14 +74,10 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_ByEmploymentDate_Test()
|
||||
{
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1",
|
||||
employmentDate: DateTime.UtcNow.AddDays(-2));
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2",
|
||||
employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3",
|
||||
employmentDate: DateTime.UtcNow.AddDays(1));
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4",
|
||||
employmentDate: DateTime.UtcNow.AddDays(2));
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", employmentDate: DateTime.UtcNow.AddDays(-2));
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", employmentDate: DateTime.UtcNow.AddDays(1));
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", employmentDate: DateTime.UtcNow.AddDays(2));
|
||||
var list = _workerStorageContract.GetList(fromEmploymentDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-1), toEmploymentDate: DateTime.UtcNow.AddDays(1).AddMinutes(1));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
@@ -94,13 +87,11 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
public void Try_GetList_ByAllParameters_Test()
|
||||
{
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", postId, birthDate: DateTime.UtcNow.AddYears(-25), employmentDate: DateTime.UtcNow.AddDays(-2));
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", postId, birthDate: DateTime.UtcNow.AddYears(-22), employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", postId, birthDate: DateTime.UtcNow.AddYears(-21), employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", birthDate: DateTime.UtcNow.AddYears(-20), employmentDate: DateTime.UtcNow.AddDays(1));
|
||||
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));
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: postId, birthDate: DateTime.UtcNow.AddYears(-25), employmentDate: DateTime.UtcNow.AddDays(-2));
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: postId, birthDate: DateTime.UtcNow.AddYears(-22), employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", postId: postId, birthDate: DateTime.UtcNow.AddYears(-21), employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", birthDate: DateTime.UtcNow.AddYears(-20), employmentDate: DateTime.UtcNow.AddDays(1));
|
||||
var list = _workerStorageContract.GetList(postId: postId, fromBirthDate: DateTime.UtcNow.AddYears(-21).AddMinutes(-1), toBirthDate: DateTime.UtcNow.AddYears(-20).AddMinutes(1), fromEmploymentDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-1), toEmploymentDate: DateTime.UtcNow.AddDays(1).AddMinutes(1));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(1));
|
||||
}
|
||||
@@ -108,7 +99,7 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
AssertElement(_workerStorageContract.GetElementById(worker.Id), worker);
|
||||
}
|
||||
|
||||
@@ -121,7 +112,7 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetElementByFIO_WhenHaveRecord_Test()
|
||||
{
|
||||
var worker = InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
AssertElement(_workerStorageContract.GetElementByFIO(worker.FIO), worker);
|
||||
}
|
||||
|
||||
@@ -136,14 +127,14 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString());
|
||||
_workerStorageContract.AddElement(worker);
|
||||
AssertElement(GetWorkerFromDatabase(worker.Id), worker);
|
||||
AssertElement(FurnitureAssemblyDbContext.GetWorkerFromDatabaseById(worker.Id), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertWorkerToDatabaseAndReturn(worker.Id);
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(worker.Id);
|
||||
Assert.That(() => _workerStorageContract.AddElement(worker), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
@@ -151,33 +142,31 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString(), "New Fio");
|
||||
InsertWorkerToDatabaseAndReturn(worker.Id);
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(worker.Id);
|
||||
_workerStorageContract.UpdElement(worker);
|
||||
AssertElement(GetWorkerFromDatabase(worker.Id), worker);
|
||||
AssertElement(FurnitureAssemblyDbContext.GetWorkerFromDatabaseById(worker.Id), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _workerStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())),
|
||||
Throws.TypeOf<ElementNotFoundException>());
|
||||
Assert.That(() => _workerStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenNoRecordWasDeleted_Test()
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertWorkerToDatabaseAndReturn(worker.Id, isDeleted: true);
|
||||
Assert.That(() => _workerStorageContract.UpdElement(worker),
|
||||
Throws.TypeOf<ElementNotFoundException>());
|
||||
FurnitureAssemblyDbContext.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 = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
_workerStorageContract.DelElement(worker.Id);
|
||||
var element = GetWorkerFromDatabase(worker.Id);
|
||||
var element = FurnitureAssemblyDbContext.GetWorkerFromDatabaseById(worker.Id);
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.That(element.IsDeleted);
|
||||
}
|
||||
@@ -185,33 +174,126 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_DelElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _workerStorageContract.DelElement(Guid.NewGuid().ToString()),
|
||||
Throws.TypeOf<ElementNotFoundException>());
|
||||
Assert.That(() => _workerStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenNoRecordWasDeleted_Test()
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertWorkerToDatabaseAndReturn(worker.Id, isDeleted: true);
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(worker.Id, isDeleted: true);
|
||||
Assert.That(() => _workerStorageContract.DelElement(worker.Id), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private Worker InsertWorkerToDatabaseAndReturn(string id, string fio = "test", string? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false)
|
||||
[Test]
|
||||
public void Try_GetList_WhenDifferentConfigTypes_Test()
|
||||
{
|
||||
var worker = new Worker()
|
||||
{
|
||||
Id = id,
|
||||
FIO = fio,
|
||||
PostId = postId ?? Guid.NewGuid().ToString(),
|
||||
BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-20),
|
||||
EmploymentDate = employmentDate ?? DateTime.UtcNow,
|
||||
IsDeleted = isDeleted
|
||||
};
|
||||
FurnitureAssemblyDbContext.Workers.Add(worker);
|
||||
FurnitureAssemblyDbContext.SaveChanges();
|
||||
return worker;
|
||||
var workerSimple = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
var workerBuilder = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(config: new BuilderPostConfiguration() { PersonalCount = 500 });
|
||||
var workerChief = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(config: new ChiefPostConfiguration() { PersonalCountTrendPremium = 20 });
|
||||
var list = _workerStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
AssertElement(list.First(x => x.Id == workerSimple.Id), workerSimple);
|
||||
AssertElement(list.First(x => x.Id == workerBuilder.Id), workerBuilder);
|
||||
AssertElement(list.First(x => x.Id == workerChief.Id), workerChief);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WithBuilderPostConfiguration_Test()
|
||||
{
|
||||
var personalCount = 500;
|
||||
var worker = CreateModel(Guid.NewGuid().ToString(), config: new BuilderPostConfiguration() { PersonalCount = 500 });
|
||||
_workerStorageContract.AddElement(worker);
|
||||
var element = FurnitureAssemblyDbContext.GetWorkerFromDatabaseById(worker.Id);
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(BuilderPostConfiguration).Name));
|
||||
Assert.That((element.Configuration as BuilderPostConfiguration)!.PersonalCount, Is.EqualTo(personalCount));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WithChiefPostConfiguration_Test()
|
||||
{
|
||||
var personalCountTrendPremium = 500;
|
||||
var worker = CreateModel(Guid.NewGuid().ToString(), config: new ChiefPostConfiguration() { PersonalCountTrendPremium = 500 });
|
||||
_workerStorageContract.AddElement(worker);
|
||||
var element = FurnitureAssemblyDbContext.GetWorkerFromDatabaseById(worker.Id);
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(ChiefPostConfiguration).Name));
|
||||
Assert.That((element.Configuration as ChiefPostConfiguration)!.PersonalCountTrendPremium, Is.EqualTo(personalCountTrendPremium));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WithBuilderPostConfiguration_Test()
|
||||
{
|
||||
var worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
var personalCount = 500;
|
||||
_workerStorageContract.UpdElement(CreateModel(worker.Id, config: new BuilderPostConfiguration() { PersonalCount = 500 }));
|
||||
var element = FurnitureAssemblyDbContext.GetWorkerFromDatabaseById(worker.Id);
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(BuilderPostConfiguration).Name));
|
||||
Assert.That((element.Configuration as BuilderPostConfiguration)!.PersonalCount, Is.EqualTo(personalCount));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WithChiefPostConfiguration_Test()
|
||||
{
|
||||
var worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
var personalCountTrendPremium = 500;
|
||||
_workerStorageContract.UpdElement(CreateModel(worker.Id, config: new ChiefPostConfiguration() { PersonalCountTrendPremium = 500 }));
|
||||
var element = FurnitureAssemblyDbContext.GetWorkerFromDatabaseById(worker.Id);
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(ChiefPostConfiguration).Name));
|
||||
Assert.That((element.Configuration as ChiefPostConfiguration)!.PersonalCountTrendPremium, Is.EqualTo(personalCountTrendPremium));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetWorkerTrend_WhenNoNewAndDeletedWorkers_Test()
|
||||
{
|
||||
var startDate = DateTime.UtcNow.AddDays(-5);
|
||||
var endDate = DateTime.UtcNow.AddDays(-3);
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-10));
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-10), isDeleted: true, dateDelete: DateTime.UtcNow.AddDays(-9));
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(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);
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-10));
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-4));
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(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);
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-10), isDeleted: true, dateDelete: DateTime.UtcNow.AddDays(-9));
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-10), isDeleted: true, dateDelete: DateTime.UtcNow.AddDays(-4));
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(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);
|
||||
@@ -221,15 +303,13 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(actual.PostId, Is.EqualTo(expected.PostId));
|
||||
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
|
||||
Assert.That(actual.BirthDate, Is.EqualTo(expected.BirthDate));
|
||||
Assert.That(actual.EmploymentDate,
|
||||
Is.EqualTo(expected.EmploymentDate));
|
||||
Assert.That(actual.EmploymentDate, Is.EqualTo(expected.EmploymentDate));
|
||||
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
|
||||
});
|
||||
}
|
||||
private static WorkerDataModel CreateModel(string id, string fio = "fio", string? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false) =>
|
||||
new(id, fio, postId ?? Guid.NewGuid().ToString(), birthDate ?? DateTime.UtcNow.AddYears(-20), employmentDate ?? DateTime.UtcNow, isDeleted);
|
||||
|
||||
private Worker? GetWorkerFromDatabase(string id) => FurnitureAssemblyDbContext.Workers.FirstOrDefault(x => x.Id == id);
|
||||
private static WorkerDataModel CreateModel(string id, string fio = "fio", string? postId = null, PostConfiguration? config = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false) =>
|
||||
new(id, fio, postId ?? Guid.NewGuid().ToString(), birthDate ?? DateTime.UtcNow.AddYears(-20), employmentDate ?? DateTime.UtcNow, isDeleted, config ?? new PostConfiguration() { Rate = 10 });
|
||||
|
||||
private static void AssertElement(Worker? actual, WorkerDataModel expected)
|
||||
{
|
||||
@@ -240,8 +320,10 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(actual.PostId, Is.EqualTo(expected.PostId));
|
||||
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
|
||||
Assert.That(actual.BirthDate, Is.EqualTo(expected.BirthDate));
|
||||
Assert.That(actual.EmploymentDate,Is.EqualTo(expected.EmploymentDate));
|
||||
Assert.That(actual.EmploymentDate, Is.EqualTo(expected.EmploymentDate));
|
||||
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
|
||||
Assert.That(actual.Configuration.Rate, Is.EqualTo(expected.ConfigurationModel.Rate));
|
||||
Assert.That(actual.DateOfDelete.HasValue, Is.EqualTo(expected.IsDeleted));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
using FurnitureAssemblyDatebase;
|
||||
using FurnitureAssemblyTests.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 FurnitureAssemblyTests.WebApiControllerTests;
|
||||
|
||||
internal class BaseWebApiControllerTest
|
||||
{
|
||||
private WebApplicationFactory<Program> _webApplication;
|
||||
|
||||
protected HttpClient HttpClient { get; private set; }
|
||||
|
||||
protected FurnitureAssemblyDbContext FurnitureAssemblyDbContext { 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}");
|
||||
|
||||
FurnitureAssemblyDbContext = _webApplication.Services.GetRequiredService<FurnitureAssemblyDbContext>();
|
||||
FurnitureAssemblyDbContext.Database.EnsureDeleted();
|
||||
FurnitureAssemblyDbContext.Database.EnsureCreated();
|
||||
}
|
||||
|
||||
[OneTimeTearDown]
|
||||
public void OneTimeTearDown()
|
||||
{
|
||||
FurnitureAssemblyDbContext?.Database.EnsureDeleted();
|
||||
FurnitureAssemblyDbContext?.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,305 @@
|
||||
using FurnitureAssemblyContracts.BindingModels;
|
||||
using FurnitureAssemblyContracts.Enums;
|
||||
using FurnitureAssemblyContracts.ViewModels;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using FurnitureAssemblyTests.Infrastructure;
|
||||
using System.Net;
|
||||
|
||||
namespace FurnitureAssemblyTests.WebApiControllerTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class ComponentControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
FurnitureAssemblyDbContext.RemoveComponentsFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetAllComponents_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
// Arrange
|
||||
var component = FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(name: "Component1");
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(name: "Component2");
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(name: "Component3");
|
||||
// Act
|
||||
var response = await HttpClient.GetAsync("/api/components");
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ComponentViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
});
|
||||
AssertElement(data.First(x => x.Id == component.Id), component);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetAllComponents_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
// Act
|
||||
var response = await HttpClient.GetAsync("/api/components");
|
||||
var data = await GetModelFromResponseAsync<List<ComponentViewModel>>(response);
|
||||
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var component = FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await
|
||||
HttpClient.GetAsync($"/api/components/{component.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await
|
||||
GetModelFromResponseAsync<ComponentViewModel>(response), component);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/components/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var manufacturer = FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/components/{manufacturer.Name}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<ComponentViewModel>(response), manufacturer);
|
||||
}
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/components/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 component = FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(prevName: oldName);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/components/{oldName}");
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<ComponentViewModel>(response), component);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn();
|
||||
var component = CreateModel(Name: "unique2");
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/components", MakeContent(component));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(FurnitureAssemblyDbContext.GetComponentFromDatabaseById(component.Id!), component);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/components", 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/components", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var componentIdIncorrect = new ComponentBindingModel { Id = "Id", Name = "name" };
|
||||
var componentWithNameIncorrect = new ComponentBindingModel { Id = Guid.NewGuid().ToString(), Name = string.Empty };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/components", MakeContent(componentIdIncorrect));
|
||||
var responseWithNameIncorrect = await HttpClient.PostAsync($"/api/components", MakeContent(componentWithNameIncorrect));
|
||||
//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_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var component = CreateModel();
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(component.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/components", MakeContent(component));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
FurnitureAssemblyDbContext.ChangeTracker.Clear();
|
||||
AssertElement(FurnitureAssemblyDbContext.GetComponentFromDatabaseById(component.Id!), component);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_CheckPrevNames_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var component1 = CreateModel(Name: "name 1");
|
||||
var component2 = CreateModel(id: component1.Id, Name: "name 2");
|
||||
var component3 = CreateModel(id: component1.Id, Name: "name 3");
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(component1.Id);
|
||||
//Act
|
||||
await HttpClient.PutAsync($"/api/components", MakeContent(component1));
|
||||
await HttpClient.PutAsync($"/api/components", MakeContent(component2));
|
||||
await HttpClient.PutAsync($"/api/components", MakeContent(component3));
|
||||
//Assert
|
||||
FurnitureAssemblyDbContext.ChangeTracker.Clear();
|
||||
var entityModel = FurnitureAssemblyDbContext.GetComponentFromDatabaseById(component1.Id!);
|
||||
Assert.That(entityModel, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(entityModel.Name, Is.EqualTo(component3.Name));
|
||||
Assert.That(entityModel.PrevName, Is.EqualTo(component2.Name));
|
||||
Assert.That(entityModel.PrevPrevName, Is.EqualTo(component1.Name));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var manufacturerModel = CreateModel();
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/components", MakeContent(manufacturerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var component = CreateModel(Name: "unique name");
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(component.Id);
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(name: component.Name!);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/components", MakeContent(component));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/components", 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/components", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var component = Guid.NewGuid().ToString();
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(component);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/components/{component}");
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(FurnitureAssemblyDbContext.GetComponentFromDatabaseById(component), Is.Null);
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/components/{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/components/id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
private static ComponentBindingModel CreateModel(string? id = null, string Name = "test", ComponentType type = ComponentType.Panel)
|
||||
=> new()
|
||||
{
|
||||
Id = id ?? Guid.NewGuid().ToString(),
|
||||
Name = Name,
|
||||
Type = type,
|
||||
};
|
||||
|
||||
private static void AssertElement(ComponentViewModel? actual, Component expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.Name, Is.EqualTo(expected.Name));
|
||||
Assert.That(actual.Type, Is.EqualTo(expected.Type));
|
||||
});
|
||||
}
|
||||
|
||||
private static void AssertElement(Component? actual, ComponentBindingModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.Name, Is.EqualTo(expected.Name));
|
||||
Assert.That(actual.Type, Is.EqualTo(expected.Type));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
using FurnitureAssemblyContracts.BindingModels;
|
||||
using FurnitureAssemblyContracts.ViewModels;
|
||||
using FurnitureAssemblyDatebase;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using FurnitureAssemblyTests.Infrastructure;
|
||||
using System.Net;
|
||||
|
||||
namespace FurnitureAssemblyTests.WebApiControllerTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class FurnitureControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
private string _componentId;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_componentId = FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn().Id;
|
||||
}
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
FurnitureAssemblyDbContext.RemoveComponentsFromDatabase();
|
||||
FurnitureAssemblyDbContext.RemoveFurnituresFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetAllFurnitures_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
// Arrange
|
||||
var furniture = FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(name: "name1");
|
||||
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(name: "name2");
|
||||
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(name: "name3");
|
||||
// Act
|
||||
var response = await HttpClient.GetAsync("/api/furniture");
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<FurnitureViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
});
|
||||
AssertElement(data.First(x => x.Id == furniture.Id), furniture);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/furniture");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<FurnitureViewModel>>(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 furniture = FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await
|
||||
HttpClient.GetAsync($"/api/furniture/{furniture.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<FurnitureViewModel>(response), furniture);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/furniture/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var furniture = FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/furniture/{furniture.Name}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<FurnitureViewModel>(response), furniture);
|
||||
}
|
||||
[Test]
|
||||
public async Task GetElement_ByName_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/furniture/New%20Name");
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn();
|
||||
var furniture = CreateModel(name: "name", components: [(_componentId, 5)]);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/furniture", MakeContent(furniture));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(FurnitureAssemblyDbContext.GetFurnitureFromDatabaseById(furniture.Id!), furniture);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/furniture", 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/furniture", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var furnitureIdIncorrect = new FurnitureBindingModel { Id = "Id", Name = "name" };
|
||||
var furnitureWithNameIncorrect = new FurnitureBindingModel { Id = Guid.NewGuid().ToString(), Name = string.Empty };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/furniture", MakeContent(furnitureIdIncorrect));
|
||||
var responseWithNameIncorrect = await HttpClient.PostAsync($"/api/furniture", MakeContent(furnitureWithNameIncorrect));
|
||||
//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_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var furniture = CreateModel(components: [(_componentId, 5)]);
|
||||
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(furniture.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/furniture", MakeContent(furniture));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
FurnitureAssemblyDbContext.ChangeTracker.Clear();
|
||||
AssertElement(FurnitureAssemblyDbContext.GetFurnitureFromDatabaseById(furniture.Id!), furniture);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var furniture = CreateModel();
|
||||
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/furniture", MakeContent(furniture));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenHaveRecordWithSameName_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var furniture = CreateModel(name: "unique name");
|
||||
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(furniture.Id);
|
||||
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(name: furniture.Name!);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/furniture", MakeContent(furniture));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/furniture", 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/furniture", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var component = Guid.NewGuid().ToString();
|
||||
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(component);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/furniture/{component}");
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{ Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(FurnitureAssemblyDbContext.GetFurnitureFromDatabaseById(component), Is.Null);
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn();
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/furniture/{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/furniture/id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
private static FurnitureBindingModel CreateModel(string? id = null, string name = "test", int weight = 5, List<(string, int)>? components = null)
|
||||
{
|
||||
var furniture = new FurnitureBindingModel() { Id = id ?? Guid.NewGuid().ToString(), Name = name, Weight = weight, Components = [] };
|
||||
if (components is not null)
|
||||
{
|
||||
foreach (var elem in components)
|
||||
{
|
||||
furniture.Components.Add(new FurnitureComponentBindingModel { FurnitureId = furniture.Id, ComponentId = elem.Item1, Count = elem.Item2 });
|
||||
}
|
||||
}
|
||||
return furniture;
|
||||
}
|
||||
|
||||
private static void AssertElement(FurnitureViewModel? actual, Furniture expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.Name, Is.EqualTo(expected.Name));
|
||||
Assert.That(actual.Weight, Is.EqualTo(expected.Weight));
|
||||
});
|
||||
}
|
||||
|
||||
private static void AssertElement(Furniture? actual, FurnitureBindingModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.Name, Is.EqualTo(expected.Name));
|
||||
Assert.That(actual.Weight, Is.EqualTo(expected.Weight));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
using FurnitureAssemblyContracts.BindingModels;
|
||||
using FurnitureAssemblyContracts.ViewModels;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using FurnitureAssemblyTests.Infrastructure;
|
||||
using System.Net;
|
||||
|
||||
namespace FurnitureAssemblyTests.WebApiControllerTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class ManifacturingFurnitureControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
private string _workerId;
|
||||
private string _furnitureId;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_workerId = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn().Id;
|
||||
_furnitureId = FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn().Id;
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
FurnitureAssemblyDbContext.RemoveManifacturingFromDatabase();
|
||||
FurnitureAssemblyDbContext.RemoveWorkersFromDatabase();
|
||||
FurnitureAssemblyDbContext.RemoveFurnituresFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var man = FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_workerId, _furnitureId);
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_workerId, _furnitureId);
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_workerId, _furnitureId);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/manifacturing/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<ManifacturingFurnitureViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
});
|
||||
AssertElement(data.First(x => x.Id == man.Id), man);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/manifacturing/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<ManifacturingFurnitureViewModel>>(response);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByPeriod_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/manifacturing/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 = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "Other worker");
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_workerId, _furnitureId);
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_workerId, _furnitureId);
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(worker.Id, _furnitureId);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/manifacturing/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<ManifacturingFurnitureViewModel>>(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 = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "Other worker");
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_workerId, _furnitureId);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/manifacturing/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<ManifacturingFurnitureViewModel>>(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/manifacturing/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/manifacturing/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_ByFurnitureId_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_workerId, _furnitureId);
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_workerId, _furnitureId);
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_workerId, _furnitureId);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/manifacturing/getfurniturerecords?id={_furnitureId}&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<ManifacturingFurnitureViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(3));
|
||||
Assert.That(data.All(x => x.FurnitureId == _furnitureId));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByFurnitureId_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var furniture = FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_workerId, _furnitureId);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/manifacturing/getfurniturerecords?id={furniture.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<ManifacturingFurnitureViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_ByFurnitureId_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/manifacturing/getfurniturerecords?id={_furnitureId}&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_ByFurnitureId_WhenIdIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/manifacturing/getfurniturerecords?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 man = FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_workerId, _furnitureId);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/manifacturing/getrecord/{man.Id}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<ManifacturingFurnitureViewModel>(response), man);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenIdIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/manifacturing/getrecord/Id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_workerId, _furnitureId);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/manifacturing/getrecord/{Guid.NewGuid()}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_workerId, _furnitureId);
|
||||
var model = CreateModel(_workerId, _furnitureId);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/manifacturing/registermanifacturing", MakeContent(model));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(FurnitureAssemblyDbContext.GetManifacturingFromDatabaseById(model.Id!), model);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var saleId = Guid.NewGuid().ToString();
|
||||
var saleModelWithIdIncorrect = new ManifacturingFurniture { Id = "Id", WorkerId = _workerId, FurnitureId = _furnitureId};
|
||||
var saleModelWithWorkerIdIncorrect = new ManifacturingFurniture { Id = saleId, WorkerId = "Id", FurnitureId = _furnitureId};
|
||||
var saleModelWithBuyerIdIncorrect = new ManifacturingFurniture { Id = saleId, WorkerId = _workerId, FurnitureId = "Id" };
|
||||
var saleModelWithCountIncorrect = new ManifacturingFurniture { Id = saleId, WorkerId = _workerId, FurnitureId = _furnitureId, Count = -1 };
|
||||
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/manifacturing/registermanifacturing", MakeContent(saleModelWithIdIncorrect));
|
||||
var responseWithWorkerIdIncorrect = await HttpClient.PostAsync($"/api/manifacturing/registermanifacturing", MakeContent(saleModelWithWorkerIdIncorrect));
|
||||
var responseWithBuyerIdIncorrect = await HttpClient.PostAsync($"/api/manifacturing/registermanifacturing", MakeContent(saleModelWithBuyerIdIncorrect));
|
||||
var responseWithCountIncorrect = await HttpClient.PostAsync($"/api/manifacturing/registermanifacturing", MakeContent(saleModelWithCountIncorrect));
|
||||
//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(responseWithBuyerIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "BuyerId is incorrect");
|
||||
Assert.That(responseWithCountIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Count is incorrect");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/manifacturing/registermanifacturing", 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/manifacturing/registermanifacturing", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var model = CreateModel(_workerId, _furnitureId);
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(model.WorkerId!, model.FurnitureId!, model.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/manifacturing/changemanifacturing", MakeContent(model));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
FurnitureAssemblyDbContext.ChangeTracker.Clear();
|
||||
AssertElement(FurnitureAssemblyDbContext.GetManifacturingFromDatabaseById(model.Id!), model);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var model = CreateModel(_workerId, _furnitureId);
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(model.WorkerId!, model.FurnitureId!);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/manifacturing/changemanifacturing", MakeContent(model));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/manifacturing/changemanifacturing", 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/manifacturing/changemanifacturing", MakeContent(new { Data = "test", Position = 10 }));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
private static ManifacturingFurnitureBindingModel CreateModel(string workerId, string furnitureId, string? id = null, int count = 1)
|
||||
{
|
||||
var mid = id ?? Guid.NewGuid().ToString();
|
||||
return new()
|
||||
{
|
||||
Id = mid,
|
||||
WorkerId = workerId,
|
||||
FurnitureId = furnitureId,
|
||||
Count = count,
|
||||
ProductionDate = DateTime.UtcNow
|
||||
};
|
||||
}
|
||||
|
||||
private static void AssertElement(ManifacturingFurnitureViewModel? actual, ManifacturingFurniture expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
|
||||
Assert.That(actual.FurnitureId, Is.EqualTo(expected.FurnitureId));
|
||||
Assert.That(actual.Count, Is.EqualTo(expected.Count));
|
||||
});
|
||||
}
|
||||
|
||||
private static void AssertElement(ManifacturingFurniture? actual, ManifacturingFurnitureBindingModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
|
||||
Assert.That(actual.FurnitureId, Is.EqualTo(expected.FurnitureId));
|
||||
Assert.That(actual.Count, Is.EqualTo(expected.Count));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,470 @@
|
||||
using FurnitureAssemblyContracts.BindingModels;
|
||||
using FurnitureAssemblyContracts.Enums;
|
||||
using FurnitureAssemblyContracts.ViewModels;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using FurnitureAssemblyTests.Infrastructure;
|
||||
using System.Net;
|
||||
|
||||
namespace FurnitureAssemblyTests.WebApiControllerTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class PostControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
FurnitureAssemblyDbContext.RemovePostsFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetRecords_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postName: "name 1");
|
||||
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postName: "name 2");
|
||||
FurnitureAssemblyDbContext.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<PostViewModel>>(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();
|
||||
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
|
||||
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
|
||||
FurnitureAssemblyDbContext.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();
|
||||
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
|
||||
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
|
||||
FurnitureAssemblyDbContext.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 = FurnitureAssemblyDbContext.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
|
||||
FurnitureAssemblyDbContext.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 = FurnitureAssemblyDbContext.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 = FurnitureAssemblyDbContext.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
|
||||
FurnitureAssemblyDbContext.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 = FurnitureAssemblyDbContext.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
|
||||
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn();
|
||||
var postModel = CreateModel();
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(FurnitureAssemblyDbContext.GetPostFromDatabaseByPostId(postModel.Id!), postModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModel = CreateModel();
|
||||
FurnitureAssemblyDbContext.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");
|
||||
FurnitureAssemblyDbContext.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.Builder.ToString(), Salary = 10 };
|
||||
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Builder.ToString(), Salary = 10 };
|
||||
var postModelWithPostTypeIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = string.Empty, Salary = 10 };
|
||||
var postModelWithSalaryIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Builder.ToString(), Salary = -10 };
|
||||
//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 Put_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModel = CreateModel();
|
||||
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
FurnitureAssemblyDbContext.ChangeTracker.Clear();
|
||||
AssertElement(FurnitureAssemblyDbContext.GetPostFromDatabaseByPostId(postModel.Id!), postModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postModel = CreateModel();
|
||||
FurnitureAssemblyDbContext.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();
|
||||
FurnitureAssemblyDbContext.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");
|
||||
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postModel.Id);
|
||||
FurnitureAssemblyDbContext.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.Builder.ToString(), Salary = 10 };
|
||||
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Builder.ToString(), Salary = 10 };
|
||||
var postModelWithPostTypeIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = string.Empty, Salary = 10 };
|
||||
var postModelWithSalaryIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Builder.ToString(), Salary = -10 };
|
||||
//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 Delete_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postId = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn().PostId;
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/posts/{postId}");
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(FurnitureAssemblyDbContext.GetPostFromDatabaseByPostId(postId), Is.Null);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
FurnitureAssemblyDbContext.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 = FurnitureAssemblyDbContext.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 = FurnitureAssemblyDbContext.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(FurnitureAssemblyDbContext.GetPostFromDatabaseByPostId(postId), Is.Not.Null);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Patch_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
FurnitureAssemblyDbContext.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 = FurnitureAssemblyDbContext.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(FurnitureAssemblyDbContext.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(actual.Salary, Is.EqualTo(expected.Salary));
|
||||
});
|
||||
}
|
||||
|
||||
private static PostBindingModel CreateModel(string? postId = null, string postName = "name", PostType postType = PostType.Builder, double salary = 10)
|
||||
=> new()
|
||||
{
|
||||
Id = postId ?? Guid.NewGuid().ToString(),
|
||||
PostName = postName,
|
||||
PostType = postType.ToString(),
|
||||
Salary = salary
|
||||
};
|
||||
|
||||
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.Salary, Is.EqualTo(expected.Salary));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
using FurnitureAssemblyContracts.ViewModels;
|
||||
using System.Net;
|
||||
using System;
|
||||
using FurnitureAssemblyTests.Infrastructure;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
|
||||
|
||||
namespace FurnitureAssemblyTests.WebApiControllerTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class SalaryControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
FurnitureAssemblyDbContext.RemovePostsFromDatabase();
|
||||
FurnitureAssemblyDbContext.RemoveManifacturingFromDatabase();
|
||||
FurnitureAssemblyDbContext.RemoveFurnituresFromDatabase();
|
||||
FurnitureAssemblyDbContext.RemoveWorkersFromDatabase();
|
||||
FurnitureAssemblyDbContext.RemoveSalariesFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "Иванов И.И.");
|
||||
var salary = FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(worker.Id, workerSalary: 100);
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(worker.Id);
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(worker.Id);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salaries/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(3));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salaries/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_OnlyInDatePeriod_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "Иванов И.И.");
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salaries/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_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salaries/getworkerrecords?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 = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "Иванов И.И.");
|
||||
var worker2 = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "Иванов И.И.");
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id);
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id);
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(worker2.Id);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salaries/getworkerrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&id={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_OnlyInDatePeriod_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker1 = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "Иванов И.И.");
|
||||
var worker2 = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "Иванов И.И.");
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(worker2.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(worker2.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
FurnitureAssemblyDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salaries/getworkerrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&id={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_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "Иванов И.И.");
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/salaries/getworkerrecords?fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&id={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/salaries/getworkerrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&id=id");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Calculate_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(salary: 1000);
|
||||
var worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "Иванов И.И.", postId: post.PostId);
|
||||
var furniture = FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn();
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(worker.Id, furniture.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/salaries/calculate?date={DateTime.UtcNow:MM/dd/yyyy}", null);
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
var salaries = FurnitureAssemblyDbContext.GetSalariesFromDatabaseByWorkerId(worker.Id);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(salaries, Has.Length.EqualTo(1));
|
||||
Assert.That(salaries.First().WorkerSalary, Is.EqualTo(100));
|
||||
Assert.That(salaries.First().SalaryDate.Month, Is.EqualTo(DateTime.UtcNow.Month));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Calculate_WithoutWorkers_ShouldSuccess_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/salaries/calculate?date={DateTime.UtcNow:MM/dd/yyyy}", null);
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
var salaries = FurnitureAssemblyDbContext.Salaries.ToArray();
|
||||
Assert.That(salaries, Has.Length.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Calculate_WithoutSalesByWorker_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(salary: 1000);
|
||||
var worker1 = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "name 1", postId: post.PostId, config: new PostConfiguration() { Rate = 1000 });
|
||||
var worker2 = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "name 2", postId: post.PostId);
|
||||
var man = FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn();
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(worker1.Id, man.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/salaries/calculate?date={DateTime.UtcNow:MM/dd/yyyy}", null);
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
var salary1 = FurnitureAssemblyDbContext.GetSalariesFromDatabaseByWorkerId(worker1.Id).First().WorkerSalary;
|
||||
var salary2 = FurnitureAssemblyDbContext.GetSalariesFromDatabaseByWorkerId(worker2.Id).First().WorkerSalary;
|
||||
Assert.That(salary1, Is.Not.EqualTo(salary2));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,618 @@
|
||||
using FurnitureAssemblyContracts.BindingModels;
|
||||
using FurnitureAssemblyContracts.Enums;
|
||||
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
|
||||
using FurnitureAssemblyContracts.ViewModels;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using FurnitureAssemblyTests.Infrastructure;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace FurnitureAssemblyTests.WebApiControllerTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class WorkerControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
private Post _post;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn();
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
FurnitureAssemblyDbContext.RemovePostsFromDatabase();
|
||||
FurnitureAssemblyDbContext.RemoveWorkersFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId)
|
||||
.AddPost(_post);
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: _post.PostId);
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", postId: _post.PostId);
|
||||
//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
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId, isDeleted: true);
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: _post.PostId, isDeleted: false);
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", postId: _post.PostId, 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
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId, isDeleted: true);
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: _post.PostId, isDeleted: true);
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", postId: _post.PostId, 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
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId);
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: _post.PostId);
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", postId: _post.PostId, isDeleted: true);
|
||||
FurnitureAssemblyDbContext.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
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId);
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4");
|
||||
//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
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "Иванов И.И.", birthDate: DateTime.UtcNow.AddYears(-25));
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "Иванов И.И.", birthDate: DateTime.UtcNow.AddYears(-21));
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "Иванов И.И.", birthDate: DateTime.UtcNow.AddYears(-20), isDeleted: true);
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "Иванов И.И.", 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
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "Иванов И.И.", employmentDate: DateTime.UtcNow.AddDays(-2));
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "Иванов И.И.", employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "Иванов И.И.", employmentDate: DateTime.UtcNow.AddDays(1), isDeleted: true);
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "Иванов И.И.", 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 = FurnitureAssemblyDbContext.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
|
||||
FurnitureAssemblyDbContext.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 = FurnitureAssemblyDbContext.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 = FurnitureAssemblyDbContext.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
|
||||
FurnitureAssemblyDbContext.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 = FurnitureAssemblyDbContext.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 Post_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
var workerModel = CreateModel(_post.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/workers/register", MakeContent(workerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(FurnitureAssemblyDbContext.GetWorkerFromDatabaseById(workerModel.Id!), workerModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerModel = CreateModel(_post.Id);
|
||||
FurnitureAssemblyDbContext.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_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerModelWithIdIncorrect = new WorkerBindingModel { Id = "Id", FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id, ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
|
||||
var workerModelWithFioIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = string.Empty, BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id, ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
|
||||
var workerModelWithPostIdIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = "Id", ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
|
||||
var workerModelWithBirthDateIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-15), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id, ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
|
||||
var workerModelWithConfigurationIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-15), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id, ConfigurationJson = null };
|
||||
//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 responseWithConfigurationIncorrect = await HttpClient.PostAsync($"/api/workers/register", MakeContent(workerModelWithConfigurationIncorrect));
|
||||
//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(responseWithConfigurationIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Configuration 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);
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(workerModel.Id);
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
FurnitureAssemblyDbContext.ChangeTracker.Clear();
|
||||
AssertElement(FurnitureAssemblyDbContext.GetWorkerFromDatabaseById(workerModel.Id!), workerModel);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerModel = CreateModel(_post.Id, fio: "new fio");
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
//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");
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(workerModel.Id, 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_WhenDataIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerModelWithIdIncorrect = new WorkerBindingModel { Id = "Id", FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id, ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
|
||||
var workerModelWithFioIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = string.Empty, BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id, ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
|
||||
var workerModelWithPostIdIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = "Id", ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
|
||||
var workerModelWithBirthDateIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-15), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id, ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
|
||||
var workerModelWithConfigurationIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-15), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id, ConfigurationJson = null };
|
||||
//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 responseConfigurationIncorrect = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModelWithConfigurationIncorrect));
|
||||
//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(responseConfigurationIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Configuration 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();
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(workerId);
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/workers/delete/{workerId}");
|
||||
FurnitureAssemblyDbContext.ChangeTracker.Clear();
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That(FurnitureAssemblyDbContext.GetWorkerFromDatabaseById(workerId)!.IsDeleted);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Delete_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
FurnitureAssemblyDbContext.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 = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(isDeleted: true).Id;
|
||||
//Act
|
||||
var response = await HttpClient.DeleteAsync($"/api/workers/delete/{workerId}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetRecords_WhenDifferentConfigTypes_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var workerSimple = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(postId: _post.PostId).AddPost(_post);
|
||||
var workerBuilder = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(postId: _post.PostId, config: new BuilderPostConfiguration() { PersonalCount = 500 }).AddPost(_post);
|
||||
var workerChief = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(postId: _post.PostId, config: new ChiefPostConfiguration() { PersonalCountTrendPremium = 500 }).AddPost(_post);
|
||||
//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.That(data, Is.Not.Null);
|
||||
AssertElement(data.First(x => x.Id == workerSimple.Id), workerSimple);
|
||||
AssertElement(data.First(x => x.Id == workerBuilder.Id), workerBuilder);
|
||||
AssertElement(data.First(x => x.Id == workerChief.Id), workerChief);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WithBuilderPostConfiguration_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var personalCount = 500;
|
||||
var workerModel = CreateModel(postId: _post.PostId, configuration: JsonSerializer.Serialize(new BuilderPostConfiguration() { Rate = 10, PersonalCount = 500 }));
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/workers/register", MakeContent(workerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
var element = FurnitureAssemblyDbContext.GetWorkerFromDatabaseById(workerModel.Id!);
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(BuilderPostConfiguration).Name));
|
||||
Assert.That((element.Configuration as BuilderPostConfiguration)!.PersonalCount, Is.EqualTo(personalCount));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WithChiefPostConfiguration_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var personalCountTrendPremium = 500;
|
||||
var workerModel = CreateModel(postId: _post.PostId, configuration: JsonSerializer.Serialize(new ChiefPostConfiguration() { Rate = 10, PersonalCountTrendPremium = 500 }));
|
||||
//Act
|
||||
var response = await HttpClient.PostAsync($"/api/workers/register", MakeContent(workerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
var element = FurnitureAssemblyDbContext.GetWorkerFromDatabaseById(workerModel.Id!);
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(ChiefPostConfiguration).Name));
|
||||
Assert.That((element.Configuration as ChiefPostConfiguration)!.PersonalCountTrendPremium, Is.EqualTo(personalCountTrendPremium));
|
||||
});
|
||||
}
|
||||
|
||||
public async Task Put_WithCashierPostConfiguration_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var personalCount = 10;
|
||||
var worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
var postModel = CreateModel(postId: _post.PostId, id: worker.Id, configuration: JsonSerializer.Serialize(new BuilderPostConfiguration() { Rate = 10, PersonalCount = 500 }));
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(postModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
FurnitureAssemblyDbContext.ChangeTracker.Clear();
|
||||
var element = FurnitureAssemblyDbContext.GetWorkerFromDatabaseById(postModel.Id!);
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(BuilderPostConfiguration).Name));
|
||||
Assert.That((element.Configuration as BuilderPostConfiguration)!.PersonalCount, Is.EqualTo(personalCount));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WithChiefPostConfiguration_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var personalCountTrendPremium = 500;
|
||||
var worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
var workerModel = CreateModel(postId: _post.PostId, id: worker.Id, configuration: JsonSerializer.Serialize(new ChiefPostConfiguration() { Rate = 10, PersonalCountTrendPremium = 500 }));
|
||||
//Act
|
||||
var response = await HttpClient.PutAsync($"api/workers/changeinfo", MakeContent(workerModel));
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
FurnitureAssemblyDbContext.ChangeTracker.Clear();
|
||||
var element = FurnitureAssemblyDbContext.GetWorkerFromDatabaseById(workerModel.Id!);
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(ChiefPostConfiguration).Name));
|
||||
Assert.That((element.Configuration as ChiefPostConfiguration)!.PersonalCountTrendPremium, Is.EqualTo(personalCountTrendPremium));
|
||||
});
|
||||
}
|
||||
|
||||
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.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));
|
||||
Assert.That(JsonNode.Parse(actual.Configuration)!["Type"]!.GetValue<string>(), Is.EqualTo(expected.Configuration.Type));
|
||||
});
|
||||
}
|
||||
|
||||
private static WorkerBindingModel CreateModel(string postId, string? id = null, string fio = "Иванов И.И.", DateTime? birthDate = null, DateTime? employmentDate = null, string? configuration = null)
|
||||
{
|
||||
return new()
|
||||
{
|
||||
Id = id ?? Guid.NewGuid().ToString(),
|
||||
FIO = fio,
|
||||
BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-22),
|
||||
EmploymentDate = employmentDate ?? DateTime.UtcNow.AddDays(-5),
|
||||
PostId = postId,
|
||||
ConfigurationJson = configuration ?? JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 })
|
||||
};
|
||||
}
|
||||
|
||||
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.BirthDate.ToString(), Is.EqualTo(expected.BirthDate.ToString()));
|
||||
Assert.That(actual.EmploymentDate.ToString(), Is.EqualTo(expected.EmploymentDate.ToString()));
|
||||
Assert.That(!actual.IsDeleted);
|
||||
Assert.That(actual.Configuration.Type, Is.EqualTo(JsonNode.Parse(expected.ConfigurationJson!)!["Type"]!.GetValue<string>()));
|
||||
});
|
||||
}
|
||||
}
|
||||
32
FurnitureAssembly/FurnitureAssemblyTests/appsettings.json
Normal file
32
FurnitureAssembly/FurnitureAssemblyTests/appsettings.json
Normal file
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": {
|
||||
"Default": "Information"
|
||||
},
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": {
|
||||
"path": "../logs/furnitureassembly-.log",
|
||||
"rollingInterval": "Day",
|
||||
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {CorrelationId} {Level:u3} {Username} {Message:lj}{Exception}{NewLine}"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"AllowedHosts": "*",
|
||||
"SalarySettings": {
|
||||
"ExtraMadeSum": 10,
|
||||
"MaxConcurrentThreads": 2
|
||||
},
|
||||
"BuilderSettings": {
|
||||
"PersonalCount": 0.1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
using AutoMapper;
|
||||
using FurnitureAssemblyBusinessLogic.Implementations;
|
||||
using FurnitureAssemblyContracts.AdapterContracts;
|
||||
using FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
|
||||
using FurnitureAssemblyContracts.BindingModels;
|
||||
using FurnitureAssemblyContracts.BusinessLogicsContracts;
|
||||
using FurnitureAssemblyContracts.DataModels;
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using FurnitureAssemblyContracts.ViewModels;
|
||||
|
||||
namespace FurnitureAssemblyWebApi.Adapters;
|
||||
|
||||
public class ComponentAdapter : IComponentAdapter
|
||||
{
|
||||
private readonly IComponentBusinessLogicContract _componentBusinessLogicContract;
|
||||
private readonly ILogger<ComponentAdapter> _logger;
|
||||
private readonly IMapper _mapper;
|
||||
|
||||
public ComponentAdapter(IComponentBusinessLogicContract componentBusinessLogicContract, ILogger<ComponentAdapter> logger)
|
||||
{
|
||||
_componentBusinessLogicContract = componentBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<ComponentBindingModel, ComponentDataModel>();
|
||||
cfg.CreateMap<ComponentDataModel, ComponentViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public ComponentOperationResponse GetAllComponents()
|
||||
{
|
||||
try
|
||||
{
|
||||
return ComponentOperationResponse.OK([.. _componentBusinessLogicContract.GetAllComponents().Select(x => _mapper.Map<ComponentViewModel>(x))]);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException: The list of components is null");
|
||||
return ComponentOperationResponse.NotFound("The list of components is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException: Error while working with data storage");
|
||||
return ComponentOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException?.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception: An unexpected error occurred");
|
||||
return ComponentOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ComponentOperationResponse GetComponentByData(string data)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ComponentOperationResponse.OK(_mapper.Map<ComponentViewModel>(_componentBusinessLogicContract.GetComponentByData(data)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException: Data is null or empty");
|
||||
return ComponentOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException: Component not found");
|
||||
return ComponentOperationResponse.NotFound($"Component with data '{data}' not found");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException: Error while working with data storage");
|
||||
return ComponentOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException?.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception: An unexpected error occurred");
|
||||
return ComponentOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ComponentOperationResponse InsertComponent(ComponentBindingModel componentDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_componentBusinessLogicContract.InsertComponent(_mapper.Map<ComponentDataModel>(componentDataModel));
|
||||
return ComponentOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException: Component data is null");
|
||||
return ComponentOperationResponse.BadRequest("Component data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException: Invalid component data");
|
||||
return ComponentOperationResponse.BadRequest($"Invalid component data: {ex.Message}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException: Component already exists");
|
||||
return ComponentOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException: Error while working with data storage");
|
||||
return ComponentOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException?.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception: An unexpected error occurred");
|
||||
return ComponentOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ComponentOperationResponse UpdateComponent(ComponentBindingModel componentDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_componentBusinessLogicContract.UpdateComponent(_mapper.Map<ComponentDataModel>(componentDataModel));
|
||||
return ComponentOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException: Component data is null");
|
||||
return ComponentOperationResponse.BadRequest("Component data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException: Invalid component data");
|
||||
return ComponentOperationResponse.BadRequest($"Invalid component data: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException: Component not found");
|
||||
return ComponentOperationResponse.BadRequest($"Component with id '{componentDataModel.Id}' not found");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException: Component already exists");
|
||||
return ComponentOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException: Error while working with data storage");
|
||||
return ComponentOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException?.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception: An unexpected error occurred");
|
||||
return ComponentOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ComponentOperationResponse DeleteComponent(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
_componentBusinessLogicContract.DeleteComponent(id);
|
||||
return ComponentOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException: Id is null or empty");
|
||||
return ComponentOperationResponse.BadRequest("Id is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException: Invalid id");
|
||||
return ComponentOperationResponse.BadRequest($"Invalid id: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException: Component not found");
|
||||
return ComponentOperationResponse.BadRequest($"Component with id '{id}' not found");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException: Error while working with data storage");
|
||||
return ComponentOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException?.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception: An unexpected error occurred");
|
||||
return ComponentOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
using AutoMapper;
|
||||
using FurnitureAssemblyContracts.AdapterContracts;
|
||||
using FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
|
||||
using FurnitureAssemblyContracts.BindingModels;
|
||||
using FurnitureAssemblyContracts.BusinessLogicsContracts;
|
||||
using FurnitureAssemblyContracts.DataModels;
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using FurnitureAssemblyContracts.ViewModels;
|
||||
|
||||
namespace FurnitureAssemblyWebApi.Adapters;
|
||||
|
||||
public class FurnitureAdapter : IFurnitureAdapter
|
||||
{
|
||||
private readonly IFurnitureBusinessLogicContract _furnitureBusinessLogicContract;
|
||||
private readonly ILogger<FurnitureAdapter> _logger;
|
||||
private readonly IMapper _mapper;
|
||||
|
||||
public FurnitureAdapter(IFurnitureBusinessLogicContract furnitureBusinessLogicContract, ILogger<FurnitureAdapter> logger)
|
||||
{
|
||||
_furnitureBusinessLogicContract = furnitureBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<FurnitureBindingModel, FurnitureDataModel>();
|
||||
cfg.CreateMap<FurnitureDataModel, FurnitureViewModel>();
|
||||
cfg.CreateMap<FurnitureComponentBindingModel, FurnitureComponentDataModel>();
|
||||
cfg.CreateMap<FurnitureComponentDataModel, FurnitureComponentViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public FurnitureOperationResponse GetAllFurnitures()
|
||||
{
|
||||
try
|
||||
{
|
||||
Console.WriteLine(_furnitureBusinessLogicContract.GetAllFurnitures());
|
||||
return FurnitureOperationResponse.OK([.. _furnitureBusinessLogicContract.GetAllFurnitures().Select(x => _mapper.Map<FurnitureViewModel>(x))]);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException: The list of furniture is null");
|
||||
return FurnitureOperationResponse.NotFound("The list of furniture is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException: Error while working with data storage");
|
||||
return FurnitureOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException?.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception: An unexpected error occurred");
|
||||
return FurnitureOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public FurnitureOperationResponse GetFurnitureByData(string data)
|
||||
{
|
||||
try
|
||||
{
|
||||
return FurnitureOperationResponse.OK(_mapper.Map<FurnitureViewModel>(_furnitureBusinessLogicContract.GetFurnitureByData(data)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException: Data is null or empty");
|
||||
return FurnitureOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException: furniture not found");
|
||||
return FurnitureOperationResponse.NotFound($"furniture with data '{data}' not found");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException: Error while working with data storage");
|
||||
return FurnitureOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException?.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception: An unexpected error occurred");
|
||||
return FurnitureOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public FurnitureOperationResponse InsertFurniture(FurnitureBindingModel furnitureDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_furnitureBusinessLogicContract.InsertFurniture(_mapper.Map<FurnitureDataModel>(furnitureDataModel));
|
||||
return FurnitureOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException: furniture data is null");
|
||||
return FurnitureOperationResponse.BadRequest("furniture data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException: Invalid furniture data");
|
||||
return FurnitureOperationResponse.BadRequest($"Invalid furniture data: {ex.Message}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException: furniture already exists");
|
||||
return FurnitureOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException: Error while working with data storage");
|
||||
return FurnitureOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException?.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception: An unexpected error occurred");
|
||||
return FurnitureOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public FurnitureOperationResponse UpdateFurniture(FurnitureBindingModel furnitureDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_furnitureBusinessLogicContract.UpdateFurniture(_mapper.Map<FurnitureDataModel>(furnitureDataModel));
|
||||
return FurnitureOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException: furniture data is null");
|
||||
return FurnitureOperationResponse.BadRequest("furniture data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException: Invalid furniture data");
|
||||
return FurnitureOperationResponse.BadRequest($"Invalid furniture data: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException: furniture not found");
|
||||
return FurnitureOperationResponse.BadRequest($"furniture with id '{furnitureDataModel.Id}' not found");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException: furniture already exists");
|
||||
return FurnitureOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException: Error while working with data storage");
|
||||
return FurnitureOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException?.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception: An unexpected error occurred");
|
||||
return FurnitureOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public FurnitureOperationResponse DeleteFurniture(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
_furnitureBusinessLogicContract.DeleteFurniture(id);
|
||||
return FurnitureOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException: Id is null or empty");
|
||||
return FurnitureOperationResponse.BadRequest("Id is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException: Invalid id");
|
||||
return FurnitureOperationResponse.BadRequest($"Invalid id: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException: furniture not found");
|
||||
return FurnitureOperationResponse.BadRequest($"furniture with id '{id}' not found");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException: Error while working with data storage");
|
||||
return FurnitureOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException?.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception: An unexpected error occurred");
|
||||
return FurnitureOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
using AutoMapper;
|
||||
using FurnitureAssemblyContracts.AdapterContracts;
|
||||
using FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
|
||||
using FurnitureAssemblyContracts.BindingModels;
|
||||
using FurnitureAssemblyContracts.BusinessLogicsContracts;
|
||||
using FurnitureAssemblyContracts.DataModels;
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using FurnitureAssemblyContracts.ViewModels;
|
||||
|
||||
namespace FurnitureAssemblyWebApi.Adapters;
|
||||
|
||||
public class ManifacturingFurnitureAdapter : IManifacturingFurnitureAdapter
|
||||
{
|
||||
private readonly IManifacturingBusinessLogicContract _manifacturingBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public ManifacturingFurnitureAdapter(IManifacturingBusinessLogicContract mfBusinessLogicContract, ILogger<ManifacturingFurnitureAdapter> logger)
|
||||
{
|
||||
_manifacturingBusinessLogicContract = mfBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<ManifacturingFurnitureBindingModel, ManifacturingFurnitureDataModel>();
|
||||
cfg.CreateMap<ManifacturingFurnitureDataModel, ManifacturingFurnitureViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public ManifacturingFurnitureOperationResponse GetList(DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ManifacturingFurnitureOperationResponse.OK([.. _manifacturingBusinessLogicContract.GetManifacturingByPeriod(fromDate, toDate).Select(x => _mapper.Map<ManifacturingFurnitureViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return ManifacturingFurnitureOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return ManifacturingFurnitureOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ManifacturingFurnitureOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ManifacturingFurnitureOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ManifacturingFurnitureOperationResponse GetAllManifacturingByWorkerByPeriod(string id, DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ManifacturingFurnitureOperationResponse.OK([.. _manifacturingBusinessLogicContract.GetAllManifacturingByWorkerByPeriod(id, fromDate, toDate).Select(x => _mapper.Map<ManifacturingFurnitureViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return ManifacturingFurnitureOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return ManifacturingFurnitureOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return ManifacturingFurnitureOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ManifacturingFurnitureOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ManifacturingFurnitureOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ManifacturingFurnitureOperationResponse GetAllManifacturingByFurnitureByPeriod(string id, DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ManifacturingFurnitureOperationResponse.OK([.. _manifacturingBusinessLogicContract.GetAllManifacturingByFurnitureByPeriod(id, fromDate, toDate).Select(x => _mapper.Map<ManifacturingFurnitureViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return ManifacturingFurnitureOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return ManifacturingFurnitureOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return ManifacturingFurnitureOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ManifacturingFurnitureOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ManifacturingFurnitureOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ManifacturingFurnitureOperationResponse GetElement(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ManifacturingFurnitureOperationResponse.OK(_mapper.Map<ManifacturingFurnitureViewModel>(_manifacturingBusinessLogicContract.GetManifacturingByData(id)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ManifacturingFurnitureOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return ManifacturingFurnitureOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return ManifacturingFurnitureOperationResponse.NotFound($"Not found element by data {id}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ManifacturingFurnitureOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ManifacturingFurnitureOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ManifacturingFurnitureOperationResponse RegisterManifacturingFurniture(ManifacturingFurnitureBindingModel model)
|
||||
{
|
||||
try
|
||||
{
|
||||
var data = _mapper.Map<ManifacturingFurnitureDataModel>(model);
|
||||
_manifacturingBusinessLogicContract.InsertFurniture(_mapper.Map<ManifacturingFurnitureDataModel>(model));
|
||||
return ManifacturingFurnitureOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ManifacturingFurnitureOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return ManifacturingFurnitureOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ManifacturingFurnitureOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ManifacturingFurnitureOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ManifacturingFurnitureOperationResponse ChangeManifacturingFurniture(ManifacturingFurnitureBindingModel model)
|
||||
{
|
||||
try
|
||||
{
|
||||
_manifacturingBusinessLogicContract.UpdateFurniture(_mapper.Map<ManifacturingFurnitureDataModel>(model));
|
||||
return ManifacturingFurnitureOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException: furniture data is null");
|
||||
return ManifacturingFurnitureOperationResponse.BadRequest("furniture data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException: Invalid furniture data");
|
||||
return ManifacturingFurnitureOperationResponse.BadRequest($"Invalid furniture data: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException: furniture not found");
|
||||
return ManifacturingFurnitureOperationResponse.BadRequest($"furniture with id '{model.Id}' not found");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException: furniture already exists");
|
||||
return ManifacturingFurnitureOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException: Error while working with data storage");
|
||||
return ManifacturingFurnitureOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException?.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception: An unexpected error occurred");
|
||||
return ManifacturingFurnitureOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
using AutoMapper;
|
||||
using FurnitureAssemblyContracts.AdapterContracts;
|
||||
using FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
|
||||
using FurnitureAssemblyContracts.BindingModels;
|
||||
using FurnitureAssemblyContracts.BusinessLogicsContracts;
|
||||
using FurnitureAssemblyContracts.DataModels;
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using FurnitureAssemblyContracts.ViewModels;
|
||||
|
||||
namespace FurnitureAssemblyWebApi.Adapters;
|
||||
|
||||
public class PostAdapter : IPostAdapter
|
||||
{
|
||||
private readonly IPostBusinessLogicContract _postBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public PostAdapter(IPostBusinessLogicContract postBusinessLogicContract, ILogger<PostAdapter> logger)
|
||||
{
|
||||
_postBusinessLogicContract = postBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<PostBindingModel, PostDataModel>();
|
||||
cfg.CreateMap<PostDataModel, PostViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public PostOperationResponse GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllPosts().Select(x => _mapper.Map<PostViewModel>(x))]);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return PostOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
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([.. _postBusinessLogicContract.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>(_postBusinessLogicContract.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
|
||||
{
|
||||
_postBusinessLogicContract.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
|
||||
{
|
||||
_postBusinessLogicContract.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
|
||||
{
|
||||
_postBusinessLogicContract.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
|
||||
{
|
||||
_postBusinessLogicContract.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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
using AutoMapper;
|
||||
using FurnitureAssemblyContracts.AdapterContracts;
|
||||
using FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
|
||||
using FurnitureAssemblyContracts.BusinessLogicsContracts;
|
||||
using FurnitureAssemblyContracts.DataModels;
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using FurnitureAssemblyContracts.ViewModels;
|
||||
|
||||
namespace FurnitureAssemblyWebApi.Adapters;
|
||||
|
||||
public class SalaryAdapter : ISalaryAdapter
|
||||
{
|
||||
private readonly ISalaryBusinessLogicContract _salaryBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public SalaryAdapter(ISalaryBusinessLogicContract salaryBusinessLogicContract, ILogger<SalaryAdapter> logger)
|
||||
{
|
||||
_salaryBusinessLogicContract = salaryBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<SalaryDataModel, SalaryViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public SalaryOperationResponse GetListByPeriod(DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SalaryOperationResponse.OK([.. _salaryBusinessLogicContract.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($"Incorrect dates: {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 GetListByPeriodByWorker(DateTime fromDate, DateTime toDate, string workerId)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SalaryOperationResponse.OK([.. _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(fromDate, toDate, workerId).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($"Incorrect dates: {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 CalculateSalary(DateTime date)
|
||||
{
|
||||
try
|
||||
{
|
||||
_salaryBusinessLogicContract.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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
using AutoMapper;
|
||||
using FurnitureAssemblyContracts.AdapterContracts;
|
||||
using FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
|
||||
using FurnitureAssemblyContracts.BindingModels;
|
||||
using FurnitureAssemblyContracts.BusinessLogicsContracts;
|
||||
using FurnitureAssemblyContracts.DataModels;
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using FurnitureAssemblyContracts.ViewModels;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace FurnitureAssemblyWebApi.Adapters;
|
||||
|
||||
public class WorkerAdapter : IWorkerAdapter
|
||||
{
|
||||
private readonly IWorkerBusinessLogicContract _buyerBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
private readonly JsonSerializerOptions JsonSerializerOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
public WorkerAdapter(IWorkerBusinessLogicContract workerBusinessLogicContract, ILogger<WorkerAdapter> logger)
|
||||
{
|
||||
_buyerBusinessLogicContract = workerBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<WorkerBindingModel, WorkerDataModel>();
|
||||
cfg.CreateMap<WorkerDataModel, WorkerViewModel>()
|
||||
.ForMember(x => x.Configuration, x => x.MapFrom(src => JsonSerializer.Serialize(src.ConfigurationModel, JsonSerializerOptions)));
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public WorkerOperationResponse GetList(bool includeDeleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
return WorkerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllWorkers(!includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return WorkerOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return WorkerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return WorkerOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public WorkerOperationResponse GetPostList(string id, bool includeDeleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
return WorkerOperationResponse.OK([.. _buyerBusinessLogicContract.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([.. _buyerBusinessLogicContract.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([.. _buyerBusinessLogicContract.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>(_buyerBusinessLogicContract.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
|
||||
{
|
||||
_buyerBusinessLogicContract.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
|
||||
{
|
||||
_buyerBusinessLogicContract.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
|
||||
{
|
||||
_buyerBusinessLogicContract.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);
|
||||
}
|
||||
}
|
||||
}
|
||||
12
FurnitureAssembly/FurnitureAssemblyWebApi/AuthOptions.cs
Normal file
12
FurnitureAssembly/FurnitureAssemblyWebApi/AuthOptions.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.Text;
|
||||
|
||||
namespace FurnitureAssemblyWebApi;
|
||||
|
||||
public class AuthOptions
|
||||
{
|
||||
public const string ISSUER = "FurnitureAssemly_AuthServer"; // издатель токена
|
||||
public const string AUDIENCE = "FurnitureAssemly_AuthClient"; // потребитель токена
|
||||
const string KEY = "catsecret_secretsecretsecretkey!123"; // ключ для шифрации
|
||||
public static SymmetricSecurityKey GetSymmetricSecurityKey() => new(Encoding.UTF8.GetBytes(KEY));
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
using FurnitureAssemblyContracts.AdapterContracts;
|
||||
using FurnitureAssemblyContracts.BindingModels;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace FurnitureAssemblyWebApi.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
public class ComponentsController(IComponentAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly IComponentAdapter _adapter = adapter;
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetAllComponents()
|
||||
{
|
||||
return _adapter.GetAllComponents().GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet("{data}")]
|
||||
public IActionResult GetComponentByData(string data)
|
||||
{
|
||||
return _adapter.GetComponentByData(data).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public IActionResult Register([FromBody] ComponentBindingModel componentBindingModel)
|
||||
{
|
||||
return _adapter.InsertComponent(componentBindingModel).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPut]
|
||||
public IActionResult ChangeInfo([FromBody] ComponentBindingModel componentBindingModel)
|
||||
{
|
||||
return _adapter.UpdateComponent(componentBindingModel).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult DeleteComponent(string id)
|
||||
{
|
||||
if (string.IsNullOrEmpty(id))
|
||||
return BadRequest("Id is null or empty");
|
||||
|
||||
return _adapter.DeleteComponent(id).GetResponse(Request, Response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
using FurnitureAssemblyContracts.AdapterContracts;
|
||||
using FurnitureAssemblyContracts.BindingModels;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace FurnitureAssemblyWebApi.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
public class FurnitureController(IFurnitureAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly IFurnitureAdapter _adapter = adapter;
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetAll()
|
||||
{
|
||||
return _adapter.GetAllFurnitures().GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet("{data}")]
|
||||
public IActionResult GetComponentByData(string data)
|
||||
{
|
||||
return _adapter.GetFurnitureByData(data).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public IActionResult Register([FromBody] FurnitureBindingModel furnitureBindingModel)
|
||||
{
|
||||
return _adapter.InsertFurniture(furnitureBindingModel).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPut]
|
||||
public IActionResult ChangeInfo([FromBody] FurnitureBindingModel furnitureBindingModel)
|
||||
{
|
||||
return _adapter.UpdateFurniture(furnitureBindingModel).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult DeleteComponent(string id)
|
||||
{
|
||||
if (string.IsNullOrEmpty(id))
|
||||
return BadRequest("Id is null or empty");
|
||||
|
||||
return _adapter.DeleteFurniture(id).GetResponse(Request, Response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using FurnitureAssemblyContracts.AdapterContracts;
|
||||
using FurnitureAssemblyContracts.BindingModels;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace FurnitureAssemblyWebApi.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[Route("api/[controller]/[action]")]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
public class ManifacturingController(IManifacturingFurnitureAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly IManifacturingFurnitureAdapter _adapter = adapter;
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetRecords([FromQuery] DateTime fromDate, [FromQuery] DateTime toDate)
|
||||
{
|
||||
return _adapter.GetList(fromDate, toDate).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetWorkerRecords(string id, [FromQuery] DateTime fromDate, [FromQuery] DateTime toDate)
|
||||
{
|
||||
return _adapter.GetAllManifacturingByWorkerByPeriod(id, fromDate, toDate).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetFurnitureRecords(string id, [FromQuery] DateTime fromDate, [FromQuery] DateTime toDate)
|
||||
{
|
||||
return _adapter.GetAllManifacturingByFurnitureByPeriod(id, fromDate, toDate).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet("{data}")]
|
||||
public IActionResult GetRecord(string data)
|
||||
{
|
||||
return _adapter.GetElement(data).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public IActionResult RegisterManifacturing([FromBody] ManifacturingFurnitureBindingModel model)
|
||||
{
|
||||
return _adapter.RegisterManifacturingFurniture(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPut]
|
||||
public IActionResult ChangeManifacturing([FromBody] ManifacturingFurnitureBindingModel model)
|
||||
{
|
||||
return _adapter.ChangeManifacturingFurniture(model).GetResponse(Request, Response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using FurnitureAssemblyContracts.AdapterContracts;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace FurnitureAssemblyWebApi.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
public class PostHistoryController(IPostAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly IPostAdapter _adapter = adapter;
|
||||
|
||||
[HttpGet("{id}")]
|
||||
public IActionResult GetHistory(string id)
|
||||
{
|
||||
return _adapter.GetHistory(id).GetResponse(Request, Response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using FurnitureAssemblyContracts.AdapterContracts;
|
||||
using FurnitureAssemblyContracts.BindingModels;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace FurnitureAssemblyWebApi.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
public class PostsController(IPostAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly IPostAdapter _adapter = adapter;
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetRecords()
|
||||
{
|
||||
return _adapter.GetList().GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet("{data}")]
|
||||
public IActionResult GetRecord(string data)
|
||||
{
|
||||
return _adapter.GetElement(data).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public IActionResult Register([FromBody] PostBindingModel model)
|
||||
{
|
||||
return _adapter.RegisterPost(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPut]
|
||||
public IActionResult ChangeInfo([FromBody] PostBindingModel model)
|
||||
{
|
||||
return _adapter.ChangePostInfo(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult Delete(string id)
|
||||
{
|
||||
return _adapter.RemovePost(id).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPatch("{id}")]
|
||||
public IActionResult Restore(string id)
|
||||
{
|
||||
return _adapter.RestorePost(id).GetResponse(Request, Response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using FurnitureAssemblyContracts.AdapterContracts;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace FurnitureAssemblyWebApi.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[Route("api/[controller]/[action]")]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
public class SalariesController(ISalaryAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly ISalaryAdapter _adapter = adapter;
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetRecords(DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
return _adapter.GetListByPeriod(fromDate, toDate).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetWorkerRecords(string id, DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
return _adapter.GetListByPeriodByWorker(fromDate, toDate, id).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public IActionResult Calculate(DateTime date)
|
||||
{
|
||||
return _adapter.CalculateSalary(date).GetResponse(Request, Response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using FurnitureAssemblyContracts.AdapterContracts;
|
||||
using FurnitureAssemblyContracts.BindingModels;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace FurnitureAssemblyWebApi.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[Route("api/[controller]/[action]")]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
public class WorkersController(IWorkerAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly IWorkerAdapter _adapter = adapter;
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetRecords(bool includeDeleted = false)
|
||||
{
|
||||
return _adapter.GetList(includeDeleted).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetPostRecords(string id, bool includeDeleted = false)
|
||||
{
|
||||
return _adapter.GetPostList(id, includeDeleted).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetBirthDateRecords(DateTime fromDate, DateTime toDate, bool includeDeleted = false)
|
||||
{
|
||||
return _adapter.GetListByBirthDate(fromDate, toDate, includeDeleted).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetEmploymentRecords(DateTime fromDate, DateTime toDate, bool includeDeleted = false)
|
||||
{
|
||||
return _adapter.GetListByEmploymentDate(fromDate, toDate, includeDeleted).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet("{data}")]
|
||||
public IActionResult GetRecord(string data)
|
||||
{
|
||||
return _adapter.GetElement(data).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public IActionResult Register([FromBody] WorkerBindingModel model)
|
||||
{
|
||||
return _adapter.RegisterWorker(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpPut]
|
||||
public IActionResult ChangeInfo([FromBody] WorkerBindingModel model)
|
||||
{
|
||||
return _adapter.ChangeWorkerInfo(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult Delete(string id)
|
||||
{
|
||||
return _adapter.RemoveWorker(id).GetResponse(Request, Response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.3" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.1" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.2">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\FurnitureAssemblyBusinessLogic\FurnitureAssemblyBusinessLogic.csproj" />
|
||||
<ProjectReference Include="..\FurnitureAssemblyContracts\FurnitureAssemblyContracts.csproj" />
|
||||
<ProjectReference Include="..\FurnitureAssemblyDatebase\FurnitureAssemblyDatebase.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="FurnitureAssemblyTests" />
|
||||
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Update="appsettings.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,6 @@
|
||||
@FurnitureAssemblyWebApi_HostAddress = http://localhost:5269
|
||||
|
||||
GET {{FurnitureAssemblyWebApi_HostAddress}}/weatherforecast/
|
||||
Accept: application/json
|
||||
|
||||
###
|
||||
@@ -0,0 +1,12 @@
|
||||
using FurnitureAssemblyContracts.Infrastructure;
|
||||
|
||||
namespace FurnitureAssemblyWebApi.Infrastucture;
|
||||
|
||||
public class ConfigurationDatabase(IConfiguration configuration) : IConfigurationDatabase
|
||||
{
|
||||
private readonly Lazy<DataBaseSettings> _dataBaseSettings = new(() =>
|
||||
{
|
||||
return configuration.GetValue<DataBaseSettings>("DataBaseSettings") ?? throw new InvalidDataException(nameof(DataBaseSettings));
|
||||
});
|
||||
public string ConnectionString => _dataBaseSettings.Value.ConnectionString;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using FurnitureAssemblyContracts.Infrastructure;
|
||||
|
||||
namespace FurnitureAssemblyWebApi.Infrastucture;
|
||||
|
||||
public class ConfigurationSalary(IConfiguration configuration) : IConfigurationSalary
|
||||
{
|
||||
private readonly Lazy<SalarySettings> _salarySettings = new(() =>
|
||||
{
|
||||
var settings = configuration.GetSection("SalarySettings").Get<SalarySettings>();
|
||||
return settings ?? throw new InvalidDataException("SalarySettings configuration section is missing or invalid");
|
||||
});
|
||||
|
||||
public double ExtraMadeSum => _salarySettings.Value.ExtraMadeSum;
|
||||
|
||||
public int MaxConcurrentThreads => _salarySettings.Value.MaxConcurrentThreads;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user