Compare commits
10 Commits
LabWork02_
...
LabWork04_
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c26b7017dc | ||
|
|
d725cfc544 | ||
|
|
0c05d06346 | ||
|
|
806490a3a4 | ||
|
|
1f354d36bc | ||
|
|
1217527e35 | ||
|
|
56ac4a9851 | ||
|
|
9bc7da62f9 | ||
|
|
2e1379fdc0 | ||
|
|
e9d39370c8 |
@@ -9,6 +9,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FurnitureAssemblyTests", "F
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FurnitureAssemblyBusinessLogic", "FurnitureAssemblyBusinessLogic\FurnitureAssemblyBusinessLogic.csproj", "{698BF48B-C9AC-4684-8150-52E8148F15A0}"
|
||||
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
|
||||
@@ -27,6 +31,14 @@ Global
|
||||
{698BF48B-C9AC-4684-8150-52E8148F15A0}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{698BF48B-C9AC-4684-8150-52E8148F15A0}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{698BF48B-C9AC-4684-8150-52E8148F15A0}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{BDE6EBBB-E735-408D-B34B-490C2AE9201B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{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)
|
||||
|
||||
@@ -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,10 @@
|
||||
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; }
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -5,13 +5,13 @@ using FurnitureAssemblyContracts.Infrastructure;
|
||||
|
||||
namespace FurnitureAssemblyContracts.DataModels;
|
||||
|
||||
public class ComponentDataModel(string id, string name, ComponentType componentType, string? prevName = null, string? prevPrevName = null) : IValidation
|
||||
public class ComponentDataModel(string id, string name, ComponentType type, string? prevName = null, string? prevPrevName = null) : IValidation
|
||||
{
|
||||
public string Id { get; private set; } = id;
|
||||
public string Name { get; private set; } = name;
|
||||
public string? PrevName { get; private set; } = prevName;
|
||||
public string? PrevPrevName { get; private set; } = prevPrevName;
|
||||
public ComponentType Type { get; private set; } = componentType;
|
||||
public ComponentType Type { get; private set; } = type;
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
|
||||
@@ -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 id, string postName, PostType postType, double salary, bool isActual, DateTime changeDate) : IValidation
|
||||
public class PostDataModel(string postid, string postName, PostType postType, double salary) : IValidation
|
||||
{
|
||||
public string Id { get; private set; } = id;
|
||||
public string Id { get; private set; } = postid;
|
||||
public string PostName { get; private set; } = postName;
|
||||
public PostType PostType { get; private set; } = postType;
|
||||
public double Salary { get; private set; } = salary;
|
||||
public bool IsActual { get; private set; } = isActual;
|
||||
public DateTime ChangeDate { get; private set; } = changeDate;
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
|
||||
@@ -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()
|
||||
{
|
||||
|
||||
@@ -7,32 +7,56 @@ namespace FurnitureAssemblyContracts.DataModels;
|
||||
|
||||
public class WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted) : IValidation
|
||||
{
|
||||
private readonly PostDataModel? _post;
|
||||
|
||||
public string Id { get; private set; } = id;
|
||||
|
||||
public string FIO { get; private set; } = fio;
|
||||
|
||||
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 WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted, PostDataModel post) : this(id, fio, postId, birthDate, employmentDate, isDeleted)
|
||||
{
|
||||
_post = post;
|
||||
}
|
||||
|
||||
public WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate) : this(id, fio, postId, birthDate, employmentDate, false) { }
|
||||
|
||||
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()})");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace FurnitureAssemblyContracts.Exceptions;
|
||||
|
||||
public class ElementDeletedException : Exception
|
||||
{
|
||||
public ElementDeletedException(string id) : base($"Cannot modify a deleted item(id: { id})") { }
|
||||
}
|
||||
@@ -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,7 @@
|
||||
namespace FurnitureAssemblyContracts.Infrastructure;
|
||||
|
||||
public interface IConfigurationDatabase
|
||||
{
|
||||
string ConnectionString { 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 };
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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,12 @@
|
||||
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; }
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoMapper" Version="14.0.0" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.2" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\FurnitureAssemblyContracts\FurnitureAssemblyContracts.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="FurnitureAssemblyTests" />
|
||||
<InternalVisibleTo Include="FurnitureAssemblyWebApi"/>
|
||||
<InternalsVisibleTo Include="DynamicProxyGenAssembly2"/>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,59 @@
|
||||
using FurnitureAssemblyContracts.Infrastructure;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace FurnitureAssemblyDatebase;
|
||||
|
||||
public class FurnitureAssemblyDbContext : DbContext
|
||||
{
|
||||
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)
|
||||
{
|
||||
optionsBuilder.UseNpgsql(_configurationDatabase?.ConnectionString, o
|
||||
=> o.SetPostgresVersion(12, 2));
|
||||
base.OnConfiguring(optionsBuilder);
|
||||
}
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
base.OnModelCreating(modelBuilder);
|
||||
|
||||
modelBuilder.Entity<Component>().HasIndex(x => x.Name).IsUnique();
|
||||
|
||||
modelBuilder.Entity<Furniture>().HasIndex(x => x.Name).IsUnique();
|
||||
|
||||
modelBuilder.Entity<Post>()
|
||||
.HasIndex(e => new { e.PostName, e.IsActual })
|
||||
.IsUnique()
|
||||
.HasFilter($"\"{nameof(Post.IsActual)}\" = TRUE");
|
||||
|
||||
modelBuilder.Entity<Post>()
|
||||
.HasIndex(e => new { e.PostId, e.IsActual })
|
||||
.IsUnique()
|
||||
.HasFilter($"\"{nameof(Post.IsActual)}\" = TRUE");
|
||||
|
||||
modelBuilder.Entity<FurnitureComponent>().HasKey(x => new { x.FurnitureId, x.ComponentId });
|
||||
|
||||
modelBuilder.Entity<FurnitureComponent>()
|
||||
.HasOne(fc => fc.Furniture)
|
||||
.WithMany(f => f.Components)
|
||||
.HasForeignKey(fc => fc.FurnitureId)
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
}
|
||||
|
||||
public DbSet<ManifacturingFurniture> Manufacturing { get; set; }
|
||||
public DbSet<Post> Posts { get; set; }
|
||||
public DbSet<Component> Components { get; set; }
|
||||
public DbSet<Salary> Salaries { get; set; }
|
||||
public DbSet<Furniture> Furnitures { get; set; }
|
||||
public DbSet<FurnitureComponent> FurnitureComponents { get; set; }
|
||||
public DbSet<Worker> Workers { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
using AutoMapper;
|
||||
using FurnitureAssemblyContracts.DataModels;
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using FurnitureAssemblyContracts.StoragesContracts;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Npgsql;
|
||||
|
||||
namespace FurnitureAssemblyDatebase.Implementations;
|
||||
|
||||
public class ComponentStorageContract : IComponentStorageContract
|
||||
{
|
||||
private readonly FurnitureAssemblyDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public ComponentStorageContract(FurnitureAssemblyDbContext dbContext)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.AddMaps(typeof(Component));
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<ComponentDataModel> GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return [.. _dbContext.Components.Select(x => _mapper.Map<ComponentDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public ComponentDataModel? GetElementById(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<ComponentDataModel>(GetComponentById(id));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public ComponentDataModel? GetElementByName(string name)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<ComponentDataModel>(_dbContext.Components.FirstOrDefault(x => x.Name == name));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public ComponentDataModel? GetElementByOldName(string name)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<ComponentDataModel>(_dbContext.Components.FirstOrDefault(x =>
|
||||
x.PrevName == name || x.PrevPrevName == name));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddElement(ComponentDataModel manufacturerDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_dbContext.Components.Add(_mapper.Map<Component>(manufacturerDataModel));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("Id", manufacturerDataModel.Id);
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Components_Name" })
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("Name", manufacturerDataModel.Name);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdElement(ComponentDataModel manufacturerDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
var element = GetComponentById(manufacturerDataModel.Id) ?? throw new ElementNotFoundException(manufacturerDataModel.Id);
|
||||
if (element.Name != manufacturerDataModel.Name)
|
||||
{
|
||||
element.PrevPrevName = element.PrevName;
|
||||
element.PrevName = element.Name;
|
||||
element.Name = manufacturerDataModel.Name;
|
||||
}
|
||||
if (element.Type != manufacturerDataModel.Type)
|
||||
{
|
||||
element.Type = manufacturerDataModel.Type;
|
||||
}
|
||||
_dbContext.Components.Update(element);
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (ElementNotFoundException)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Components_Name" })
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("Name", manufacturerDataModel.Name);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void DelElement(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var element = GetComponentById(id) ?? throw new ElementNotFoundException(id);
|
||||
_dbContext.Components.Remove(element);
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (ElementNotFoundException)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private Component? GetComponentById(string id) => _dbContext.Components.FirstOrDefault(x => x.Id == id);
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
using AutoMapper;
|
||||
using FurnitureAssemblyContracts.DataModels;
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using FurnitureAssemblyContracts.StoragesContracts;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Npgsql;
|
||||
|
||||
namespace FurnitureAssemblyDatebase;
|
||||
|
||||
public class FurnitureStorageContract : IFurnitureStorageContract
|
||||
{
|
||||
private readonly FurnitureAssemblyDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public FurnitureStorageContract(FurnitureAssemblyDbContext dbContext)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Furniture, FurnitureDataModel>();
|
||||
cfg.CreateMap<FurnitureDataModel, Furniture>();
|
||||
cfg.CreateMap<FurnitureComponent, FurnitureComponentDataModel>();
|
||||
cfg.CreateMap<FurnitureComponentDataModel, FurnitureComponent>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<FurnitureDataModel> GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return [.. _dbContext.Furnitures.Select(x => _mapper.Map<FurnitureDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public FurnitureDataModel GetElementById(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<FurnitureDataModel>(GetFurnitureById(id));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public FurnitureDataModel GetElementByName(string name)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<FurnitureDataModel>(_dbContext.Furnitures.FirstOrDefault(x => x.Name == name));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddElement(FurnitureDataModel furnitureDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_dbContext.Furnitures.Add(_mapper.Map<Furniture>(furnitureDataModel));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("Id", furnitureDataModel.Id);
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Furnitures_Name" })
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("Name", furnitureDataModel.Name);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdElement(FurnitureDataModel furnitureDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
var element = GetFurnitureById(furnitureDataModel.Id) ?? throw new ElementNotFoundException(furnitureDataModel.Id);
|
||||
_dbContext.Furnitures.Update(_mapper.Map(furnitureDataModel, element));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (ElementNotFoundException)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Furnitures_Name" })
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("Name", furnitureDataModel.Name);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void DelElement(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var element = GetFurnitureById(id) ?? throw new ElementNotFoundException(id);
|
||||
_dbContext.Furnitures.Remove(element);
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (ElementNotFoundException)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private Furniture? GetFurnitureById(string id) => _dbContext.Furnitures.FirstOrDefault(x => x.Id == id);
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
using AutoMapper;
|
||||
using FurnitureAssemblyContracts.DataModels;
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using FurnitureAssemblyContracts.StoragesContracts;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Npgsql;
|
||||
|
||||
namespace FurnitureAssemblyDatebase.Implementations;
|
||||
|
||||
public class ManifacturingStorageContract : IManifacturingStorageContract
|
||||
{
|
||||
private readonly FurnitureAssemblyDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public ManifacturingStorageContract(FurnitureAssemblyDbContext dbContext)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Worker, WorkerDataModel>();
|
||||
cfg.CreateMap<Furniture, FurnitureDataModel>();
|
||||
cfg.CreateMap<ManifacturingFurniture, ManifacturingFurnitureDataModel>();
|
||||
cfg.CreateMap<ManifacturingFurnitureDataModel, ManifacturingFurniture>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<ManifacturingFurnitureDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? workerId = null, string? furnitureId = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var query = _dbContext.Manufacturing.AsQueryable();
|
||||
if (startDate is not null && endDate is not null)
|
||||
{
|
||||
query = query.Where(x => x.ProductuionDate >= startDate && x.ProductuionDate < endDate);
|
||||
}
|
||||
if (workerId is not null)
|
||||
{
|
||||
query = query.Where(x => x.WorkerId == workerId);
|
||||
}
|
||||
if (furnitureId is not null)
|
||||
{
|
||||
query = query.Where(x => x.FurnitureId == furnitureId);
|
||||
}
|
||||
return [.. query.Select(x => _mapper.Map<ManifacturingFurnitureDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public ManifacturingFurnitureDataModel? GetElementById(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<ManifacturingFurnitureDataModel>(GetManifacturingById(id));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddElement(ManifacturingFurnitureDataModel manifacturingFurnitureDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_dbContext.Manufacturing.Add(_mapper.Map<ManifacturingFurniture>(manifacturingFurnitureDataModel));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdElement(ManifacturingFurnitureDataModel manifacturingFurnitureDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
var element = GetManifacturingById(manifacturingFurnitureDataModel.Id) ?? throw new ElementNotFoundException(manifacturingFurnitureDataModel.Id);
|
||||
_dbContext.Manufacturing.Update(_mapper.Map(manifacturingFurnitureDataModel, element));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (ElementNotFoundException)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Manifacturing_Id" })
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("PostId", manifacturingFurnitureDataModel.Id);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private ManifacturingFurniture? GetManifacturingById(string id) => _dbContext.Manufacturing.Include(x => x.Worker).Include(x => x.Furniture).FirstOrDefault(x => x.Id == id);
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
using AutoMapper;
|
||||
using FurnitureAssemblyContracts.DataModels;
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using FurnitureAssemblyContracts.StoragesContracts;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Npgsql;
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace FurnitureAssemblyDatebase.Implementations;
|
||||
|
||||
public class PostStorageContract : IPostStorageContract
|
||||
{
|
||||
private readonly FurnitureAssemblyDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public PostStorageContract(FurnitureAssemblyDbContext dbContext)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Post, PostDataModel>()
|
||||
.ForMember(x => x.Id, x => x.MapFrom(src =>
|
||||
src.PostId));
|
||||
cfg.CreateMap<PostDataModel, Post>()
|
||||
.ForMember(x => x.Id, x => x.Ignore())
|
||||
.ForMember(x => x.PostId, x => x.MapFrom(src => src.Id))
|
||||
.ForMember(x => x.IsActual, x => x.MapFrom(src => true))
|
||||
.ForMember(x => x.ChangeDate, x => x.MapFrom(src => DateTime.UtcNow));
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<PostDataModel> GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return [.._dbContext.Posts.Select(x => _mapper.Map<PostDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public PostDataModel? GetElementById(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostId == id && x.IsActual));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public PostDataModel? GetElementByName(string name)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostName == name && x.IsActual));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public List<PostDataModel> GetPostWithHistory(string postId)
|
||||
{
|
||||
try
|
||||
{
|
||||
return [.. _dbContext.Posts.Where(x => x.PostId == postId).Select(x => _mapper.Map<PostDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddElement(PostDataModel postDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_dbContext.Posts.Add(_mapper.Map<Post>(postDataModel));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("PostName", postDataModel.PostName);
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostId_IsActual" })
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("PostId", postDataModel.Id);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdElement(PostDataModel postDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
var transaction = _dbContext.Database.BeginTransaction();
|
||||
try
|
||||
{
|
||||
var element = GetPostById(postDataModel.Id) ?? throw new ElementNotFoundException(postDataModel.Id);
|
||||
if (!element.IsActual)
|
||||
{
|
||||
throw new
|
||||
ElementDeletedException(postDataModel.Id);
|
||||
}
|
||||
element.IsActual = false;
|
||||
_dbContext.SaveChanges();
|
||||
var newElement = _mapper.Map<Post>(postDataModel);
|
||||
_dbContext.Posts.Add(newElement);
|
||||
_dbContext.SaveChanges();
|
||||
transaction.Commit();
|
||||
}
|
||||
catch
|
||||
{
|
||||
transaction.Rollback();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("PostName", postDataModel.PostName);
|
||||
}
|
||||
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void DelElement(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var element = GetPostById(id) ?? throw new ElementNotFoundException(id);
|
||||
if (!element.IsActual)
|
||||
{
|
||||
throw new ElementDeletedException(id);
|
||||
}
|
||||
element.IsActual = false;
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public void ResElement(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var element = GetPostById(id) ?? throw new ElementNotFoundException(id);
|
||||
element.IsActual = true;
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private Post? GetPostById(string id) => _dbContext.Posts.Where(x => x.PostId == id).OrderByDescending(x => x.ChangeDate).FirstOrDefault();
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using AutoMapper;
|
||||
using FurnitureAssemblyContracts.DataModels;
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using FurnitureAssemblyContracts.StoragesContracts;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace FurnitureAssemblyDatebase.Implementations;
|
||||
|
||||
public class SalaryStorageContract : ISalaryStorageContract
|
||||
{
|
||||
private readonly FurnitureAssemblyDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public SalaryStorageContract(FurnitureAssemblyDbContext dbContext)
|
||||
{
|
||||
_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));
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
public List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? workerId = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
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);
|
||||
}
|
||||
return [.. query.Select(x => _mapper.Map<SalaryDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddElement(SalaryDataModel salaryDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_dbContext.Salaries.Add(_mapper.Map<Salary>(salaryDataModel));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
using AutoMapper;
|
||||
using FurnitureAssemblyContracts.DataModels;
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using FurnitureAssemblyContracts.StoragesContracts;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
|
||||
namespace FurnitureAssemblyDatebase.Implementations;
|
||||
|
||||
public class WorkerStorageContract : IWorkerStorageContract
|
||||
{
|
||||
private readonly FurnitureAssemblyDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public WorkerStorageContract(FurnitureAssemblyDbContext dbContext)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Post, PostDataModel>()
|
||||
.ForMember(x => x.Id, x => x.MapFrom(src => src.PostId));
|
||||
cfg.CreateMap<Worker, WorkerDataModel>();
|
||||
cfg.CreateMap<WorkerDataModel, Worker>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<WorkerDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var query = _dbContext.Workers.AsQueryable();
|
||||
if (onlyActive)
|
||||
{
|
||||
query = query.Where(x => !x.IsDeleted);
|
||||
}
|
||||
if (postId is not null)
|
||||
{
|
||||
query = query.Where(x => x.PostId == postId);
|
||||
}
|
||||
if (fromBirthDate is not null && toBirthDate is not null)
|
||||
{
|
||||
query = query.Where(x => x.BirthDate >= fromBirthDate && x.BirthDate <= toBirthDate);
|
||||
}
|
||||
if (fromEmploymentDate is not null && toEmploymentDate is not null)
|
||||
{
|
||||
query = query.Where(x => x.EmploymentDate >= fromEmploymentDate && x.EmploymentDate <= toEmploymentDate);
|
||||
}
|
||||
return [.. JoinPost(query).Select(x => _mapper.Map<WorkerDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public WorkerDataModel? GetElementById(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<WorkerDataModel>(GetWorkerById(id));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public WorkerDataModel? GetElementByFIO(string fio)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<WorkerDataModel>(AddPost(_dbContext.Workers.FirstOrDefault(x => x.FIO == fio && !x.IsDeleted)));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddElement(WorkerDataModel workerDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_dbContext.Workers.Add(_mapper.Map<Worker>(workerDataModel));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("Id", workerDataModel.Id);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdElement(WorkerDataModel workerDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
var element = GetWorkerById(workerDataModel.Id) ?? throw new ElementNotFoundException(workerDataModel.Id);
|
||||
_dbContext.Workers.Update(_mapper.Map(workerDataModel, element));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (ElementNotFoundException)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void DelElement(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var element = GetWorkerById(id) ?? throw new ElementNotFoundException(id);
|
||||
element.IsDeleted = true;
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (ElementNotFoundException)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
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));
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using AutoMapper;
|
||||
using FurnitureAssemblyContracts.DataModels;
|
||||
using FurnitureAssemblyContracts.Enums;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace FurnitureAssemblyDatebase.Models;
|
||||
|
||||
[AutoMap(typeof(ComponentDataModel), ReverseMap = true)]
|
||||
public class Component
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
public required string Name { get; set; }
|
||||
public string? PrevName { get; set; }
|
||||
public string? PrevPrevName { get; set; }
|
||||
public required ComponentType Type { get; set; }
|
||||
[ForeignKey("ComponentId")]
|
||||
public List<FurnitureComponent>? FurnitureComponents { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace FurnitureAssemblyDatebase.Models;
|
||||
|
||||
public class Furniture
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
public required string Name { get; set; }
|
||||
public int Weight { get; set; }
|
||||
[ForeignKey("FurnitureId")]
|
||||
public List<FurnitureComponent>? Components { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace FurnitureAssemblyDatebase.Models;
|
||||
|
||||
public class FurnitureComponent
|
||||
{
|
||||
public required string FurnitureId { get; set; }
|
||||
public required string ComponentId { get; set; }
|
||||
public int Count { get; set; }
|
||||
public Furniture? Furniture { get; set; }
|
||||
public Component? Component { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace FurnitureAssemblyDatebase.Models;
|
||||
|
||||
public class ManifacturingFurniture
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
public required string FurnitureId { get; set; }
|
||||
public int Count { get; set; }
|
||||
public DateTime ProductuionDate { get; set; }
|
||||
public required string WorkerId { get; set ; }
|
||||
public Furniture? Furniture { get; set; }
|
||||
public Worker? Worker { get; set; }
|
||||
}
|
||||
14
FurnitureAssembly/FurnitureAssemblyDatebase/Models/Post.cs
Normal file
14
FurnitureAssembly/FurnitureAssemblyDatebase/Models/Post.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
using FurnitureAssemblyContracts.Enums;
|
||||
|
||||
namespace FurnitureAssemblyDatebase.Models;
|
||||
|
||||
public class Post
|
||||
{
|
||||
public string Id { get; set; } = Guid.NewGuid().ToString();
|
||||
public required string PostId { get; set; }
|
||||
public required string PostName { get; set; }
|
||||
public PostType PostType { get; set; }
|
||||
public double Salary { get; set; }
|
||||
public bool IsActual { get; set; }
|
||||
public DateTime ChangeDate { get; set; }
|
||||
}
|
||||
10
FurnitureAssembly/FurnitureAssemblyDatebase/Models/Salary.cs
Normal file
10
FurnitureAssembly/FurnitureAssemblyDatebase/Models/Salary.cs
Normal file
@@ -0,0 +1,10 @@
|
||||
namespace FurnitureAssemblyDatebase.Models;
|
||||
|
||||
public class Salary
|
||||
{
|
||||
public string Id { get; set; } = Guid.NewGuid().ToString();
|
||||
public required string WorkerId { get; set; }
|
||||
public double WorkerSalary { get; set; }
|
||||
public DateTime SalaryDate { get; set; }
|
||||
public Worker? Worker { get; set; }
|
||||
}
|
||||
26
FurnitureAssembly/FurnitureAssemblyDatebase/Models/Worker.cs
Normal file
26
FurnitureAssembly/FurnitureAssemblyDatebase/Models/Worker.cs
Normal file
@@ -0,0 +1,26 @@
|
||||
using FurnitureAssemblyContracts.Enums;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace FurnitureAssemblyDatebase.Models;
|
||||
|
||||
public class Worker
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
public required string FIO { get; set; }
|
||||
public required string PostId { get; set; }
|
||||
public DateTime BirthDate { get; set; }
|
||||
public DateTime EmploymentDate { get; set; }
|
||||
public bool IsDeleted { get; set; }
|
||||
public DateTime ChangeDate { get; set; }
|
||||
[ForeignKey("WorkerId")]
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -190,7 +190,7 @@ internal class SalaryBuisnessLogicContractTests
|
||||
_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));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, postSalary));
|
||||
_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)]);
|
||||
var sum = 0.0;
|
||||
@@ -225,7 +225,7 @@ internal class SalaryBuisnessLogicContractTests
|
||||
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));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 2000));
|
||||
_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
|
||||
@@ -243,7 +243,7 @@ internal class SalaryBuisnessLogicContractTests
|
||||
_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));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, postSalary));
|
||||
_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)]);
|
||||
var sum = 0.0;
|
||||
@@ -265,7 +265,7 @@ internal class SalaryBuisnessLogicContractTests
|
||||
//Arrange
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 2000, true, DateTime.UtcNow));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 2000));
|
||||
_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
|
||||
@@ -293,7 +293,7 @@ internal class SalaryBuisnessLogicContractTests
|
||||
_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));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 2000));
|
||||
//Act&Assert
|
||||
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
|
||||
}
|
||||
@@ -306,7 +306,7 @@ internal class SalaryBuisnessLogicContractTests
|
||||
_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));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 2000));
|
||||
_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
|
||||
@@ -336,7 +336,7 @@ internal class SalaryBuisnessLogicContractTests
|
||||
_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));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 2000));
|
||||
_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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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" />
|
||||
@@ -20,6 +29,8 @@
|
||||
<ItemGroup>
|
||||
<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,8 @@
|
||||
using FurnitureAssemblyContracts.Infrastructure;
|
||||
|
||||
namespace FurnitureAssemblyTests.Infrastructure;
|
||||
|
||||
public class ConfigurationDateBaseTest : IConfigurationDatabase
|
||||
{
|
||||
public string ConnectionString => "Host=127.0.0.1;Port=5432;Database=furnitureassemblytest;";
|
||||
}
|
||||
@@ -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,80 @@
|
||||
using FurnitureAssemblyContracts.Enums;
|
||||
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, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false)
|
||||
{
|
||||
var worker = new Worker() { Id = id ?? Guid.NewGuid().ToString(), FIO = fio, PostId = postId ?? Guid.NewGuid().ToString(), BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-20), EmploymentDate = employmentDate ?? DateTime.UtcNow, IsDeleted = isDeleted };
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using FurnitureAssemblyDatebase;
|
||||
using FurnitureAssemblyTests.Infrastructure;
|
||||
|
||||
namespace FurnitureAssemblyTests.StorageContractTests;
|
||||
|
||||
internal abstract class BaseStorageContractTest
|
||||
{
|
||||
protected FurnitureAssemblyDbContext FurnitureAssemblyDbContext { get; private set; }
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
FurnitureAssemblyDbContext = new FurnitureAssemblyDbContext(new ConfigurationDateBaseTest());
|
||||
FurnitureAssemblyDbContext.Database.EnsureDeleted();
|
||||
FurnitureAssemblyDbContext.Database.EnsureCreated();
|
||||
}
|
||||
|
||||
[OneTimeTearDown]
|
||||
public void OneTimeTearDown()
|
||||
{
|
||||
FurnitureAssemblyDbContext.Database.EnsureDeleted();
|
||||
FurnitureAssemblyDbContext.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
using FurnitureAssemblyContracts.DataModels;
|
||||
using FurnitureAssemblyContracts.Enums;
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using FurnitureAssemblyDatebase.Implementations;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using FurnitureAssemblyTests.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace FurnitureAssemblyTests.StorageContractTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class ComponentStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
private ComponentStorageContract _componentStorageContract;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_componentStorageContract = new ComponentStorageContract(FurnitureAssemblyDbContext);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
FurnitureAssemblyDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Components\" CASCADE; ");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
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));
|
||||
AssertElement(list.First(), component);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenNoRecords_Test()
|
||||
{
|
||||
var list = _componentStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var component = FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn();
|
||||
AssertElement(_componentStorageContract.GetElementById(component.Id), component);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn();
|
||||
Assert.That(() => _componentStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenHaveRecord_Test()
|
||||
{
|
||||
var component = FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn();
|
||||
AssertElement(_componentStorageContract.GetElementByName(component.Name), component);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenNoRecord_Test()
|
||||
{
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn();
|
||||
Assert.That(() => _componentStorageContract.GetElementByName("Non-existent Name"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByOldName_WhenHaveRecord_Test()
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByOldName_WhenNoRecord_Test()
|
||||
{
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn();
|
||||
Assert.That(() => _componentStorageContract.GetElementByOldName("Non-existent Old Name"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var component = CreateModel(Guid.NewGuid().ToString(), "New Component");
|
||||
_componentStorageContract.AddElement(component);
|
||||
AssertElement(FurnitureAssemblyDbContext.GetComponentFromDatabaseById(component.Id), component);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
|
||||
{
|
||||
var component = CreateModel(Guid.NewGuid().ToString(), "Unique Name");
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(component.Id);
|
||||
Assert.That(() => _componentStorageContract.AddElement(component), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var component = CreateModel(Guid.NewGuid().ToString(), "Duplicate Name");
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(Guid.NewGuid().ToString(), component.Name);
|
||||
Assert.That(() => _componentStorageContract.AddElement(component), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var component = CreateModel(Guid.NewGuid().ToString(), "Old Name", ComponentType.Panel, "Previous Name", "Old Name");
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(component.Id, name: component.Name!, type: component.Type!, prevName: component.PrevName!, prevPrevName: component.PrevPrevName!);
|
||||
_componentStorageContract.UpdElement(component);
|
||||
AssertElement(FurnitureAssemblyDbContext.GetComponentFromDatabaseById(component.Id), component);
|
||||
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenNoChangeName_Test()
|
||||
{
|
||||
var component = CreateModel(Guid.NewGuid().ToString(), "Same Name", ComponentType.Panel, "Previous Name", "Old Name");
|
||||
FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn(component.Id, component.Name, component.Type, component.PrevName, component.PrevPrevName);
|
||||
_componentStorageContract.UpdElement(component);
|
||||
AssertElement(FurnitureAssemblyDbContext.GetComponentFromDatabaseById(component.Id), component);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _componentStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var component = CreateModel(Guid.NewGuid().ToString(), "Duplicate 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 = FurnitureAssemblyDbContext.InsertComponentToDatabaseAndReturn();
|
||||
_componentStorageContract.DelElement(component.Id);
|
||||
var element = FurnitureAssemblyDbContext.GetComponentFromDatabaseById(component.Id);
|
||||
Assert.That(element, Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _componentStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private static void AssertElement(ComponentDataModel? 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.PrevName, Is.EqualTo(expected.PrevName));
|
||||
Assert.That(actual.PrevPrevName, Is.EqualTo(expected.PrevPrevName));
|
||||
Assert.That(actual.Type, Is.EqualTo(expected.Type));
|
||||
});
|
||||
}
|
||||
|
||||
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 static void AssertElement(Component? actual, ComponentDataModel 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.PrevName, Is.EqualTo(expected.PrevName));
|
||||
Assert.That(actual.PrevPrevName, Is.EqualTo(expected.PrevPrevName));
|
||||
Assert.That(actual.Type, Is.EqualTo(expected.Type));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
using FurnitureAssemblyContracts.DataModels;
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using FurnitureAssemblyDatebase;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using FurnitureAssemblyTests.Infrastructure;
|
||||
|
||||
namespace FurnitureAssemblyTests.StorageContractTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class FurnitureStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
private FurnitureStorageContract _furnitureStorageContract;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_furnitureStorageContract = new FurnitureStorageContract(FurnitureAssemblyDbContext);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
FurnitureAssemblyDbContext.RemoveFurnituresFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
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));
|
||||
AssertElement(list.First(), furniture);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenNoRecords_Test()
|
||||
{
|
||||
var list = _furnitureStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var furniture = FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn();
|
||||
AssertElement(_furnitureStorageContract.GetElementById(furniture.Id), furniture);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn();
|
||||
Assert.That(() => FurnitureAssemblyDbContext.GetFurnitureFromDatabaseById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenHaveRecord_Test()
|
||||
{
|
||||
var furniture = FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(name: "Unique Name");
|
||||
AssertElement(_furnitureStorageContract.GetElementByName(furniture.Name), furniture);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenNoRecord_Test()
|
||||
{
|
||||
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn();
|
||||
Assert.That(() => FurnitureAssemblyDbContext.GetFurnitureFromDatabaseById("Non-existent Name"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var furniture = CreateModel(Guid.NewGuid().ToString(), "New Furniture");
|
||||
_furnitureStorageContract.AddElement(furniture);
|
||||
AssertElement(FurnitureAssemblyDbContext.GetFurnitureFromDatabaseById(furniture.Id), furniture);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
|
||||
{
|
||||
var furniture = CreateModel(Guid.NewGuid().ToString(), "Unique Name");
|
||||
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(furniture.Id);
|
||||
Assert.That(() => _furnitureStorageContract.AddElement(furniture), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var furniture = CreateModel(Guid.NewGuid().ToString(), "Duplicate Name");
|
||||
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString(), furniture.Name);
|
||||
Assert.That(() => _furnitureStorageContract.AddElement(furniture), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var furniture = CreateModel(Guid.NewGuid().ToString(), "Old Name");
|
||||
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(furniture.Id, name: furniture.Name!);
|
||||
_furnitureStorageContract.UpdElement(furniture);
|
||||
AssertElement(FurnitureAssemblyDbContext.GetFurnitureFromDatabaseById(furniture.Id), furniture);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenNoChangeName_Test()
|
||||
{
|
||||
var furniture = CreateModel(Guid.NewGuid().ToString(), "Same Name");
|
||||
FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(furniture.Id, furniture.Name);
|
||||
_furnitureStorageContract.UpdElement(furniture);
|
||||
AssertElement(FurnitureAssemblyDbContext.GetFurnitureFromDatabaseById(furniture.Id), furniture);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _furnitureStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var furniture = CreateModel(Guid.NewGuid().ToString(), "Duplicate 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 = FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
_furnitureStorageContract.DelElement(furniture.Id);
|
||||
var element = FurnitureAssemblyDbContext.GetFurnitureFromDatabaseById(furniture.Id);
|
||||
Assert.That(element, Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _furnitureStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private static void AssertElement(FurnitureDataModel? 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));
|
||||
});
|
||||
}
|
||||
|
||||
private static FurnitureDataModel CreateModel(string id, string name = "test", int weight = 0)
|
||||
=> new(id, name, weight, []);
|
||||
|
||||
private static void AssertElement(Furniture? actual, FurnitureDataModel 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));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
using FurnitureAssemblyContracts.DataModels;
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using FurnitureAssemblyDatebase.Implementations;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using FurnitureAssemblyTests.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace FurnitureAssemblyTests.StorageContractTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class ManifacturingStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
private ManifacturingStorageContract _manifacturingStorageContract;
|
||||
private Worker _worker;
|
||||
private Furniture _furniture;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_manifacturingStorageContract = new ManifacturingStorageContract(FurnitureAssemblyDbContext);
|
||||
_worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
_furniture = FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn();
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
FurnitureAssemblyDbContext.RemoveComponentsFromDatabase();
|
||||
FurnitureAssemblyDbContext.RemoveFurnituresFromDatabase();
|
||||
FurnitureAssemblyDbContext.RemoveWorkersFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
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));
|
||||
AssertElement(list.First(), manufacturing);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenNoRecords_Test()
|
||||
{
|
||||
var list = _manifacturingStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByWorker_Test()
|
||||
{
|
||||
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));
|
||||
Assert.That(list.All(x => x.WorkerId == _worker.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByFurniture_Test()
|
||||
{
|
||||
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));
|
||||
Assert.That(list.All(x => x.FurnitureId == _furniture.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var manufacturing = FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, _furniture.Id);
|
||||
AssertElement(_manifacturingStorageContract.GetElementById(manufacturing.Id), manufacturing);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, _furniture.Id);
|
||||
Assert.That(() => _manifacturingStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var manufacturing = CreateModel(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
|
||||
_manifacturingStorageContract.AddElement(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);
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, _furniture.Id, id: manufacturing.Id);
|
||||
Assert.That(() => _manifacturingStorageContract.AddElement(manufacturing), Throws.TypeOf<StorageException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var manufacturing = CreateModel(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id);
|
||||
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(_worker.Id, _furniture.Id, id: manufacturing.Id);
|
||||
_manifacturingStorageContract.UpdElement(manufacturing);
|
||||
AssertElement(FurnitureAssemblyDbContext.GetManifacturingFromDatabaseById(manufacturing.Id), manufacturing);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _manifacturingStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString(), _furniture.Id, 5, _worker.Id)), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private static void AssertElement(ManifacturingFurnitureDataModel? actual, ManifacturingFurniture expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
|
||||
Assert.That(actual.Count, Is.EqualTo(expected.Count));
|
||||
Assert.That(actual.FurnitureId, Is.EqualTo(expected.FurnitureId));
|
||||
});
|
||||
}
|
||||
|
||||
private static ManifacturingFurnitureDataModel CreateModel(string id, string furnitureId, int count, string workerId)
|
||||
{
|
||||
return new(id, furnitureId, count, workerId);
|
||||
}
|
||||
|
||||
private static void AssertElement(ManifacturingFurniture? actual, ManifacturingFurnitureDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
|
||||
Assert.That(actual.Count, Is.EqualTo(expected.Count));
|
||||
Assert.That(actual.FurnitureId, Is.EqualTo(expected.FurnitureId));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
using FurnitureAssemblyContracts.DataModels;
|
||||
using FurnitureAssemblyContracts.Enums;
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using FurnitureAssemblyDatebase.Implementations;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using FurnitureAssemblyTests.Infrastructure;
|
||||
|
||||
namespace FurnitureAssemblyTests.StorageContractTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class PostStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
private PostStorageContract _postStorageContract;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_postStorageContract = new PostStorageContract(FurnitureAssemblyDbContext);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
FurnitureAssemblyDbContext.RemovePostsFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
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));
|
||||
AssertElement(list.First(x => x.Id == post.PostId), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenNoRecords_Test()
|
||||
{
|
||||
var list = _postStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetPostWithHistory_WhenHaveRecords_Test()
|
||||
{
|
||||
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);
|
||||
var list = _postStorageContract.GetPostWithHistory(postId);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetPostWithHistory_WhenNoRecords_Test()
|
||||
{
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
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));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn();
|
||||
AssertElement(_postStorageContract.GetElementById(post.PostId), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn();
|
||||
Assert.That(() => _postStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
Assert.That(() => _postStorageContract.GetElementById(post.PostId), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenTrySearchById_Test()
|
||||
{
|
||||
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn();
|
||||
Assert.That(() => _postStorageContract.GetElementById(post.Id), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenHaveRecord_Test()
|
||||
{
|
||||
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn();
|
||||
AssertElement(_postStorageContract.GetElementByName(post.PostName), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenNoRecord_Test()
|
||||
{
|
||||
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn();
|
||||
Assert.That(() => _postStorageContract.GetElementByName("name"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
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());
|
||||
_postStorageContract.AddElement(post);
|
||||
AssertElement(FurnitureAssemblyDbContext.GetPostFromDatabaseByPostId(post.Id), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
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_WhenHaveRecordWithSamePostId_Test()
|
||||
{
|
||||
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());
|
||||
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: true);
|
||||
_postStorageContract.UpdElement(post);
|
||||
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>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), "New Name");
|
||||
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());
|
||||
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: false);
|
||||
Assert.That(() => _postStorageContract.UpdElement(post), Throws.TypeOf<ElementDeletedException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(isActual: true);
|
||||
_postStorageContract.DelElement(post.PostId);
|
||||
Assert.That(FurnitureAssemblyDbContext.GetPostFromDatabaseByPostId(post.PostId), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _postStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
Assert.That(() => _postStorageContract.DelElement(post.PostId), Throws.TypeOf<ElementDeletedException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_ResElement_Test()
|
||||
{
|
||||
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
_postStorageContract.ResElement(post.PostId);
|
||||
var element = FurnitureAssemblyDbContext.GetPostFromDatabaseByPostId(post.PostId);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.That(element!.IsActual);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_ResElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _postStorageContract.ResElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_ResElement_WhenRecordNotWasDeleted_Test()
|
||||
{
|
||||
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(isActual: true);
|
||||
Assert.That(() => _postStorageContract.ResElement(post.PostId), Throws.Nothing);
|
||||
}
|
||||
|
||||
private static void AssertElement(PostDataModel? actual, Post expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.PostId));
|
||||
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
|
||||
Assert.That(actual.PostType, Is.EqualTo(expected.PostType));
|
||||
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
|
||||
});
|
||||
}
|
||||
|
||||
private static 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)
|
||||
{
|
||||
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, Is.EqualTo(expected.PostType));
|
||||
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
using FurnitureAssemblyContracts.DataModels;
|
||||
using FurnitureAssemblyDatebase;
|
||||
using FurnitureAssemblyDatebase.Implementations;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using FurnitureAssemblyTests.Infrastructure;
|
||||
|
||||
namespace FurnitureAssemblyTests.StorageContractTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class SalaryStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
private SalaryStorageContract _salaryStorageContract;
|
||||
private Worker _worker;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_salaryStorageContract = new SalaryStorageContract(FurnitureAssemblyDbContext);
|
||||
_worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
FurnitureAssemblyDbContext.RemoveWorkersFromDatabase();
|
||||
FurnitureAssemblyDbContext.RemoveSalariesFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
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.Single(x => x.Salary == salary.WorkerSalary), salary);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenNoRecords_Test()
|
||||
{
|
||||
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-10), DateTime.UtcNow.AddDays(10));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_OnlyInDatePeriod_Test()
|
||||
{
|
||||
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(() =>
|
||||
{
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByWorker_Test()
|
||||
{
|
||||
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);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
Assert.That(list.All(x => x.WorkerId == _worker.Id));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByWorkerOnlyInDatePeriod_Test()
|
||||
{
|
||||
var worker = InsertWorkerToDatabaseAndReturn("name 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), _worker.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
Assert.That(list.All(x => x.WorkerId == _worker.Id));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var salary = CreateModel(_worker.Id);
|
||||
_salaryStorageContract.AddElement(salary);
|
||||
AssertElement(FurnitureAssemblyDbContext.GetSalariesFromDatabaseByWorkerId(_worker.Id).FirstOrDefault(), 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 static void AssertElement(SalaryDataModel? actual, Salary expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
|
||||
Assert.That(actual.Salary, Is.EqualTo(expected.WorkerSalary));
|
||||
});
|
||||
}
|
||||
private static SalaryDataModel CreateModel(string workerId, double workerSalary = 1, DateTime? salaryDate = null)
|
||||
=> new(workerId, salaryDate ?? DateTime.UtcNow, workerSalary);
|
||||
|
||||
private static void AssertElement(Salary? actual, SalaryDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.WorkerId, Is.EqualTo(expected.WorkerId));
|
||||
Assert.That(actual.WorkerSalary, Is.EqualTo(expected.Salary));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
using FurnitureAssemblyContracts.DataModels;
|
||||
using FurnitureAssemblyContracts.Exceptions;
|
||||
using FurnitureAssemblyDatebase.Implementations;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using FurnitureAssemblyTests.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace FurnitureAssemblyTests.StorageContractTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class WorkerStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
private WorkerStorageContract _workerStorageContract;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_workerStorageContract = new WorkerStorageContract(FurnitureAssemblyDbContext);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
FurnitureAssemblyDbContext.RemoveWorkersFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
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(x => x.FIO == worker.FIO), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenNoRecords_Test()
|
||||
{
|
||||
var list = _workerStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByPostId_Test()
|
||||
{
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
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));
|
||||
Assert.That(list.All(x => x.PostId == postId));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByBirthDate_Test()
|
||||
{
|
||||
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));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByEmploymentDate_Test()
|
||||
{
|
||||
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));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByAllParameters_Test()
|
||||
{
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
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));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
AssertElement(_workerStorageContract.GetElementById(worker.Id), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
Assert.That(() => _workerStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByFIO_WhenHaveRecord_Test()
|
||||
{
|
||||
var worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
AssertElement(_workerStorageContract.GetElementByFIO(worker.FIO), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByFIO_WhenNoRecord_Test()
|
||||
{
|
||||
Assert.That(() => _workerStorageContract.GetElementByFIO("New Fio"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString());
|
||||
_workerStorageContract.AddElement(worker);
|
||||
AssertElement(FurnitureAssemblyDbContext.GetWorkerFromDatabaseById(worker.Id), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString());
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(worker.Id);
|
||||
Assert.That(() => _workerStorageContract.AddElement(worker), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString(), "New Fio");
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(worker.Id);
|
||||
_workerStorageContract.UpdElement(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>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenNoRecordWasDeleted_Test()
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString());
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(worker.Id, isDeleted: true);
|
||||
Assert.That(() => _workerStorageContract.UpdElement(worker), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
_workerStorageContract.DelElement(worker.Id);
|
||||
var element = FurnitureAssemblyDbContext.GetWorkerFromDatabaseById(worker.Id);
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.That(element.IsDeleted);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _workerStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenNoRecordWasDeleted_Test()
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString());
|
||||
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(worker.Id, isDeleted: true);
|
||||
Assert.That(() => _workerStorageContract.DelElement(worker.Id), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private static void AssertElement(WorkerDataModel? 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.FIO, Is.EqualTo(expected.FIO));
|
||||
Assert.That(actual.BirthDate, Is.EqualTo(expected.BirthDate));
|
||||
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 static void AssertElement(Worker? actual, WorkerDataModel 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, Is.EqualTo(expected.BirthDate));
|
||||
Assert.That(actual.EmploymentDate, Is.EqualTo(expected.EmploymentDate));
|
||||
Assert.That(actual.IsDeleted, 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,217 @@
|
||||
using FurnitureAssemblyContracts.ViewModels;
|
||||
using System.Net;
|
||||
using System;
|
||||
using FurnitureAssemblyTests.Infrastructure;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
|
||||
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(1000.5));
|
||||
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);
|
||||
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));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Calculate_PostNotFound_ShouldNotFound_Test()
|
||||
{
|
||||
//Arrange
|
||||
FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn();
|
||||
var worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "name", postId: Guid.NewGuid().ToString());
|
||||
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.NotFound));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,508 @@
|
||||
using FurnitureAssemblyContracts.BindingModels;
|
||||
using FurnitureAssemblyContracts.ViewModels;
|
||||
using FurnitureAssemblyDatebase.Models;
|
||||
using FurnitureAssemblyTests.Infrastructure;
|
||||
using System.Net;
|
||||
|
||||
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 };
|
||||
var workerModelWithFioIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = string.Empty, BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
var workerModelWithPostIdIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = "Id" };
|
||||
var workerModelWithBirthDateIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-15), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/workers/register", MakeContent(workerModelWithIdIncorrect));
|
||||
var responseWithFioIncorrect = await HttpClient.PostAsync($"/api/workers/register", MakeContent(workerModelWithFioIncorrect));
|
||||
var responseWithPostIdIncorrect = await HttpClient.PostAsync($"/api/workers/register", MakeContent(workerModelWithPostIdIncorrect));
|
||||
var responseWithBirthDateIncorrect = await HttpClient.PostAsync($"/api/workers/register", MakeContent(workerModelWithBirthDateIncorrect));
|
||||
//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");
|
||||
});
|
||||
}
|
||||
|
||||
[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 };
|
||||
var workerModelWithFioIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = string.Empty, BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
var workerModelWithPostIdIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-22), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = "Id" };
|
||||
var workerModelWithBirthDateIncorrect = new WorkerBindingModel { Id = Guid.NewGuid().ToString(), FIO = "fio", BirthDate = DateTime.UtcNow.AddYears(-15), EmploymentDate = DateTime.UtcNow.AddDays(-5), PostId = _post.Id };
|
||||
//Act
|
||||
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModelWithIdIncorrect));
|
||||
var responseWithFioIncorrect = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModelWithFioIncorrect));
|
||||
var responseWithPostIdIncorrect = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModelWithPostIdIncorrect));
|
||||
var responseWithBirthDateIncorrect = await HttpClient.PutAsync($"/api/workers/changeinfo", MakeContent(workerModelWithBirthDateIncorrect));
|
||||
//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");
|
||||
});
|
||||
}
|
||||
|
||||
[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));
|
||||
}
|
||||
|
||||
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));
|
||||
});
|
||||
}
|
||||
|
||||
private static WorkerBindingModel CreateModel(string postId, string? id = null, string fio = "Иванов И.И.", DateTime? birthDate = null, DateTime? employmentDate = null)
|
||||
{
|
||||
return new()
|
||||
{
|
||||
Id = id ?? Guid.NewGuid().ToString(),
|
||||
FIO = fio,
|
||||
BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-22),
|
||||
EmploymentDate = employmentDate ?? DateTime.UtcNow.AddDays(-5),
|
||||
PostId = postId
|
||||
};
|
||||
}
|
||||
|
||||
private static 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);
|
||||
});
|
||||
}
|
||||
}
|
||||
25
FurnitureAssembly/FurnitureAssemblyTests/appsettings.json
Normal file
25
FurnitureAssembly/FurnitureAssemblyTests/appsettings.json
Normal file
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"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": "*"
|
||||
}
|
||||
@@ -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,278 @@
|
||||
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 WorkerAdapter : IWorkerAdapter
|
||||
{
|
||||
private readonly IWorkerBusinessLogicContract _buyerBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public WorkerAdapter(IWorkerBusinessLogicContract workerBusinessLogicContract, ILogger<WorkerAdapter> logger)
|
||||
{
|
||||
_buyerBusinessLogicContract = workerBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<WorkerBindingModel, WorkerDataModel>();
|
||||
cfg.CreateMap<WorkerDataModel, WorkerViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
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,26 @@
|
||||
<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" />
|
||||
</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>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,6 @@
|
||||
@FurnitureAssemblyWebApi_HostAddress = http://localhost:5269
|
||||
|
||||
GET {{FurnitureAssemblyWebApi_HostAddress}}/weatherforecast/
|
||||
Accept: application/json
|
||||
|
||||
###
|
||||
@@ -0,0 +1,13 @@
|
||||
using FurnitureAssemblyContracts.Infrastructure;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
|
||||
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,6 @@
|
||||
namespace FurnitureAssemblyWebApi.Infrastucture;
|
||||
|
||||
public class DataBaseSettings
|
||||
{
|
||||
public required string ConnectionString { get; set; }
|
||||
}
|
||||
111
FurnitureAssembly/FurnitureAssemblyWebApi/Program.cs
Normal file
111
FurnitureAssembly/FurnitureAssemblyWebApi/Program.cs
Normal file
@@ -0,0 +1,111 @@
|
||||
using FurnitureAssemblyBusinessLogic.Implementations;
|
||||
using FurnitureAssemblyContracts.AdapterContracts;
|
||||
using FurnitureAssemblyContracts.BusinessLogicsContracts;
|
||||
using FurnitureAssemblyContracts.Infrastructure;
|
||||
using FurnitureAssemblyContracts.StoragesContracts;
|
||||
using FurnitureAssemblyDatebase;
|
||||
using FurnitureAssemblyDatebase.Implementations;
|
||||
using FurnitureAssemblyWebApi;
|
||||
using FurnitureAssemblyWebApi.Adapters;
|
||||
using FurnitureAssemblyWebApi.Infrastucture;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Serilog;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Add services to the container.
|
||||
|
||||
builder.Services.AddControllers();
|
||||
|
||||
using var loggerFactory = new LoggerFactory();
|
||||
loggerFactory.AddSerilog(new LoggerConfiguration().ReadFrom.Configuration(builder.Configuration).CreateLogger());
|
||||
builder.Services.AddSingleton(loggerFactory.CreateLogger("Any"));
|
||||
|
||||
builder.Services.AddAuthorization();
|
||||
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
|
||||
{
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>, <20><><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
ValidateIssuer = true,
|
||||
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>, <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
ValidIssuer = AuthOptions.ISSUER,
|
||||
// <20><><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
ValidateAudience = true,
|
||||
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
ValidAudience = AuthOptions.AUDIENCE,
|
||||
// <20><><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
ValidateLifetime = true,
|
||||
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(),
|
||||
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
ValidateIssuerSigningKey = true,
|
||||
};
|
||||
});
|
||||
|
||||
builder.Services.AddSingleton<IConfigurationDatabase, ConfigurationDatabase>();
|
||||
|
||||
builder.Services.AddTransient<IComponentBusinessLogicContract, ComponentBusinessLogicContract>();
|
||||
builder.Services.AddTransient<IFurnitureBusinessLogicContract, FurnitureBusinessLogicContract>();
|
||||
builder.Services.AddTransient<IManifacturingBusinessLogicContract, ManifacturingBusinessLogicContract>();
|
||||
builder.Services.AddTransient<IPostBusinessLogicContract, PostBusinessLogicContract>();
|
||||
builder.Services.AddTransient<ISalaryBusinessLogicContract, SalaryBusinessLogicContract>();
|
||||
builder.Services.AddTransient<IWorkerBusinessLogicContract, WorkerBusinessLogicContract>();
|
||||
|
||||
builder.Services.AddTransient<FurnitureAssemblyDbContext>();
|
||||
builder.Services.AddTransient<IComponentStorageContract, ComponentStorageContract>();
|
||||
builder.Services.AddTransient<IFurnitureStorageContract, FurnitureStorageContract>();
|
||||
builder.Services.AddTransient<IManifacturingStorageContract, ManifacturingStorageContract>();
|
||||
builder.Services.AddTransient<IPostStorageContract, PostStorageContract>();
|
||||
builder.Services.AddTransient<ISalaryStorageContract, SalaryStorageContract>();
|
||||
builder.Services.AddTransient<IWorkerStorageContract, WorkerStorageContract>();
|
||||
|
||||
builder.Services.AddTransient<IPostAdapter, PostAdapter>();
|
||||
builder.Services.AddTransient<IWorkerAdapter, WorkerAdapter>();
|
||||
builder.Services.AddTransient<IComponentAdapter, ComponentAdapter>();
|
||||
builder.Services.AddTransient<IFurnitureAdapter, FurnitureAdapter>();
|
||||
builder.Services.AddTransient<IManifacturingFurnitureAdapter, ManifacturingFurnitureAdapter>();
|
||||
builder.Services.AddTransient<ISalaryAdapter, SalaryAdapter>();
|
||||
|
||||
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
|
||||
builder.Services.AddOpenApi();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.MapOpenApi();
|
||||
}
|
||||
if (app.Environment.IsProduction())
|
||||
{
|
||||
var dbContext = app.Services.GetRequiredService<FurnitureAssemblyDbContext>();
|
||||
if (dbContext.Database.CanConnect())
|
||||
{
|
||||
dbContext.Database.EnsureCreated();
|
||||
dbContext.Database.Migrate();
|
||||
}
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
app.Map("/login/{username}", (string username) =>
|
||||
{
|
||||
return new JwtSecurityTokenHandler().WriteToken(new JwtSecurityToken(
|
||||
issuer: AuthOptions.ISSUER,
|
||||
audience: AuthOptions.AUDIENCE,
|
||||
claims: [new(ClaimTypes.Name, username)],
|
||||
expires: DateTime.UtcNow.Add(TimeSpan.FromMinutes(2)),
|
||||
signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)));
|
||||
});
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
app.Run();
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json",
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "http://localhost:5269",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "https://localhost:7283;http://localhost:5269",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
25
FurnitureAssembly/FurnitureAssemblyWebApi/appsettings.json
Normal file
25
FurnitureAssembly/FurnitureAssemblyWebApi/appsettings.json
Normal file
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"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": "*"
|
||||
}
|
||||
Reference in New Issue
Block a user