20 Commits

Author SHA1 Message Date
b1a49bfde3 calculate salaryyy 2025-04-18 00:57:59 +04:00
9f03eaa09e changes in worker 2025-04-17 22:57:21 +04:00
1b8b1a06f8 first migration 2025-04-17 18:07:41 +04:00
fddb9c9d83 lab_4 complete 2025-04-10 09:07:45 +04:00
5e249e488c допилы тестов 2025-04-09 15:46:21 +04:00
bd0c52b9f1 somechanges 2025-03-27 10:52:50 +04:00
e1e8d23bd0 80% Готово 2025-03-27 06:55:34 +04:00
d3bf4eec43 Часть тестов реализована + добавление api и куча всего 2025-03-27 02:56:00 +04:00
abbfe117f9 допил аттрибутов automap 2025-03-13 09:50:33 +04:00
8bdc9275d5 all done 2025-03-12 22:39:58 +04:00
65a03714a2 contracts_db 2025-03-12 19:36:30 +04:00
2ee47af951 db_context 2025-03-12 16:59:45 +04:00
cf45ffb67d project_db + models 2025-03-12 16:35:56 +04:00
9c06125d66 Реализации, the end. 2025-02-27 00:19:38 +04:00
fda7d01074 Тесты красной зоны 2025-02-26 23:19:10 +04:00
46f94f62b9 заготовки реализаций 2025-02-26 16:00:50 +04:00
af9e774126 new branch + contracts 2025-02-26 15:06:46 +04:00
5a5fc38cb6 all done 2025-02-13 09:05:34 +04:00
bca5c116a0 all tests and some changes 2025-02-12 21:08:09 +04:00
8150c8c96b models 2025-02-12 18:46:47 +04:00
156 changed files with 15615 additions and 1 deletions

View File

@@ -0,0 +1,68 @@
using SmallSoftwareContracts.BusinessLogicsContracts;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Extensions;
using System.Text.Json;
namespace SmallSoftwareBusinessLogic.Implementations;
internal class ManufacturerBusinessLogicContract(IManufacturerStorageContract
manufacturerStorageContract, ILogger logger) : IManufacturerBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IManufacturerStorageContract _manufacturerStorageContract
= manufacturerStorageContract;
public List<ManufacturerDataModel> GetAllManufacturers()
{
_logger.LogInformation("GetAllManufacturers");
return _manufacturerStorageContract.GetList() ?? throw new
NullListException();
}
public ManufacturerDataModel GetManufacturerByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _manufacturerStorageContract.GetElementById(data) ??
throw new ElementNotFoundException(data);
}
return _manufacturerStorageContract.GetElementByName(data) ??
_manufacturerStorageContract.GetElementByOldName(data) ??
throw new ElementNotFoundException(data);
}
public void InsertManufacturer(ManufacturerDataModel manufacturerDataModel)
{
_logger.LogInformation("New data: {json}",
JsonSerializer.Serialize(manufacturerDataModel));
ArgumentNullException.ThrowIfNull(manufacturerDataModel);
manufacturerDataModel.Validate();
_manufacturerStorageContract.AddElement(manufacturerDataModel);
}
public void UpdateManufacturer(ManufacturerDataModel manufacturerDataModel)
{
_logger.LogInformation("Update data: {json}",
JsonSerializer.Serialize(manufacturerDataModel));
ArgumentNullException.ThrowIfNull(manufacturerDataModel);
manufacturerDataModel.Validate();
_manufacturerStorageContract.UpdElement(manufacturerDataModel);
}
public void DeleteManufacturer(string id)
{
_logger.LogInformation("Delete by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_manufacturerStorageContract.DelElement(id);
}
}

View File

@@ -0,0 +1,100 @@
using Microsoft.Extensions.Logging;
using SmallSoftwareContracts.BusinessLogicsContracts;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Enums;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Extensions;
using SmallSoftwareContracts.StoragesContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace SmallSoftwareBusinessLogic.Implementations;
internal class PostBusinessLogicContract(IPostStorageContract
postStorageContract, ILogger logger) : IPostBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IPostStorageContract _postStorageContract =
postStorageContract;
public List<PostDataModel> GetAllPosts()
{
_logger.LogInformation("GetAllPosts");
return _postStorageContract.GetList() ?? throw new NullListException();
}
public List<PostDataModel> GetAllDataOfPost(string postId)
{
_logger.LogInformation("GetAllDataOfPost for {postId}", postId);
if (postId.IsEmpty())
{
throw new ArgumentNullException(nameof(postId));
}
if (!postId.IsGuid())
{
throw new ValidationException("The value in the field postId is not a unique identifier.");
}
return _postStorageContract.GetPostWithHistory(postId) ?? throw new
NullListException();
}
public PostDataModel GetPostByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _postStorageContract.GetElementById(data) ?? throw new
ElementNotFoundException(data);
}
return _postStorageContract.GetElementByName(data) ?? throw new
ElementNotFoundException(data);
}
public void InsertPost(PostDataModel postDataModel)
{
_logger.LogInformation("New data: {json}",
JsonSerializer.Serialize(postDataModel));
ArgumentNullException.ThrowIfNull(postDataModel);
postDataModel.Validate();
_postStorageContract.AddElement(postDataModel);
}
public void UpdatePost(PostDataModel postDataModel)
{
_logger.LogInformation("Update data: {json}",
JsonSerializer.Serialize(postDataModel));
ArgumentNullException.ThrowIfNull(postDataModel);
postDataModel.Validate();
_postStorageContract.UpdElement(postDataModel);
}
public void DeletePost(string id)
{
_logger.LogInformation("Delete by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_postStorageContract.DelElement(id);
}
public void RestorePost(string id)
{
_logger.LogInformation("Restore by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_postStorageContract.ResElement(id);
}
}

View File

@@ -0,0 +1,108 @@
using Microsoft.Extensions.Logging;
using SmallSoftwareContracts.BusinessLogicsContracts;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Extensions;
using SmallSoftwareContracts.StoragesContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace SmallSoftwareBusinessLogic.Implementations;
internal class RequestBusinessLogicContract(IRequestStorageContract requestStorageContract, ILogger logger) : IRequestBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IRequestStorageContract _requestStorageContract =
requestStorageContract;
public List<RequestDataModel> GetAllRequestsByPeriod(DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllRequests params: {fromDate}, {toDate}", fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _requestStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
}
public List<RequestDataModel> GetAllRequestsByWorkerByPeriod(string workerId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllRequests params: {workerId}, {fromDate}, { toDate} ", workerId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (workerId.IsEmpty())
{
throw new ArgumentNullException(nameof(workerId));
}
if (!workerId.IsGuid())
{
throw new ValidationException("The value in the field workerId is not a unique identifier.");
}
return _requestStorageContract.GetList(fromDate, toDate, workerId:
workerId) ?? throw new NullListException();
}
public List<RequestDataModel> GetAllRequestsBySoftwareByPeriod(string softwareId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllRequests params: {softwareId}, {fromDate}, { toDate} ", softwareId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (softwareId.IsEmpty())
{
throw new ArgumentNullException(nameof(softwareId));
}
if (!softwareId.IsGuid())
{
throw new ValidationException("The value in the field softwareId is not a unique identifier.");
}
return _requestStorageContract.GetList(fromDate, toDate, softwareId:
softwareId) ?? throw new NullListException();
}
public RequestDataModel GetRequestByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (!data.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
return _requestStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
public void InsertRequest(RequestDataModel requestDataModel)
{
_logger.LogInformation("New data: {json}",
JsonSerializer.Serialize(requestDataModel));
ArgumentNullException.ThrowIfNull(requestDataModel);
requestDataModel.Validate();
_requestStorageContract.AddElement(requestDataModel);
}
public void CancelRequest(string id)
{
_logger.LogInformation("Cancel by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_requestStorageContract.DelElement(id);
}
}

View File

@@ -0,0 +1,144 @@
using Microsoft.Extensions.Logging;
using SmallSoftwareContracts.BusinessLogicsContracts;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Extensions;
using SmallSoftwareContracts.Infrastructure;
using SmallSoftwareContracts.Infrastructure.PostConfigurations;
using SmallSoftwareContracts.StoragesContracts;
namespace SmallSoftwareBusinessLogic.Implementations;
internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract,
IRequestStorageContract requestStorageContract, IPostStorageContract postStorageContract,
IWorkerStorageContract workerStorageContract, ILogger logger, IConfigurationSalary сonfiguration) : ISalaryBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISalaryStorageContract _salaryStorageContract = salaryStorageContract;
private readonly IRequestStorageContract _requestStorageContract = requestStorageContract;
private readonly IPostStorageContract _postStorageContract = postStorageContract;
private readonly IWorkerStorageContract _workerStorageContract = workerStorageContract;
private readonly IConfigurationSalary _salaryConfiguration = сonfiguration;
private readonly Lock _lockObject = new();
public List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate,
DateTime toDate)
{
_logger.LogInformation("GetAllSalaries params: {fromDate}, {toDate}",
fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _salaryStorageContract.GetList(fromDate, toDate) ?? throw new
NullListException();
}
public List<SalaryDataModel> GetAllSalariesByPeriodByWorker(DateTime
fromDate, DateTime toDate, string workerId)
{
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (workerId.IsEmpty())
{
throw new ArgumentNullException(nameof(workerId));
}
if (!workerId.IsGuid())
{
throw new ValidationException("The value in the field workerId is not a unique identifier.");
}
_logger.LogInformation("GetAllSalaries params: {fromDate}, {toDate}, { workerId} ", fromDate, toDate, workerId);
return _salaryStorageContract.GetList(fromDate, toDate, workerId) ??
throw new NullListException();
}
public void CalculateSalaryByMonth(DateTime date)
{
_logger.LogInformation("CalculateSalaryByMounth: {date}", date);
var startDate = new DateTime(date.Year, date.Month, 1);
var finishDate = new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month));
var workers = _workerStorageContract.GetList() ?? throw new NullListException();
foreach (var worker in workers)
{
var requests = _requestStorageContract.GetList(startDate, finishDate, workerId: worker.Id) ?? throw new NullListException();
var post = _postStorageContract.GetElementById(worker.PostId) ??
throw new NullListException();
var salary = worker.ConfigurationModel switch
{
null => 0,
CashierPostConfiguration cpc => CalculateSalaryForCashier(requests, startDate, finishDate, cpc),
SupervisorPostConfiguration spc => CalculateSalaryForSupervisor(startDate, finishDate, spc),
PostConfiguration pc => pc.Rate,
};
_logger.LogDebug("The employee {workerId} was paid a salary of {salary}", worker.Id, salary);
_salaryStorageContract.AddElement(new SalaryDataModel(worker.Id, finishDate, salary));
}
}
private double CalculateSalaryForCashier(List<RequestDataModel> requests, DateTime startDate, DateTime finishDate, CashierPostConfiguration config)
{
var parallelOptions = new ParallelOptions
{
MaxDegreeOfParallelism = _salaryConfiguration.MaxConcurrentThreads
};
double calcPercent = 0.0;
var dates = new List<DateTime>();
for (var date = startDate; date < finishDate; date = date.AddDays(1))
{
dates.Add(date);
}
Parallel.ForEach(dates, parallelOptions, date =>
{
var requestsInDay = requests.Where(x => x.RequestDate >= date && x.RequestDate < date.AddDays(1)).ToArray();
if (requestsInDay.Length > 0)
{
double dailySum = requestsInDay.Sum(x => x.Sum);
double dailyAverage = dailySum / requestsInDay.Length;
double dailyPercent = dailyAverage * config.SalePercent;
lock (_lockObject)
{
calcPercent += dailyPercent;
}
}
});
double bonus = 0;
try
{
bonus = requests
.AsParallel()
.WithDegreeOfParallelism(_salaryConfiguration.MaxConcurrentThreads)
.Where(x => x.Sum > _salaryConfiguration.ExtraSaleSum)
.Sum(x => x.Sum * config.BonusForExtraSales);
}
catch (AggregateException agEx)
{
foreach (var ex in agEx.InnerExceptions)
{
_logger.LogError(ex, "Error calculating bonus in cashier payroll");
}
return 0;
}
return config.Rate + calcPercent + bonus;
}
private double CalculateSalaryForSupervisor(DateTime startDate, DateTime finishDate, SupervisorPostConfiguration config)
{
try
{
return config.Rate + config.PersonalCountTrendPremium *
_workerStorageContract.GetWorkerTrend(startDate, finishDate);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error in the supervisor payroll process");
return 0;
}
}
}

View File

@@ -0,0 +1,100 @@
using Microsoft.Extensions.Logging;
using SmallSoftwareContracts.BusinessLogicsContracts;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Enums;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Extensions;
using SmallSoftwareContracts.StoragesContracts;
using System.Text.Json;
namespace SmallSoftwareBusinessLogic.Implementations;
internal class SoftwareBusinessLogicContract(ISoftwareStorageContract
softwareStorageContract, ILogger logger) : ISoftwareBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISoftwareStorageContract _softwareStorageContract =
softwareStorageContract;
public List<SoftwareDataModel> GetAllSoftwares(bool onlyActive)
{
_logger.LogInformation("GetAllSoftwares params: {onlyActive}", onlyActive);
return _softwareStorageContract.GetList(onlyActive) ?? throw new
NullListException();
}
public List<SoftwareDataModel> GetAllSoftwaresByManufacturer(string
manufacturerId, bool onlyActive = true)
{
if (manufacturerId.IsEmpty())
{
throw new ArgumentNullException(nameof(manufacturerId));
}
if (!manufacturerId.IsGuid())
{
throw new ValidationException("The value in the field manufacturerId is not a unique identifier.");
}
_logger.LogInformation("GetAllSoftwares params: {manufacturerId}, { onlyActive} ", manufacturerId, onlyActive);
return _softwareStorageContract.GetList(onlyActive, manufacturerId) ??
throw new NullListException();
}
public List<SoftwareHistoryDataModel> GetSoftwareHistoryBySoftware(string softwareId)
{
_logger.LogInformation("GetSoftwareHistoryBySoftware for {softwareId}", softwareId);
if (softwareId.IsEmpty())
{
throw new ArgumentNullException(nameof(softwareId));
}
if (!softwareId.IsGuid())
{
throw new ValidationException("The value in the field softwareId is not a unique identifier.");
}
return _softwareStorageContract.GetHistoryBySoftwareId(softwareId) ??
throw new NullListException();
}
public SoftwareDataModel GetSoftwareByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _softwareStorageContract.GetElementById(data) ?? throw
new ElementNotFoundException(data);
}
return _softwareStorageContract.GetElementByName(data) ?? throw new
ElementNotFoundException(data);
}
public void InsertSoftware(SoftwareDataModel softwareDataModel)
{
_logger.LogInformation("New data: {json}",
JsonSerializer.Serialize(softwareDataModel));
ArgumentNullException.ThrowIfNull(softwareDataModel);
softwareDataModel.Validate();
_softwareStorageContract.AddElement(softwareDataModel);
}
public void UpdateSoftware(SoftwareDataModel softwareDataModel)
{
_logger.LogInformation("Update data: {json}",
JsonSerializer.Serialize(softwareDataModel));
ArgumentNullException.ThrowIfNull(softwareDataModel);
softwareDataModel.Validate();
_softwareStorageContract.UpdElement(softwareDataModel);
}
public void DeleteSoftware(string id)
{
_logger.LogInformation("Delete by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_softwareStorageContract.DelElement(id);
}
}

View File

@@ -0,0 +1,110 @@
using Microsoft.Extensions.Logging;
using SmallSoftwareContracts.BusinessLogicsContracts;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Extensions;
using SmallSoftwareContracts.StoragesContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace SmallSoftwareBusinessLogic.Implementations;
internal class WorkerBusinessLogicContract(IWorkerStorageContract
workerStorageContract, ILogger logger) : IWorkerBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IWorkerStorageContract _workerStorageContract =
workerStorageContract;
public List<WorkerDataModel> GetAllWorkers(bool onlyActive = true)
{
_logger.LogInformation("GetAllWorkers params: {onlyActive}",
onlyActive);
return _workerStorageContract.GetList(onlyActive) ?? throw new
NullListException();
}
public List<WorkerDataModel> GetAllWorkersByPost(string postId, bool
onlyActive = true)
{
_logger.LogInformation("GetAllWorkers params: {postId}, { onlyActive},", postId, onlyActive);
if (postId.IsEmpty())
{
throw new ArgumentNullException(nameof(postId));
}
if (!postId.IsGuid())
{
throw new ValidationException("The value in the field postId is not a unique identifier.");
}
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);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _workerStorageContract.GetElementById(data) ?? throw
new ElementNotFoundException(data);
}
return _workerStorageContract.GetElementByFIO(data) ?? throw new
ElementNotFoundException(data);
}
public void InsertWorker(WorkerDataModel workerDataModel)
{
_logger.LogInformation("New data: {json}",
JsonSerializer.Serialize(workerDataModel));
ArgumentNullException.ThrowIfNull(workerDataModel);
workerDataModel.Validate();
_workerStorageContract.AddElement(workerDataModel);
}
public void UpdateWorker(WorkerDataModel workerDataModel)
{
_logger.LogInformation("Update data: {json}",
JsonSerializer.Serialize(workerDataModel));
ArgumentNullException.ThrowIfNull(workerDataModel);
workerDataModel.Validate();
_workerStorageContract.UpdElement(workerDataModel);
}
public void DeleteWorker(string id)
{
_logger.LogInformation("Delete by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_workerStorageContract.DelElement(id);
}
}

View File

@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.2" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="SmallSoftwareTests" />
<InternalsVisibleTo Include="SmallSoftwareWebApi" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SmallSoftwareContracts\SmallSoftwareContracts.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,18 @@
using SmallSoftwareContracts.AdapterContracts.OperationResponses;
using SmallSoftwareContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.AdapterContracts;
public interface IManufacturerAdapter
{
ManufacturerOperationResponse GetList();
ManufacturerOperationResponse GetElement(string data);
ManufacturerOperationResponse RegisterManufacturer(ManufacturerBindingModel manufacturerModel);
ManufacturerOperationResponse ChangeManufacturerInfo(ManufacturerBindingModel manufacturerModel);
ManufacturerOperationResponse RemoveManufacturer(string id);
}

View File

@@ -0,0 +1,15 @@
using SmallSoftwareContracts.AdapterContracts.OperationResponses;
using SmallSoftwareContracts.BindingModels;
namespace SmallSoftwareContracts.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);
}

View File

@@ -0,0 +1,22 @@
using SmallSoftwareContracts.AdapterContracts.OperationResponses;
using SmallSoftwareContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.AdapterContracts;
public interface IRequestAdapter
{
RequestOperationResponse GetList(DateTime fromDate, DateTime toDate);
RequestOperationResponse GetWorkerList(string id, DateTime fromDate, DateTime
toDate);
RequestOperationResponse GetSoftwareList(string id, DateTime fromDate, DateTime
toDate);
RequestOperationResponse GetElement(string id);
RequestOperationResponse MakeRequest(RequestBindingModel saleModel);
RequestOperationResponse CancelRequest(string id);
}

View File

@@ -0,0 +1,15 @@
using SmallSoftwareContracts.AdapterContracts.OperationResponses;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.AdapterContracts;
public interface ISalaryAdapter
{
SalaryOperationResponse GetListByPeriod(DateTime fromDate, DateTime toDate);
SalaryOperationResponse GetListByPeriodByWorker(DateTime fromDate, DateTime toDate, string workerId);
SalaryOperationResponse CalculateSalary(DateTime date);
}

View File

@@ -0,0 +1,18 @@
using SmallSoftwareContracts.AdapterContracts.OperationResponses;
using SmallSoftwareContracts.BindingModels;
namespace SmallSoftwareContracts.AdapterContracts;
public interface ISoftwareAdapter
{
SoftwareOperationResponse GetList(bool includeDeleted);
SoftwareOperationResponse GetManufacturerList(string id, bool
includeDeleted);
SoftwareOperationResponse GetHistory(string id);
SoftwareOperationResponse GetElement(string data);
SoftwareOperationResponse RegisterSoftware(SoftwareBindingModel productModel);
SoftwareOperationResponse ChangeSoftwareInfo(SoftwareBindingModel
productModel);
SoftwareOperationResponse RemoveSoftware(string id);
}

View File

@@ -0,0 +1,23 @@
using SmallSoftwareContracts.AdapterContracts.OperationResponses;
using SmallSoftwareContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.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);
}

View File

@@ -0,0 +1,25 @@
using SmallSoftwareContracts.Infrastructure;
using SmallSoftwareContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.AdapterContracts.OperationResponses;
public class ManufacturerOperationResponse : OperationResponse
{
public static ManufacturerOperationResponse OK(List<ManufacturerViewModel>
data) => OK<ManufacturerOperationResponse, List<ManufacturerViewModel>>(data);
public static ManufacturerOperationResponse OK(ManufacturerViewModel data)
=> OK<ManufacturerOperationResponse, ManufacturerViewModel>(data);
public static ManufacturerOperationResponse NoContent() =>
NoContent<ManufacturerOperationResponse>();
public static ManufacturerOperationResponse NotFound(string message) =>
NotFound<ManufacturerOperationResponse>(message);
public static ManufacturerOperationResponse BadRequest(string message) =>
BadRequest<ManufacturerOperationResponse>(message);
public static ManufacturerOperationResponse InternalServerError(string
message) => InternalServerError<ManufacturerOperationResponse>(message);
}

View File

@@ -0,0 +1,20 @@
using SmallSoftwareContracts.Infrastructure;
using SmallSoftwareContracts.ViewModels;
namespace SmallSoftwareContracts.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);
}

View File

@@ -0,0 +1,19 @@
using SmallSoftwareContracts.Infrastructure;
using SmallSoftwareContracts.ViewModels;
namespace SmallSoftwareContracts.AdapterContracts.OperationResponses;
public class RequestOperationResponse : OperationResponse
{
public static RequestOperationResponse OK(List<RequestViewModel> data) =>
OK<RequestOperationResponse, List<RequestViewModel>>(data);
public static RequestOperationResponse OK(RequestViewModel data) =>
OK<RequestOperationResponse, RequestViewModel>(data);
public static RequestOperationResponse NoContent() =>
NoContent<RequestOperationResponse>();
public static RequestOperationResponse NotFound(string message) =>
NotFound<RequestOperationResponse>(message);
public static RequestOperationResponse BadRequest(string message) =>
BadRequest<RequestOperationResponse>(message);
public static RequestOperationResponse InternalServerError(string message) =>
InternalServerError<RequestOperationResponse>(message);
}

View File

@@ -0,0 +1,18 @@
using SmallSoftwareContracts.Infrastructure;
using SmallSoftwareContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.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);
}

View File

@@ -0,0 +1,22 @@
using SmallSoftwareContracts.Infrastructure;
using SmallSoftwareContracts.ViewModels;
namespace SmallSoftwareContracts.AdapterContracts.OperationResponses;
public class SoftwareOperationResponse : OperationResponse
{
public static SoftwareOperationResponse OK(List<SoftwareViewModel> data) =>
OK<SoftwareOperationResponse, List<SoftwareViewModel>>(data);
public static SoftwareOperationResponse OK(List<SoftwareHistoryViewModel>
data) => OK<SoftwareOperationResponse, List<SoftwareHistoryViewModel>>(data);
public static SoftwareOperationResponse OK(SoftwareViewModel data) =>
OK<SoftwareOperationResponse, SoftwareViewModel>(data);
public static SoftwareOperationResponse NoContent() =>
NoContent<SoftwareOperationResponse>();
public static SoftwareOperationResponse NotFound(string message) =>
NotFound<SoftwareOperationResponse>(message);
public static SoftwareOperationResponse BadRequest(string message) =>
BadRequest<SoftwareOperationResponse>(message);
public static SoftwareOperationResponse InternalServerError(string message)
=> InternalServerError<SoftwareOperationResponse>(message);
}

View File

@@ -0,0 +1,24 @@
using SmallSoftwareContracts.Infrastructure;
using SmallSoftwareContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.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);
}

View File

@@ -0,0 +1,12 @@
namespace SmallSoftwareContracts.BindingModels;
public class InstallationRequestBindingModel
{
public string? SoftwareId { get; set; }
public string? RequestId { get; set; }
public int Count { get; set; }
public double Price { get; set; }
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.BindingModels;
public class ManufacturerBindingModel
{
public string? Id { get; set; }
public string? ManufacturerName { get; set; }
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.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; }
}

View File

@@ -0,0 +1,10 @@
using SmallSoftwareContracts.DataModels;
namespace SmallSoftwareContracts.BindingModels;
public class RequestBindingModel
{
public string? Id { get; set; }
public string? WorkerId { get; set; }
public List<InstallationRequestBindingModel>? Softwares { get; set; }
}

View File

@@ -0,0 +1,12 @@
using SmallSoftwareContracts.Enums;
namespace SmallSoftwareContracts.BindingModels;
public class SoftwareBindingModel
{
public string? Id { get; set; }
public string? SoftwareName { get; set; }
public string? SoftwareType { get; set; }
public string? ManufacturerId { get; set; }
public double Price { get; set; }
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.BindingModels;
public class WorkerBindingModel
{
public string? Id { get; set; }
public string? FIO { get; set; }
public string? PostId { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
public string? ConfigurationJson { get; set; }
}

View File

@@ -0,0 +1,17 @@
using SmallSoftwareContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.BusinessLogicsContracts;
public interface IManufacturerBusinessLogicContract
{
List<ManufacturerDataModel> GetAllManufacturers();
ManufacturerDataModel GetManufacturerByData(string data);
void InsertManufacturer(ManufacturerDataModel manufacturerDataModel);
void UpdateManufacturer(ManufacturerDataModel manufacturerDataModel);
void DeleteManufacturer(string id);
}

View File

@@ -0,0 +1,19 @@
using SmallSoftwareContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.BusinessLogicsContracts;
public interface IPostBusinessLogicContract
{
List<PostDataModel> GetAllPosts();
List<PostDataModel> GetAllDataOfPost(string postId);
PostDataModel GetPostByData(string data);
void InsertPost(PostDataModel postDataModel);
void UpdatePost(PostDataModel postDataModel);
void DeletePost(string id);
void RestorePost(string id);
}

View File

@@ -0,0 +1,19 @@
using SmallSoftwareContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.BusinessLogicsContracts;
public interface IRequestBusinessLogicContract
{
List<RequestDataModel> GetAllRequestsByPeriod(DateTime fromDate, DateTime toDate);
List<RequestDataModel> GetAllRequestsByWorkerByPeriod(string workerId, DateTime fromDate, DateTime toDate);
List<RequestDataModel> GetAllRequestsBySoftwareByPeriod(string softwareId, DateTime fromDate, DateTime toDate);
RequestDataModel GetRequestByData(string data);
void InsertRequest(RequestDataModel requestDataModel);
void CancelRequest(string id);
}

View File

@@ -0,0 +1,12 @@

using SmallSoftwareContracts.DataModels;
namespace SmallSoftwareContracts.BusinessLogicsContracts;
public interface ISalaryBusinessLogicContract
{
List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate);
List<SalaryDataModel> GetAllSalariesByPeriodByWorker(DateTime fromDate, DateTime toDate, string workerId);
void CalculateSalaryByMonth(DateTime date);
}

View File

@@ -0,0 +1,16 @@
using SmallSoftwareContracts.DataModels;
namespace SmallSoftwareContracts.BusinessLogicsContracts;
public interface ISoftwareBusinessLogicContract
{
List<SoftwareDataModel> GetAllSoftwares(bool onlyActive = true);
List<SoftwareDataModel> GetAllSoftwaresByManufacturer(string manufacturerId,
bool onlyActive = true);
List<SoftwareHistoryDataModel> GetSoftwareHistoryBySoftware(string softwareId);
SoftwareDataModel GetSoftwareByData(string data);
void InsertSoftware(SoftwareDataModel softwareDataModel);
void UpdateSoftware(SoftwareDataModel softwareDataModel);
void DeleteSoftware(string id);
}

View File

@@ -0,0 +1,17 @@
using SmallSoftwareContracts.DataModels;
namespace SmallSoftwareContracts.BusinessLogicsContracts;
public interface IWorkerBusinessLogicContract
{
List<WorkerDataModel> GetAllWorkers(bool onlyActive = true);
List<WorkerDataModel> GetAllWorkersByPost(string postId, bool onlyActive = true);
List<WorkerDataModel> GetAllWorkersByBirthDate(DateTime fromDate, DateTime toDate, bool onlyActive = true);
List<WorkerDataModel> GetAllWorkersByEmploymentDate(DateTime fromDate,
DateTime toDate, bool onlyActive = true);
WorkerDataModel GetWorkerByData(string data);
void InsertWorker(WorkerDataModel workerDataModel);
void UpdateWorker(WorkerDataModel workerDataModel);
void DeleteWorker(string id);
}

View File

@@ -0,0 +1,38 @@
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Extensions;
using SmallSoftwareContracts.Infrastructure;
namespace SmallSoftwareContracts.DataModels;
public class InstallationRequestDataModel(string softwareId, string requestId, int count, double price) : IValidation
{
private readonly SoftwareDataModel? _software;
public string SoftwareId { get; private set; } = softwareId;
public string RequestId { get; private set; } = requestId;
public int Count { get; private set; } = count;
public double Price { get; private set; } = price;
public string SoftwareName => _software?.SoftwareName ?? string.Empty;
public InstallationRequestDataModel(string saleId, string softwareId, int count, double price, SoftwareDataModel software) : this(saleId, softwareId, count, price)
{
_software = software;
}
public void Validate()
{
if (SoftwareId.IsEmpty())
throw new ValidationException("Field SoftwareId is empty");
if (!SoftwareId.IsGuid())
throw new ValidationException("The value in the field SoftwareId is not a unique identifier");
if (RequestId.IsEmpty())
throw new ValidationException("Field RequestId is empty");
if (!RequestId.IsGuid())
throw new ValidationException("The value in the field RequestId is not a unique identifier");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
if (Price <= 0)
throw new ValidationException("Field Price is less than or equal to 0");
}
}

View File

@@ -0,0 +1,30 @@
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Extensions;
using SmallSoftwareContracts.Infrastructure;
namespace SmallSoftwareContracts.DataModels;
public class ManufacturerDataModel(string id, string manufacturerName, string?
prevManufacturerName, string? prevPrevManufacturerName) : IValidation
{
public string Id { get; private set; } = id;
public string ManufacturerName { get; private set; } = manufacturerName;
public string? PrevManufacturerName { get; private set; } =
prevManufacturerName;
public string? PrevPrevManufacturerName { get; private set; } =
prevPrevManufacturerName;
public ManufacturerDataModel(string id, string manufacturerName) : this(id, manufacturerName, null, null){ }
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 (ManufacturerName.IsEmpty())
throw new ValidationException("Field ManufacturerName is empty");
}
}

View File

@@ -0,0 +1,28 @@
using SmallSoftwareContracts.Enums;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Extensions;
using SmallSoftwareContracts.Infrastructure;
namespace SmallSoftwareContracts.DataModels;
public class PostDataModel(string postId, string postName, PostType
postType, double salary) : IValidation
{
public string Id { get; private set; } = postId;
public string PostName { get; private set; } = postName;
public PostType PostType { get; private set; } = postType;
public double Salary { get; private set; } = salary;
public 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 (PostName.IsEmpty())
throw new ValidationException("Field PostName is empty");
if (PostType == PostType.None)
throw new ValidationException("Field PostType is empty");
if (Salary <= 0)
throw new ValidationException("Field Salary is empty");
}
}

View File

@@ -0,0 +1,60 @@
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Extensions;
using SmallSoftwareContracts.Infrastructure;
using System.Text.RegularExpressions;
using System.Xml;
namespace SmallSoftwareContracts.DataModels;
public class RequestDataModel : IValidation
{
private readonly WorkerDataModel? _worker;
public string Id { get; private set; }
public string WorkerId { get; private set; }
public DateTime RequestDate { get; private set; } = DateTime.UtcNow;
public string Email { get; private set; }
public double Sum { get; private set; }
public bool IsCancel { get; private set; }
public List<InstallationRequestDataModel>? Softwares { get; private set; }
public string WorkerFIO => _worker?.FIO ?? string.Empty;
public RequestDataModel(string id, string workerId, string email, bool isCancel, List<InstallationRequestDataModel> installationRequests, DateTime requestDate)
{
Id = id;
WorkerId = workerId;
Email = email;
IsCancel = isCancel;
Softwares = installationRequests;
Sum = Softwares?.Sum(x => x.Price * x.Count) ?? 0;
}
public RequestDataModel(string id, string workerId, string email, double sum, bool isCancel,
List<InstallationRequestDataModel> installationRequests, WorkerDataModel worker, DateTime requestDate)
: this(id, workerId, email, isCancel, installationRequests, requestDate)
{
Sum = sum;
_worker = worker;
}
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 (WorkerId.IsEmpty())
throw new ValidationException("Field WorkerId is empty");
if (!WorkerId.IsGuid())
throw new ValidationException("The value in the field WorkerId is not a unique identifier");
if (Sum <= 0)
throw new ValidationException("Field Sum is less than or equal to 0");
if ((Softwares?.Count ?? 0) == 0)
throw new ValidationException("The request must include products");
if (!Regex.IsMatch(Email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$"))
{
throw new ValidationException("Invalid email format");
}
}
}

View File

@@ -0,0 +1,31 @@
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Extensions;
using SmallSoftwareContracts.Infrastructure;
namespace SmallSoftwareContracts.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()
{
if (WorkerId.IsEmpty())
throw new ValidationException("Field WorkerId is empty");
if (!WorkerId.IsGuid())
throw new ValidationException("The value in the field WorkerId is not a unique identifier");
if (Salary <= 0)
throw new ValidationException("Field Salary is less than or equal to 0");
}
}

View File

@@ -0,0 +1,55 @@
using SmallSoftwareContracts.Enums;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Extensions;
using SmallSoftwareContracts.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace SmallSoftwareContracts.DataModels;
public class SoftwareDataModel(string id, string softwareName, SoftwareType softwareType, string manufacturerId, double price, bool isDeleted) : IValidation
{
private readonly ManufacturerDataModel? _manufacturer;
public string Id { get; private set; } = id;
public string SoftwareName { get; private set; } = softwareName;
public SoftwareType SoftwareType { get; private set; } = softwareType;
public string ManufacturerId { get; private set; } = manufacturerId;
public double Price { get; private set; } = price;
public bool IsDeleted { get; private set; } = isDeleted;
public string ManufacturerName => _manufacturer?.ManufacturerName ?? string.Empty;
public SoftwareDataModel(string id, string softwareName, SoftwareType
softwareType, string manufacturerId, double price, bool isDeleted,
ManufacturerDataModel manufacturer) : this(id, softwareName, softwareType,
manufacturerId, price, isDeleted)
{
_manufacturer = manufacturer;
}
public SoftwareDataModel(string id, string softwareName, SoftwareType
softwareType, string manufacturerId, double price) : this(id, softwareName,
softwareType, manufacturerId, price, 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 (SoftwareName.IsEmpty())
throw new ValidationException("Field SoftwareName is empty");
if (SoftwareType == SoftwareType.None)
throw new ValidationException("Field SoftwareType is empty");
if (ManufacturerId.IsEmpty())
throw new ValidationException("Field ManufacturerId is empty");
if (!ManufacturerId.IsGuid())
throw new ValidationException("The value in the field ManufacturerId is not a unique identifier");
if (Price <= 0)
throw new ValidationException("Field Price is less than or equal to 0");
}
}

View File

@@ -0,0 +1,37 @@
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Extensions;
using SmallSoftwareContracts.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.DataModels;
public class SoftwareHistoryDataModel(string softwareId, double oldPrice) : IValidation
{
private readonly SoftwareDataModel? _software;
public string SoftwareId { get; private set; } = softwareId;
public double OldPrice { get; private set; } = oldPrice;
public DateTime ChangeDate { get; private set; } = DateTime.UtcNow;
public string SoftwareName => _software?.SoftwareName ?? string.Empty;
public SoftwareHistoryDataModel(string softwareId, double oldPrice, DateTime
changeDate, SoftwareDataModel software) : this(softwareId, oldPrice)
{
ChangeDate = changeDate;
_software = software;
}
public void Validate()
{
if (SoftwareId.IsEmpty())
throw new ValidationException("Field SoftwareId is empty");
if (!SoftwareId.IsGuid())
throw new ValidationException("The value in the field SoftwareId is not a unique identifier");
if (OldPrice <= 0)
throw new ValidationException("Field OldPrice is less than or equal to 0");
}
}

View File

@@ -0,0 +1,72 @@
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Extensions;
using SmallSoftwareContracts.Infrastructure;
using SmallSoftwareContracts.Infrastructure.PostConfigurations;
namespace SmallSoftwareContracts.DataModels;
public class WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted, PostConfiguration configuration) : IValidation
{
private readonly PostDataModel? _post;
public string Id { get; private set; } = id;
public string FIO { get; private set; } = fio;
public string PostId { get; private set; } = postId;
public DateTime BirthDate { get; private set; } = birthDate;
public DateTime EmploymentDate { get; private set; } = employmentDate;
public bool IsDeleted { get; private set; } = isDeleted;
public string PostName => _post?.PostName ?? string.Empty;
public PostConfiguration ConfigurationModel { get; private set; } = configuration;
public WorkerDataModel(string id, string fio, string postId, DateTime
birthDate, DateTime employmentDate, bool isDeleted, PostDataModel post) :
this(id, fio, postId, birthDate, employmentDate, isDeleted, new PostConfiguration { Rate = 10 })
{
_post = post;
}
public WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate)
: this(id, fio, postId, birthDate, employmentDate, false, new PostConfiguration { Rate = 10 })
{ }
public WorkerDataModel(string id, string fio, string postId, DateTime
birthDate, DateTime employmentDate, string configurationJson) :
this(id, fio, postId, birthDate, employmentDate, false, new PostConfiguration { Rate = 10 })
{
var obj = JToken.Parse(configurationJson);
if (obj is not null)
{
ConfigurationModel = obj.Value<string>("Type") switch
{
nameof(CashierPostConfiguration) => JsonConvert.DeserializeObject<CashierPostConfiguration>(configurationJson)!,
nameof(SupervisorPostConfiguration) => JsonConvert.DeserializeObject<SupervisorPostConfiguration>(configurationJson)!,
_ => JsonConvert.DeserializeObject<PostConfiguration>(configurationJson)!,
};
}
}
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
if (FIO.IsEmpty())
throw new ValidationException("Field FIO is empty");
if (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(-16).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 < 16)
throw new ValidationException($"Minors cannot be hired (EmploymentDate - { EmploymentDate.ToShortDateString() }, BirthDate - { BirthDate.ToShortDateString()})");
if (ConfigurationModel is null)
throw new ValidationException("Field ConfigurationModel is not initialized");
if (ConfigurationModel!.Rate <= 0)
throw new ValidationException("Field Rate is less or equal zero");
}
}

View File

@@ -0,0 +1,10 @@
namespace SmallSoftwareContracts.Enums;
public enum PostType
{
None = 0,
Supervisor = 1,
CashierConsultant = 2,
SoftInstaller = 3
}

View File

@@ -0,0 +1,11 @@
namespace SmallSoftwareContracts.Enums;
public enum SoftwareType
{
None = 0,
Windows = 1,
Linux = 2,
MacOS = 3,
AudioDriver = 4,
GPUDriver = 5
}

View File

@@ -0,0 +1,5 @@
namespace SmallSoftwareContracts.Exceptions;
public class ElementDeletedException : Exception
{
public ElementDeletedException(string id) : base($"Cannot modify a deleted item(id: { id})") { }
}

View File

@@ -0,0 +1,13 @@

namespace SmallSoftwareContracts.Exceptions;
public class ElementExistsException : Exception
{
public string ParamName { get; private set; }
public string ParamValue { get; private set; }
public ElementExistsException(string paramName, string paramValue) :
base($"There is already an element with value{paramValue} of parameter { paramName}")
{
ParamName = paramName;
ParamValue = paramValue;
}
}

View File

@@ -0,0 +1,10 @@
namespace SmallSoftwareContracts.Exceptions;
public class ElementNotFoundException : Exception
{
public string Value { get; private set; }
public ElementNotFoundException(string value) : base($"Element not found at value = { value}")
{
Value = value;
}
}

View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace SmallSoftwareContracts.Exceptions;
public class IncorrectDatesException : Exception
{
public IncorrectDatesException(DateTime start, DateTime end) :
base($"The end date must be later than the start date..StartDate: { start: dd.MM.YYYY}.EndDate: {end:dd.MM.YYYY}") { }
}

View File

@@ -0,0 +1,7 @@

namespace SmallSoftwareContracts.Exceptions;
public class NullListException : Exception
{
public NullListException() : base("The returned list is null") { }
}

View File

@@ -0,0 +1,8 @@

namespace SmallSoftwareContracts.Exceptions;
public class StorageException : Exception
{
public StorageException(Exception ex) : base($"Error while working in storage: { ex.Message}", ex) { }
}

View File

@@ -0,0 +1,5 @@
namespace SmallSoftwareContracts.Exceptions;
public class ValidationException(string message) : Exception(message)
{
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.Extensions;
public static class DateTimeExtensions
{
public static bool IsDateNotOlder(this DateTime date, DateTime olderDate)
{
return date >= olderDate;
}
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.Extensions;
public static class StringExtensions
{
public static bool IsEmpty(this string str)
{
return string.IsNullOrWhiteSpace(str);
}
public static bool IsGuid(this string str)
{
return Guid.TryParse(str, out _);
}
}

View File

@@ -0,0 +1,6 @@
namespace SmallSoftwareContracts.Infrastructure;
public interface IConfigurationDatabase
{
string ConnectionString { get; }
}

View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.Infrastructure;
public interface IConfigurationSalary
{
double ExtraSaleSum { get; }
int MaxConcurrentThreads { get; }
}

View File

@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.Infrastructure;
public interface IValidation
{
void Validate();
}

View File

@@ -0,0 +1,48 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net;
namespace SmallSoftwareContracts.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
};
}

View File

@@ -0,0 +1,8 @@
namespace SmallSoftwareContracts.Infrastructure.PostConfigurations;
public class CashierPostConfiguration : PostConfiguration
{
public override string Type => nameof(CashierPostConfiguration);
public double SalePercent { get; set; }
public double BonusForExtraSales { get; set; }
}

View File

@@ -0,0 +1,6 @@
namespace SmallSoftwareContracts.Infrastructure.PostConfigurations;
public class PostConfiguration
{
public virtual string Type => nameof(PostConfiguration);
public double Rate { get; set; }
}

View File

@@ -0,0 +1,7 @@
namespace SmallSoftwareContracts.Infrastructure.PostConfigurations;
public class SupervisorPostConfiguration : PostConfiguration
{
public override string Type => nameof(SupervisorPostConfiguration);
public double PersonalCountTrendPremium { get; set; }
}

View File

@@ -6,4 +6,9 @@
<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>

View File

@@ -0,0 +1,15 @@
using SmallSoftwareContracts.DataModels;
namespace SmallSoftwareContracts.StoragesContracts;
public interface IManufacturerStorageContract
{
List<ManufacturerDataModel> GetList();
ManufacturerDataModel? GetElementById(string id);
ManufacturerDataModel? GetElementByName(string name);
ManufacturerDataModel? GetElementByOldName(string name);
void AddElement(ManufacturerDataModel manufacturerDataModel);
void UpdElement(ManufacturerDataModel manufacturerDataModel);
void DelElement(string id);
}

View File

@@ -0,0 +1,15 @@
using SmallSoftwareContracts.DataModels;
namespace SmallSoftwareContracts.StoragesContracts;
public interface IPostStorageContract
{
List<PostDataModel> GetList();
List<PostDataModel> GetPostWithHistory(string postId);
PostDataModel? GetElementById(string id);
PostDataModel? GetElementByName(string name);
void AddElement(PostDataModel postDataModel);
void UpdElement(PostDataModel postDataModel);
void DelElement(string id);
void ResElement(string id);
}

View File

@@ -0,0 +1,12 @@
using SmallSoftwareContracts.DataModels;
namespace SmallSoftwareContracts.StoragesContracts;
public interface IRequestStorageContract
{
List<RequestDataModel> GetList(DateTime? startDate = null,
DateTime? endDate = null, string? workerId = null, string? softwareId = null);
RequestDataModel? GetElementById(string id);
void AddElement(RequestDataModel requestDataModel);
void DelElement(string id);
}

View File

@@ -0,0 +1,10 @@
using SmallSoftwareContracts.DataModels;
namespace SmallSoftwareContracts.StoragesContracts;
public interface ISalaryStorageContract
{
List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? workerId = null);
void AddElement(SalaryDataModel salaryDataModel);
}

View File

@@ -0,0 +1,19 @@
using SmallSoftwareContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.StoragesContracts;
public interface ISoftwareStorageContract
{
List<SoftwareDataModel> GetList(bool onlyActive = true, string? manufacturerId = null);
List<SoftwareHistoryDataModel> GetHistoryBySoftwareId(string softwareId);
SoftwareDataModel? GetElementById(string id);
SoftwareDataModel? GetElementByName(string name);
void AddElement(SoftwareDataModel softwareDataModel);
void UpdElement(SoftwareDataModel softwareDataModel);
void DelElement(string id);
}

View File

@@ -0,0 +1,21 @@
using SmallSoftwareContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.StoragesContracts;
public interface IWorkerStorageContract
{
List<WorkerDataModel> GetList(bool onlyActive = true, string? postId =
null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime?
fromEmploymentDate = null, DateTime? toEmploymentDate = null);
WorkerDataModel? GetElementById(string id);
WorkerDataModel? GetElementByFIO(string fio);
void AddElement(WorkerDataModel workerDataModel);
void UpdElement(WorkerDataModel workerDataModel);
void DelElement(string id);
int GetWorkerTrend(DateTime fromPeriod, DateTime toPeriod);
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.ViewModels;
public class InstallationRequestViewModel
{
public required string SoftwareId { get; set; }
public required string SoftwareName { get; set; }
public int Count { get; set; }
public double Price { get; set; }
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.ViewModels;
public class ManufacturerViewModel
{
public required string Id { get; set; }
public required string ManufacturerName { get; set; }
public string? PrevManufacturerName { get; set; }
public string? PrevPrevManufacturerName { get; set; }
}

View File

@@ -0,0 +1,10 @@

namespace SmallSoftwareContracts.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; }
}

View File

@@ -0,0 +1,14 @@

namespace SmallSoftwareContracts.ViewModels;
public class RequestViewModel
{
public required string Id { get; set; }
public required string WorkerId { get; set; }
public required string WorkerFIO { get; set; }
public DateTime RequestDate { get; set; }
public double Sum { get; set; }
public bool IsCancel { get; set; }
public required List<InstallationRequestViewModel> Softwares { get; set; }
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.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; }
}

View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.ViewModels;
public class SoftwareHistoryViewModel
{
public required string SoftwareName { get; set; }
public double OldPrice { get; set; }
public DateTime ChangeDate { get; set; }
}

View File

@@ -0,0 +1,13 @@
namespace SmallSoftwareContracts.ViewModels;
public class SoftwareViewModel
{
public required string Id { get; set; }
public required string SoftwareName { get; set; }
public required string ManufacturerId { get; set; }
public required string ManufacturerName { get; set; }
public required string SoftwareType { get; set; }
public double Price { get; set; }
public bool IsDeleted { get; set; }
}

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareContracts.ViewModels;
public class WorkerViewModel
{
public required string Id { get; set; }
public required string FIO { get; set; }
public required string PostId { get; set; }
public required string PostName { get; set; }
public bool IsDeleted { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
public required string Configuration { get; set; }
}

View File

@@ -0,0 +1,13 @@
using SmallSoftwareContracts.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareDatabase;
class DefaultConfigurationDatabase : IConfigurationDatabase
{
public string ConnectionString => "";
}

View File

@@ -0,0 +1,166 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.StoragesContracts;
using SmallSoftwareDatabase.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareDatabase.Implementations;
internal class ManufacturerStorageContract : IManufacturerStorageContract
{
private readonly SmallSoftwareDbContext _dbContext;
private readonly Mapper _mapper;
public ManufacturerStorageContract(SmallSoftwareDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(Manufacturer));
});
_mapper = new Mapper(config);
}
public List<ManufacturerDataModel> GetList()
{
try
{
return [.. _dbContext.Manufacturers.Select(x => _mapper.Map<ManufacturerDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ManufacturerDataModel? GetElementById(string id)
{
try
{
return
_mapper.Map<ManufacturerDataModel>(GetManufacturerById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ManufacturerDataModel? GetElementByName(string name)
{
try
{
return
_mapper.Map<ManufacturerDataModel>(_dbContext.Manufacturers.FirstOrDefault(x => x.ManufacturerName == name));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ManufacturerDataModel? GetElementByOldName(string name)
{
try
{
return
_mapper.Map<ManufacturerDataModel>(_dbContext.Manufacturers.FirstOrDefault(x =>
x.PrevManufacturerName == name ||
x.PrevPrevManufacturerName == name));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(ManufacturerDataModel manufacturerDataModel)
{
try
{
_dbContext.Manufacturers.Add(_mapper.Map<Manufacturer>(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_Manufacturers_ManufacturerName" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("ManufacturerName",
manufacturerDataModel.ManufacturerName);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(ManufacturerDataModel manufacturerDataModel)
{
try
{
var element = GetManufacturerById(manufacturerDataModel.Id) ??
throw new ElementNotFoundException(manufacturerDataModel.Id);
if (element.ManufacturerName !=
manufacturerDataModel.ManufacturerName)
{
element.PrevPrevManufacturerName =
element.PrevManufacturerName;
element.PrevManufacturerName = element.ManufacturerName;
element.ManufacturerName =
manufacturerDataModel.ManufacturerName;
}
_dbContext.Manufacturers.Update(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (DbUpdateException ex) when (ex.InnerException is
PostgresException { ConstraintName: "IX_Manufacturers_ManufacturerName" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("ManufacturerName",
manufacturerDataModel.ManufacturerName);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetManufacturerById(id) ?? throw new
ElementNotFoundException(id);
_dbContext.Manufacturers.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Manufacturer? GetManufacturerById(string id) =>
_dbContext.Manufacturers.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,192 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.StoragesContracts;
using SmallSoftwareDatabase.Models;
namespace SmallSoftwareDatabase.Implementations;
internal class PostStorageContract : IPostStorageContract
{
private readonly SmallSoftwareDbContext _dbContext;
private readonly Mapper _mapper;
public PostStorageContract(SmallSoftwareDbContext 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 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 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 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();
}

View File

@@ -0,0 +1,118 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.StoragesContracts;
using SmallSoftwareDatabase.Models;
namespace SmallSoftwareDatabase.Implementations;
internal class RequestStorageContract : IRequestStorageContract
{
private readonly SmallSoftwareDbContext _dbContext;
private readonly Mapper _mapper;
public RequestStorageContract(SmallSoftwareDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Manufacturer, ManufacturerDataModel>();
cfg.CreateMap<Software, SoftwareDataModel>();
cfg.CreateMap<Worker, WorkerDataModel>();
cfg.CreateMap<InstallationRequest, InstallationRequestDataModel>();
cfg.CreateMap<InstallationRequestDataModel, InstallationRequest>()
.ForMember(x => x.SoftwareId, x => x.MapFrom(src => src.SoftwareId));
cfg.CreateMap<Request, RequestDataModel>();
cfg.CreateMap<RequestDataModel, Request>()
.ForMember(x => x.IsCancel, x => x.MapFrom(src => false))
.ForMember(x => x.InstallationRequests, x => x.MapFrom(src => src.Softwares))
.ForMember(x => x.Worker, x => x.Ignore())
.ForMember(dest => dest.RequestDate, opt => opt.MapFrom(src => src.RequestDate))
.ForMember(dest => dest.RequestDate, opt => opt.MapFrom(src => src.RequestDate));
});
_mapper = new Mapper(config);
}
public List<RequestDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? workerId = null, string? softwareId = null)
{
try
{
var query = _dbContext.Requests.Include(x => x.Worker).Include(x => x.InstallationRequests).AsQueryable();
if (workerId is not null)
{
query = query.Where(x => x.WorkerId == workerId);
}
if (softwareId is not null)
{
query = query.Where(x => x.InstallationRequests!.Any(y => y.SoftwareId == softwareId));
}
return [.. query.Select(x => _mapper.Map<RequestDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public RequestDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<RequestDataModel>(GetRequestById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(RequestDataModel requestDataModel)
{
try
{
_dbContext.Requests.Add(_mapper.Map<Request>(requestDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetRequestById(id) ?? throw new ElementNotFoundException(id);
if (element.IsCancel)
{
throw new ElementDeletedException(id);
}
element.IsCancel = true;
_dbContext.SaveChanges();
}
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Request? GetRequestById(string id) =>
_dbContext.Requests
.Include(x => x.Worker)
.Include(x => x.InstallationRequests)!
.ThenInclude(x => x.Software)
.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,56 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.StoragesContracts;
using SmallSoftwareDatabase.Models;
namespace SmallSoftwareDatabase.Implementations;
internal class SalaryStorageContract : ISalaryStorageContract
{
private readonly SmallSoftwareDbContext _dbContext;
private readonly Mapper _mapper;
public SalaryStorageContract(SmallSoftwareDbContext 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);
}
}
}

View File

@@ -0,0 +1,187 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.StoragesContracts;
using SmallSoftwareDatabase.Models;
namespace SmallSoftwareDatabase.Implementations;
internal class SoftwareStorageContract : ISoftwareStorageContract
{
private readonly SmallSoftwareDbContext _dbContext;
private readonly Mapper _mapper;
public SoftwareStorageContract(SmallSoftwareDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Manufacturer, ManufacturerDataModel>();
cfg.CreateMap<Software, SoftwareDataModel>();
cfg.CreateMap<SoftwareDataModel, Software>()
.ForMember(x => x.IsDeleted, x => x.MapFrom(src => false));
cfg.CreateMap<SoftwareHistory, SoftwareHistoryDataModel>();
});
_mapper = new Mapper(config);
}
public List<SoftwareDataModel> GetList(bool onlyActive = true, string?
manufacturerId = null)
{
try
{
var query = _dbContext.Softwares.Include(x => x.Manufacturer).AsQueryable();
if (onlyActive)
{
query = query.Where(x => !x.IsDeleted);
}
if (manufacturerId is not null)
{
query = query.Where(x => x.ManufacturerId ==
manufacturerId);
}
return [.. query.Select(x => _mapper.Map<SoftwareDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public List<SoftwareHistoryDataModel> GetHistoryBySoftwareId(string
softwareId)
{
try
{
return [.. _dbContext.SoftwareHistories.Include(x => x.Software).Where(x => x.SoftwareId == softwareId)
.OrderByDescending(x => x.ChangeDate)
.Select(x => _mapper.Map<SoftwareHistoryDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public SoftwareDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<SoftwareDataModel>(GetSoftwareById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public SoftwareDataModel? GetElementByName(string name)
{
try
{
return
_mapper.Map<SoftwareDataModel>(_dbContext.Softwares.Include(x => x.Manufacturer).FirstOrDefault(x =>
x.SoftwareName == name && !x.IsDeleted));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(SoftwareDataModel softwareDataModel)
{
try
{
_dbContext.Softwares.Add(_mapper.Map<Software>(softwareDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name ==
"ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", softwareDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is
PostgresException { ConstraintName: "IX_Softwares_SoftwareName_IsDeleted" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("SoftwareName",
softwareDataModel.SoftwareName);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(SoftwareDataModel softwareDataModel)
{
try
{
var transaction = _dbContext.Database.BeginTransaction();
try
{
var element = GetSoftwareById(softwareDataModel.Id) ??
throw new ElementNotFoundException(softwareDataModel.Id);
if (element.Price != softwareDataModel.Price)
{
_dbContext.SoftwareHistories.Add(new
SoftwareHistory()
{ SoftwareId = element.Id, OldPrice = element.Price });
_dbContext.SaveChanges();
}
_dbContext.Softwares.Update(_mapper.Map(softwareDataModel,
element));
_dbContext.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
catch (DbUpdateException ex) when (ex.InnerException is
PostgresException { ConstraintName: "IX_Softwares_SoftwareName_IsDeleted" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("SoftwareName",
softwareDataModel.SoftwareName);
}
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 = GetSoftwareById(id) ?? throw new
ElementNotFoundException(id);
element.IsDeleted = true;
_dbContext.SaveChanges();
}
catch (ElementNotFoundException ex)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Software? GetSoftwareById(string id) =>
_dbContext.Softwares.Include(x => x.Manufacturer).FirstOrDefault(x => x.Id == id && !x.IsDeleted);
}

View File

@@ -0,0 +1,177 @@
using AutoMapper;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.StoragesContracts;
using SmallSoftwareDatabase.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareDatabase.Implementations;
internal class WorkerStorageContract : IWorkerStorageContract
{
private readonly SmallSoftwareDbContext _dbContext;
private readonly Mapper _mapper;
public WorkerStorageContract(SmallSoftwareDbContext 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>()
.ForMember(x => x.Post, x => x.Ignore())
.ForMember(x => x.Configuration, x => x.MapFrom(src => src.ConfigurationModel));
});
_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;
element.DateOfDelete = DateTime.UtcNow;
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public int GetWorkerTrend(DateTime fromPeriod, DateTime toPeriod)
{
try
{
var countWorkersOnBegining = _dbContext.Workers.Count(x =>
x.EmploymentDate < fromPeriod && (!x.IsDeleted || x.DateOfDelete > fromPeriod));
var countWorkersOnEnding = _dbContext.Workers.Count(x =>
x.EmploymentDate < toPeriod && (!x.IsDeleted || x.DateOfDelete > toPeriod));
return countWorkersOnEnding - countWorkersOnBegining;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Worker? GetWorkerById(string id) => AddPost(_dbContext.Workers.FirstOrDefault(x => x.Id == id && !x.IsDeleted));
private IQueryable<Worker> JoinPost(IQueryable<Worker> query) => query.GroupJoin(_dbContext.Posts.Where(x => x.IsActual), x =>
x.PostId, y => y.PostId, (x, y) => new { Worker = x, Post = y }).SelectMany(xy => xy.Post.DefaultIfEmpty(), (x, y) => x.Worker.AddPost(y));
private Worker? AddPost(Worker? worker) => worker?.AddPost(_dbContext.Posts.FirstOrDefault(x => x.PostId == worker.PostId && x.IsActual));
}

View File

@@ -0,0 +1,338 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using SmallSoftwareDatabase;
#nullable disable
namespace SmallSoftwareDatabase.Migrations
{
[DbContext(typeof(SmallSoftwareDbContext))]
[Migration("20250417140247_FirstMigration")]
partial class FirstMigration
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.2")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("SmallSoftwareDatabase.Models.InstallationRequest", b =>
{
b.Property<string>("RequestId")
.HasColumnType("text");
b.Property<string>("SoftwareId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("RequestId", "SoftwareId");
b.HasIndex("SoftwareId");
b.ToTable("InstallationRequests");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Manufacturer", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ManufacturerName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PrevManufacturerName")
.HasColumnType("text");
b.Property<string>("PrevPrevManufacturerName")
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ManufacturerName")
.IsUnique();
b.ToTable("Manufacturers");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Post", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<bool>("IsActual")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PostName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("PostType")
.HasColumnType("integer");
b.Property<double>("Salary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("PostId", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.HasIndex("PostName", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.ToTable("Posts");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Request", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsCancel")
.HasColumnType("boolean");
b.Property<DateTime>("RequestDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("WorkerId");
b.ToTable("Requests");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Salary", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("SalaryDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("WorkerSalary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("WorkerId");
b.ToTable("Salaries");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Software", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("ManufacturerId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PrevPrevSoftwareName")
.HasColumnType("text");
b.Property<string>("PrevSoftwareName")
.HasColumnType("text");
b.Property<double>("Price")
.HasColumnType("double precision");
b.Property<string>("SoftwareName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("SoftwareType")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ManufacturerId");
b.HasIndex("SoftwareName", "IsDeleted")
.IsUnique()
.HasFilter("\"IsDeleted\" = FALSE");
b.ToTable("Softwares");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.SoftwareHistory", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("OldPrice")
.HasColumnType("double precision");
b.Property<string>("SoftwareId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("SoftwareId");
b.ToTable("SoftwareHistories");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Worker", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("BirthDate")
.HasColumnType("timestamp without time zone");
b.Property<DateTime>("EmploymentDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Workers");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.InstallationRequest", b =>
{
b.HasOne("SmallSoftwareDatabase.Models.Request", "Request")
.WithMany("InstallationRequests")
.HasForeignKey("RequestId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SmallSoftwareDatabase.Models.Software", "Software")
.WithMany("InstallationRequests")
.HasForeignKey("SoftwareId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Request");
b.Navigation("Software");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Request", b =>
{
b.HasOne("SmallSoftwareDatabase.Models.Worker", "Worker")
.WithMany("Requests")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Worker");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Salary", b =>
{
b.HasOne("SmallSoftwareDatabase.Models.Worker", "Worker")
.WithMany("Salaries")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Worker");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Software", b =>
{
b.HasOne("SmallSoftwareDatabase.Models.Manufacturer", "Manufacturer")
.WithMany("Softwares")
.HasForeignKey("ManufacturerId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Manufacturer");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.SoftwareHistory", b =>
{
b.HasOne("SmallSoftwareDatabase.Models.Software", "Software")
.WithMany("SoftwareHistories")
.HasForeignKey("SoftwareId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Software");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Manufacturer", b =>
{
b.Navigation("Softwares");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Request", b =>
{
b.Navigation("InstallationRequests");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Software", b =>
{
b.Navigation("InstallationRequests");
b.Navigation("SoftwareHistories");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Worker", b =>
{
b.Navigation("Requests");
b.Navigation("Salaries");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,254 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SmallSoftwareDatabase.Migrations
{
/// <inheritdoc />
public partial class FirstMigration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Manufacturers",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
ManufacturerName = table.Column<string>(type: "text", nullable: false),
PrevManufacturerName = table.Column<string>(type: "text", nullable: true),
PrevPrevManufacturerName = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Manufacturers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Posts",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
PostId = table.Column<string>(type: "text", nullable: false),
PostName = table.Column<string>(type: "text", nullable: false),
PostType = table.Column<int>(type: "integer", nullable: false),
Salary = table.Column<double>(type: "double precision", nullable: false),
IsActual = table.Column<bool>(type: "boolean", nullable: false),
ChangeDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Posts", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Workers",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
FIO = table.Column<string>(type: "text", nullable: false),
PostId = table.Column<string>(type: "text", nullable: false),
BirthDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
EmploymentDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
IsDeleted = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Workers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Softwares",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
SoftwareName = table.Column<string>(type: "text", nullable: false),
SoftwareType = table.Column<int>(type: "integer", nullable: false),
ManufacturerId = table.Column<string>(type: "text", nullable: false),
Price = table.Column<double>(type: "double precision", nullable: false),
IsDeleted = table.Column<bool>(type: "boolean", nullable: false),
PrevSoftwareName = table.Column<string>(type: "text", nullable: true),
PrevPrevSoftwareName = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Softwares", x => x.Id);
table.ForeignKey(
name: "FK_Softwares_Manufacturers_ManufacturerId",
column: x => x.ManufacturerId,
principalTable: "Manufacturers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Requests",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
WorkerId = table.Column<string>(type: "text", nullable: false),
RequestDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
Email = table.Column<string>(type: "text", nullable: false),
Sum = table.Column<double>(type: "double precision", nullable: false),
IsCancel = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Requests", x => x.Id);
table.ForeignKey(
name: "FK_Requests_Workers_WorkerId",
column: x => x.WorkerId,
principalTable: "Workers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Salaries",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
WorkerId = table.Column<string>(type: "text", nullable: false),
WorkerSalary = table.Column<double>(type: "double precision", nullable: false),
SalaryDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Salaries", x => x.Id);
table.ForeignKey(
name: "FK_Salaries_Workers_WorkerId",
column: x => x.WorkerId,
principalTable: "Workers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "SoftwareHistories",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
SoftwareId = table.Column<string>(type: "text", nullable: false),
OldPrice = table.Column<double>(type: "double precision", nullable: false),
ChangeDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_SoftwareHistories", x => x.Id);
table.ForeignKey(
name: "FK_SoftwareHistories_Softwares_SoftwareId",
column: x => x.SoftwareId,
principalTable: "Softwares",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "InstallationRequests",
columns: table => new
{
SoftwareId = table.Column<string>(type: "text", nullable: false),
RequestId = table.Column<string>(type: "text", nullable: false),
Count = table.Column<int>(type: "integer", nullable: false),
Price = table.Column<double>(type: "double precision", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_InstallationRequests", x => new { x.RequestId, x.SoftwareId });
table.ForeignKey(
name: "FK_InstallationRequests_Requests_RequestId",
column: x => x.RequestId,
principalTable: "Requests",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_InstallationRequests_Softwares_SoftwareId",
column: x => x.SoftwareId,
principalTable: "Softwares",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_InstallationRequests_SoftwareId",
table: "InstallationRequests",
column: "SoftwareId");
migrationBuilder.CreateIndex(
name: "IX_Manufacturers_ManufacturerName",
table: "Manufacturers",
column: "ManufacturerName",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Posts_PostId_IsActual",
table: "Posts",
columns: new[] { "PostId", "IsActual" },
unique: true,
filter: "\"IsActual\" = TRUE");
migrationBuilder.CreateIndex(
name: "IX_Posts_PostName_IsActual",
table: "Posts",
columns: new[] { "PostName", "IsActual" },
unique: true,
filter: "\"IsActual\" = TRUE");
migrationBuilder.CreateIndex(
name: "IX_Requests_WorkerId",
table: "Requests",
column: "WorkerId");
migrationBuilder.CreateIndex(
name: "IX_Salaries_WorkerId",
table: "Salaries",
column: "WorkerId");
migrationBuilder.CreateIndex(
name: "IX_SoftwareHistories_SoftwareId",
table: "SoftwareHistories",
column: "SoftwareId");
migrationBuilder.CreateIndex(
name: "IX_Softwares_ManufacturerId",
table: "Softwares",
column: "ManufacturerId");
migrationBuilder.CreateIndex(
name: "IX_Softwares_SoftwareName_IsDeleted",
table: "Softwares",
columns: new[] { "SoftwareName", "IsDeleted" },
unique: true,
filter: "\"IsDeleted\" = FALSE");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "InstallationRequests");
migrationBuilder.DropTable(
name: "Posts");
migrationBuilder.DropTable(
name: "Salaries");
migrationBuilder.DropTable(
name: "SoftwareHistories");
migrationBuilder.DropTable(
name: "Requests");
migrationBuilder.DropTable(
name: "Softwares");
migrationBuilder.DropTable(
name: "Workers");
migrationBuilder.DropTable(
name: "Manufacturers");
}
}
}

View File

@@ -0,0 +1,345 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using SmallSoftwareDatabase;
#nullable disable
namespace SmallSoftwareDatabase.Migrations
{
[DbContext(typeof(SmallSoftwareDbContext))]
[Migration("20250417185242_ChangeFieldsInWorker")]
partial class ChangeFieldsInWorker
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.2")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("SmallSoftwareDatabase.Models.InstallationRequest", b =>
{
b.Property<string>("RequestId")
.HasColumnType("text");
b.Property<string>("SoftwareId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("RequestId", "SoftwareId");
b.HasIndex("SoftwareId");
b.ToTable("InstallationRequests");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Manufacturer", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ManufacturerName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PrevManufacturerName")
.HasColumnType("text");
b.Property<string>("PrevPrevManufacturerName")
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ManufacturerName")
.IsUnique();
b.ToTable("Manufacturers");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Post", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<bool>("IsActual")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PostName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("PostType")
.HasColumnType("integer");
b.Property<double>("Salary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("PostId", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.HasIndex("PostName", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.ToTable("Posts");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Request", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsCancel")
.HasColumnType("boolean");
b.Property<DateTime>("RequestDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("WorkerId");
b.ToTable("Requests");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Salary", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("SalaryDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("WorkerSalary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("WorkerId");
b.ToTable("Salaries");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Software", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("ManufacturerId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PrevPrevSoftwareName")
.HasColumnType("text");
b.Property<string>("PrevSoftwareName")
.HasColumnType("text");
b.Property<double>("Price")
.HasColumnType("double precision");
b.Property<string>("SoftwareName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("SoftwareType")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ManufacturerId");
b.HasIndex("SoftwareName", "IsDeleted")
.IsUnique()
.HasFilter("\"IsDeleted\" = FALSE");
b.ToTable("Softwares");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.SoftwareHistory", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("OldPrice")
.HasColumnType("double precision");
b.Property<string>("SoftwareId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("SoftwareId");
b.ToTable("SoftwareHistories");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Worker", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("BirthDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Configuration")
.IsRequired()
.HasColumnType("jsonb");
b.Property<DateTime?>("DateOfDelete")
.HasColumnType("timestamp without time zone");
b.Property<DateTime>("EmploymentDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Workers");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.InstallationRequest", b =>
{
b.HasOne("SmallSoftwareDatabase.Models.Request", "Request")
.WithMany("InstallationRequests")
.HasForeignKey("RequestId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SmallSoftwareDatabase.Models.Software", "Software")
.WithMany("InstallationRequests")
.HasForeignKey("SoftwareId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Request");
b.Navigation("Software");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Request", b =>
{
b.HasOne("SmallSoftwareDatabase.Models.Worker", "Worker")
.WithMany("Requests")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Worker");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Salary", b =>
{
b.HasOne("SmallSoftwareDatabase.Models.Worker", "Worker")
.WithMany("Salaries")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Worker");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Software", b =>
{
b.HasOne("SmallSoftwareDatabase.Models.Manufacturer", "Manufacturer")
.WithMany("Softwares")
.HasForeignKey("ManufacturerId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Manufacturer");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.SoftwareHistory", b =>
{
b.HasOne("SmallSoftwareDatabase.Models.Software", "Software")
.WithMany("SoftwareHistories")
.HasForeignKey("SoftwareId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Software");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Manufacturer", b =>
{
b.Navigation("Softwares");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Request", b =>
{
b.Navigation("InstallationRequests");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Software", b =>
{
b.Navigation("InstallationRequests");
b.Navigation("SoftwareHistories");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Worker", b =>
{
b.Navigation("Requests");
b.Navigation("Salaries");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,40 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SmallSoftwareDatabase.Migrations
{
/// <inheritdoc />
public partial class ChangeFieldsInWorker : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Configuration",
table: "Workers",
type: "jsonb",
nullable: false,
defaultValue: "{\"Rate\": 0, \"Type\": \"PostConfiguration\"}");
migrationBuilder.AddColumn<DateTime>(
name: "DateOfDelete",
table: "Workers",
type: "timestamp without time zone",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Configuration",
table: "Workers");
migrationBuilder.DropColumn(
name: "DateOfDelete",
table: "Workers");
}
}
}

View File

@@ -0,0 +1,342 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using SmallSoftwareDatabase;
#nullable disable
namespace SmallSoftwareDatabase.Migrations
{
[DbContext(typeof(SmallSoftwareDbContext))]
partial class SmallSoftwareDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.2")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("SmallSoftwareDatabase.Models.InstallationRequest", b =>
{
b.Property<string>("RequestId")
.HasColumnType("text");
b.Property<string>("SoftwareId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("RequestId", "SoftwareId");
b.HasIndex("SoftwareId");
b.ToTable("InstallationRequests");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Manufacturer", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ManufacturerName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PrevManufacturerName")
.HasColumnType("text");
b.Property<string>("PrevPrevManufacturerName")
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ManufacturerName")
.IsUnique();
b.ToTable("Manufacturers");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Post", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<bool>("IsActual")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PostName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("PostType")
.HasColumnType("integer");
b.Property<double>("Salary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("PostId", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.HasIndex("PostName", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.ToTable("Posts");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Request", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsCancel")
.HasColumnType("boolean");
b.Property<DateTime>("RequestDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("WorkerId");
b.ToTable("Requests");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Salary", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("SalaryDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("WorkerSalary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("WorkerId");
b.ToTable("Salaries");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Software", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("ManufacturerId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PrevPrevSoftwareName")
.HasColumnType("text");
b.Property<string>("PrevSoftwareName")
.HasColumnType("text");
b.Property<double>("Price")
.HasColumnType("double precision");
b.Property<string>("SoftwareName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("SoftwareType")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ManufacturerId");
b.HasIndex("SoftwareName", "IsDeleted")
.IsUnique()
.HasFilter("\"IsDeleted\" = FALSE");
b.ToTable("Softwares");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.SoftwareHistory", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("OldPrice")
.HasColumnType("double precision");
b.Property<string>("SoftwareId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("SoftwareId");
b.ToTable("SoftwareHistories");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Worker", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("BirthDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Configuration")
.IsRequired()
.HasColumnType("jsonb");
b.Property<DateTime?>("DateOfDelete")
.HasColumnType("timestamp without time zone");
b.Property<DateTime>("EmploymentDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Workers");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.InstallationRequest", b =>
{
b.HasOne("SmallSoftwareDatabase.Models.Request", "Request")
.WithMany("InstallationRequests")
.HasForeignKey("RequestId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SmallSoftwareDatabase.Models.Software", "Software")
.WithMany("InstallationRequests")
.HasForeignKey("SoftwareId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Request");
b.Navigation("Software");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Request", b =>
{
b.HasOne("SmallSoftwareDatabase.Models.Worker", "Worker")
.WithMany("Requests")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Worker");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Salary", b =>
{
b.HasOne("SmallSoftwareDatabase.Models.Worker", "Worker")
.WithMany("Salaries")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Worker");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Software", b =>
{
b.HasOne("SmallSoftwareDatabase.Models.Manufacturer", "Manufacturer")
.WithMany("Softwares")
.HasForeignKey("ManufacturerId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Manufacturer");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.SoftwareHistory", b =>
{
b.HasOne("SmallSoftwareDatabase.Models.Software", "Software")
.WithMany("SoftwareHistories")
.HasForeignKey("SoftwareId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Software");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Manufacturer", b =>
{
b.Navigation("Softwares");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Request", b =>
{
b.Navigation("InstallationRequests");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Software", b =>
{
b.Navigation("InstallationRequests");
b.Navigation("SoftwareHistories");
});
modelBuilder.Entity("SmallSoftwareDatabase.Models.Worker", b =>
{
b.Navigation("Requests");
b.Navigation("Salaries");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareDatabase.Models;
internal class InstallationRequest
{
public required string SoftwareId { get; set; }
public required string RequestId { get; set; }
public int Count { get; set; }
public double Price { get; set; }
public Request? Request { get; set; }
public Software? Software { get; set; }
}

View File

@@ -0,0 +1,23 @@
using AutoMapper;
using SmallSoftwareContracts.DataModels;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareDatabase.Models;
[AutoMap(typeof(ManufacturerDataModel), ReverseMap = true)]
internal class Manufacturer
{
public required string Id { get; set; }
public required string ManufacturerName { get; set; }
public string? PrevManufacturerName { get; set; }
public string? PrevPrevManufacturerName { get; set; }
[ForeignKey("ManufacturerId")]
public List<Software>? Softwares { get; set; }
}

View File

@@ -0,0 +1,14 @@
using SmallSoftwareContracts.Enums;
namespace SmallSoftwareDatabase.Models;
internal 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; }
}

View File

@@ -0,0 +1,17 @@
using System.ComponentModel.DataAnnotations.Schema;
namespace SmallSoftwareDatabase.Models;
internal class Request
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string WorkerId { get; set; }
public DateTime RequestDate { get; set; }
public required string Email { get; set; }
public double Sum { get; set; }
public bool IsCancel { get; set; }
public Worker? Worker { get; set; }
[ForeignKey("RequestId")]
public List<InstallationRequest>? InstallationRequests { get; set; }
}

View File

@@ -0,0 +1,11 @@
namespace SmallSoftwareDatabase.Models;
internal 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; }
}

View File

@@ -0,0 +1,24 @@
using SmallSoftwareContracts.Enums;
using System.ComponentModel.DataAnnotations.Schema;
namespace SmallSoftwareDatabase.Models;
internal class Software
{
public required string Id { get; set; }
public required string SoftwareName { get; set; }
public SoftwareType SoftwareType { get; set; }
public required string ManufacturerId { get; set; }
public double Price { get; set; }
public bool IsDeleted { get; set; }
public string? PrevSoftwareName { get; set; }
public string? PrevPrevSoftwareName { get; set; }
public Manufacturer? Manufacturer { get; set; }
[ForeignKey("SoftwareId")]
public List<SoftwareHistory>? SoftwareHistories { get; set; }
[ForeignKey("SoftwareId")]
public List<InstallationRequest>? InstallationRequests { get; set; }
}

View File

@@ -0,0 +1,11 @@
namespace SmallSoftwareDatabase.Models;
internal class SoftwareHistory
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string SoftwareId { get; set; }
public double OldPrice { get; set; }
public DateTime ChangeDate { get; set; } = DateTime.UtcNow;
public Software? Software { get; set; }
}

View File

@@ -0,0 +1,30 @@
using AutoMapper;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Infrastructure.PostConfigurations;
using System.ComponentModel.DataAnnotations.Schema;
namespace SmallSoftwareDatabase.Models;
[AutoMap(typeof(WorkerDataModel), ReverseMap = true)]
internal 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 required PostConfiguration Configuration { get; set; }
public DateTime? DateOfDelete { get; set; }
[NotMapped]
public Post? Post { get; set; }
[ForeignKey("WorkerId")]
public List<Salary>? Salaries { get; set; }
[ForeignKey("WorkerId")]
public List<Request>? Requests { get; set; }
public Worker AddPost(Post? post)
{
Post = post;
return this;
}
}

View File

@@ -0,0 +1,16 @@
using Microsoft.EntityFrameworkCore.Design;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareDatabase;
internal class SampleContextFactory : IDesignTimeDbContextFactory<SmallSoftwareDbContext>
{
public SmallSoftwareDbContext CreateDbContext(string[] args)
{
return new SmallSoftwareDbContext(new DefaultConfigurationDatabase());
}
}

View File

@@ -0,0 +1,30 @@
<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="Microsoft.EntityFrameworkCore.Tools" Version="9.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SmallSoftwareContracts\SmallSoftwareContracts.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="SmallSoftwareWebApi" />
<InternalsVisibleTo Include="SmallSoftwareTests" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,70 @@
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SmallSoftwareContracts.Infrastructure;
using SmallSoftwareContracts.Infrastructure.PostConfigurations;
using SmallSoftwareDatabase.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareDatabase;
internal class SmallSoftwareDbContext : DbContext
{
private readonly IConfigurationDatabase? _configurationDatabase;
public SmallSoftwareDbContext(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<Manufacturer>().HasIndex(x => x.ManufacturerName).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<Software>().HasIndex(x => new { x.SoftwareName, x.IsDeleted })
.IsUnique()
.HasFilter($"\"{nameof(Software.IsDeleted)}\" = FALSE");
modelBuilder.Entity<Software>()
.HasOne(e => e.Manufacturer)
.WithMany(e => e.Softwares)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<InstallationRequest>().HasKey(x => new { x.RequestId, x.SoftwareId });
modelBuilder.Entity<Worker>().Property(x => x.Configuration).HasColumnType("jsonb").HasConversion(
x => SerializePostConfiguration(x),
x => DeserialzePostConfiguration(x)
);
}
public DbSet<Manufacturer> Manufacturers { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<Software> Softwares { get; set; }
public DbSet<SoftwareHistory> SoftwareHistories { get; set; }
public DbSet<Salary> Salaries { get; set; }
public DbSet<Request> Requests { get; set; }
public DbSet<InstallationRequest> InstallationRequests { get; set; }
public DbSet<Worker> Workers { get; set; }
private static string SerializePostConfiguration(PostConfiguration postConfiguration) => JsonConvert.SerializeObject(postConfiguration);
private static PostConfiguration DeserialzePostConfiguration(string jsonString) => JToken.Parse(jsonString).Value<string>("Type") switch
{
nameof(CashierPostConfiguration) => JsonConvert.DeserializeObject<CashierPostConfiguration>(jsonString)!,
nameof(SupervisorPostConfiguration) => JsonConvert.DeserializeObject<SupervisorPostConfiguration>(jsonString)!,
_ => JsonConvert.DeserializeObject<PostConfiguration>(jsonString)!
};
}

View File

@@ -1,10 +1,18 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.12.35728.132 d17.12
VisualStudioVersion = 17.12.35728.132
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SmallSoftwareContracts", "SmallSoftwareContracts\SmallSoftwareContracts.csproj", "{07D2A792-3603-47CB-B5A3-9736E582F496}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SmallSoftwareTests", "SmallSoftwareTests\SmallSoftwareTests.csproj", "{A98AC101-F5F5-4270-97D6-B5FA766D3E64}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SmallSoftwareBusinessLogic", "SmallSoftwareBusinessLogic\SmallSoftwareBusinessLogic.csproj", "{C4E0D33E-8DBB-4BB5-8CCE-D2888F754EC7}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SmallSoftwareDatabase", "SmallSoftwareDatabase\SmallSoftwareDatabase.csproj", "{59771C74-7A34-4354-949A-F3AA071FBCAA}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SmallSoftwareWebApi", "SmallSoftwareWebApi\SmallSoftwareWebApi.csproj", "{AC51FBAD-A0B1-40C3-AD75-E29F6E7FD624}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -15,6 +23,22 @@ Global
{07D2A792-3603-47CB-B5A3-9736E582F496}.Debug|Any CPU.Build.0 = Debug|Any CPU
{07D2A792-3603-47CB-B5A3-9736E582F496}.Release|Any CPU.ActiveCfg = Release|Any CPU
{07D2A792-3603-47CB-B5A3-9736E582F496}.Release|Any CPU.Build.0 = Release|Any CPU
{A98AC101-F5F5-4270-97D6-B5FA766D3E64}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A98AC101-F5F5-4270-97D6-B5FA766D3E64}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A98AC101-F5F5-4270-97D6-B5FA766D3E64}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A98AC101-F5F5-4270-97D6-B5FA766D3E64}.Release|Any CPU.Build.0 = Release|Any CPU
{C4E0D33E-8DBB-4BB5-8CCE-D2888F754EC7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C4E0D33E-8DBB-4BB5-8CCE-D2888F754EC7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C4E0D33E-8DBB-4BB5-8CCE-D2888F754EC7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C4E0D33E-8DBB-4BB5-8CCE-D2888F754EC7}.Release|Any CPU.Build.0 = Release|Any CPU
{59771C74-7A34-4354-949A-F3AA071FBCAA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{59771C74-7A34-4354-949A-F3AA071FBCAA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{59771C74-7A34-4354-949A-F3AA071FBCAA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{59771C74-7A34-4354-949A-F3AA071FBCAA}.Release|Any CPU.Build.0 = Release|Any CPU
{AC51FBAD-A0B1-40C3-AD75-E29F6E7FD624}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AC51FBAD-A0B1-40C3-AD75-E29F6E7FD624}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AC51FBAD-A0B1-40C3-AD75-E29F6E7FD624}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AC51FBAD-A0B1-40C3-AD75-E29F6E7FD624}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@@ -0,0 +1,446 @@
using Microsoft.Extensions.Logging;
using Moq;
using SmallSoftwareBusinessLogic.Implementations;
using SmallSoftwareContracts.BusinessLogicsContracts;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.StoragesContracts;
namespace SmallSoftwareTests.BusinessLogicsContractsTests;
[TestFixture]
internal class ManufacturerBusinessLogicContractTests
{
private IManufacturerBusinessLogicContract _manufacturerBusinessLogicContract;
private Mock<IManufacturerStorageContract> _manufacturerStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_manufacturerStorageContract = new
Mock<IManufacturerStorageContract>();
_manufacturerBusinessLogicContract = new ManufacturerBusinessLogicContract(_manufacturerStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_manufacturerStorageContract.Reset();
}
[Test]
public void GetAllManufacturers_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<ManufacturerDataModel>()
{
new(Guid.NewGuid().ToString(), "name 1", null, null),
new(Guid.NewGuid().ToString(), "name 2", null, null),
new(Guid.NewGuid().ToString(), "name 3", null, null),
};
_manufacturerStorageContract.Setup(x =>
x.GetList()).Returns(listOriginal);
//Act
var list = _manufacturerBusinessLogicContract.GetAllManufacturers();
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
}
[Test]
public void GetAllManufacturers_ReturnEmptyList_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x => x.GetList()).Returns([]);
//Act
var list = _manufacturerBusinessLogicContract.GetAllManufacturers();
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_manufacturerStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllManufacturers_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_manufacturerBusinessLogicContract.GetAllManufacturers(),
Throws.TypeOf<NullListException>());
_manufacturerStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllManufacturers_StorageThrowError_ThrowException_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x => x.GetList()).Throws(new
StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() =>
_manufacturerBusinessLogicContract.GetAllManufacturers(),
Throws.TypeOf<StorageException>());
_manufacturerStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetManufacturerByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new ManufacturerDataModel(id, "name", null, null);
_manufacturerStorageContract.Setup(x =>
x.GetElementById(id)).Returns(record);
//Act
var element =
_manufacturerBusinessLogicContract.GetManufacturerByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_manufacturerStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetManufacturerByData_GetByName_ReturnRecord_Test()
{
//Arrange
var manufacturerName = "name";
var record = new ManufacturerDataModel(Guid.NewGuid().ToString(),
manufacturerName, null, null);
_manufacturerStorageContract.Setup(x =>
x.GetElementByName(manufacturerName)).Returns(record);
//Act
var element =
_manufacturerBusinessLogicContract.GetManufacturerByData(manufacturerName);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.ManufacturerName, Is.EqualTo(manufacturerName));
_manufacturerStorageContract.Verify(x =>
x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetManufacturerByData_GetByOldName_ReturnRecord_Test()
{
//Arrange
var manufacturerOldName = "name before";
var record = new ManufacturerDataModel(Guid.NewGuid().ToString(),
"name", manufacturerOldName, null);
_manufacturerStorageContract.Setup(x =>
x.GetElementByOldName(manufacturerOldName)).Returns(record);
//Act
var element =
_manufacturerBusinessLogicContract.GetManufacturerByData(manufacturerOldName);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.PrevManufacturerName,
Is.EqualTo(manufacturerOldName));
_manufacturerStorageContract.Verify(x =>
x.GetElementByName(It.IsAny<string>()), Times.Once);
_manufacturerStorageContract.Verify(x =>
x.GetElementByOldName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetManufacturerByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_manufacturerBusinessLogicContract.GetManufacturerByData(null),
Throws.TypeOf<ArgumentNullException>());
Assert.That(() =>
_manufacturerBusinessLogicContract.GetManufacturerByData(string.Empty),
Throws.TypeOf<ArgumentNullException>());
_manufacturerStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Never);
_manufacturerStorageContract.Verify(x =>
x.GetElementByName(It.IsAny<string>()), Times.Never);
_manufacturerStorageContract.Verify(x =>
x.GetElementByOldName(It.IsAny<string>()), Times.Never);
}
[Test]
public void
GetManufacturerByData__GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_manufacturerBusinessLogicContract.GetManufacturerByData(Guid.NewGuid().ToString(
)), Throws.TypeOf<ElementNotFoundException>());
_manufacturerStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Once);
_manufacturerStorageContract.Verify(x =>
x.GetElementByName(It.IsAny<string>()), Times.Never);
_manufacturerStorageContract.Verify(x =>
x.GetElementByOldName(It.IsAny<string>()), Times.Never);
}
[Test]
public void
GetManufacturerByData_GetByNameOrOldName_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_manufacturerBusinessLogicContract.GetManufacturerByData("name"),
Throws.TypeOf<ElementNotFoundException>());
_manufacturerStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Never);
_manufacturerStorageContract.Verify(x =>
x.GetElementByName(It.IsAny<string>()), Times.Once);
_manufacturerStorageContract.Verify(x =>
x.GetElementByOldName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetManufacturerByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x =>
x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException()));
_manufacturerStorageContract.Setup(x =>
x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException()));
//Act&Assert
Assert.That(() =>
_manufacturerBusinessLogicContract.GetManufacturerByData(Guid.NewGuid().ToString(
)), Throws.TypeOf<StorageException>());
Assert.That(() =>
_manufacturerBusinessLogicContract.GetManufacturerByData("name"),
Throws.TypeOf<StorageException>());
_manufacturerStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Once);
_manufacturerStorageContract.Verify(x =>
x.GetElementByName(It.IsAny<string>()), Times.Once);
_manufacturerStorageContract.Verify(x =>
x.GetElementByOldName(It.IsAny<string>()), Times.Never);
}
[Test]
public void
GetManufacturerByData_GetByOldName_StorageThrowError_ThrowException_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x =>
x.GetElementByOldName(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException()));
//Act&Assert
Assert.That(() =>
_manufacturerBusinessLogicContract.GetManufacturerByData("name"),
Throws.TypeOf<StorageException>());
_manufacturerStorageContract.Verify(x =>
x.GetElementByName(It.IsAny<string>()), Times.Once);
_manufacturerStorageContract.Verify(x =>
x.GetElementByOldName(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertManufacturer_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new ManufacturerDataModel(Guid.NewGuid().ToString(),
"name", null, null);
_manufacturerStorageContract.Setup(x =>
x.AddElement(It.IsAny<ManufacturerDataModel>()))
.Callback((ManufacturerDataModel x) =>
{
flag = x.Id == record.Id && x.ManufacturerName ==
record.ManufacturerName;
});
//Act
_manufacturerBusinessLogicContract.InsertManufacturer(record);
//Assert
_manufacturerStorageContract.Verify(x =>
x.AddElement(It.IsAny<ManufacturerDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertManufacturer_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x =>
x.AddElement(It.IsAny<ManufacturerDataModel>())).Throws(new
ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() =>
_manufacturerBusinessLogicContract.InsertManufacturer(new(Guid.NewGuid().ToString
(), "name", null, null)), Throws.TypeOf<ElementExistsException>());
_manufacturerStorageContract.Verify(x =>
x.AddElement(It.IsAny<ManufacturerDataModel>()), Times.Once);
}
[Test]
public void InsertManufacturer_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_manufacturerBusinessLogicContract.InsertManufacturer(null),
Throws.TypeOf<ArgumentNullException>());
_manufacturerStorageContract.Verify(x =>
x.AddElement(It.IsAny<ManufacturerDataModel>()), Times.Never);
}
[Test]
public void InsertManufacturer_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_manufacturerBusinessLogicContract.InsertManufacturer(new
ManufacturerDataModel("id", "name", null, null)),
Throws.TypeOf<ValidationException>());
_manufacturerStorageContract.Verify(x =>
x.AddElement(It.IsAny<ManufacturerDataModel>()), Times.Never);
}
[Test]
public void InsertManufacturer_StorageThrowError_ThrowException_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x =>
x.AddElement(It.IsAny<ManufacturerDataModel>())).Throws(new StorageException(new
InvalidOperationException()));
//Act&Assert
Assert.That(() =>
_manufacturerBusinessLogicContract.InsertManufacturer(new(Guid.NewGuid().ToString
(), "name", null, null)), Throws.TypeOf<StorageException>());
_manufacturerStorageContract.Verify(x =>
x.AddElement(It.IsAny<ManufacturerDataModel>()), Times.Once);
}
[Test]
public void UpdateManufacturer_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new ManufacturerDataModel(Guid.NewGuid().ToString(),
"name", null, null);
_manufacturerStorageContract.Setup(x =>
x.UpdElement(It.IsAny<ManufacturerDataModel>()))
.Callback((ManufacturerDataModel x) =>
{
flag = x.Id == record.Id && x.ManufacturerName ==
record.ManufacturerName;
});
//Act
_manufacturerBusinessLogicContract.UpdateManufacturer(record);
//Assert
_manufacturerStorageContract.Verify(x =>
x.UpdElement(It.IsAny<ManufacturerDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void
UpdateManufacturer_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x =>
x.UpdElement(It.IsAny<ManufacturerDataModel>())).Throws(new
ElementNotFoundException(""));
//Act&Assert
Assert.That(() =>
_manufacturerBusinessLogicContract.UpdateManufacturer(new(Guid.NewGuid().ToString
(), "name", null, null)), Throws.TypeOf<ElementNotFoundException>());
_manufacturerStorageContract.Verify(x =>
x.UpdElement(It.IsAny<ManufacturerDataModel>()), Times.Once);
}
[Test]
public void UpdateManufacturer_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x =>
x.UpdElement(It.IsAny<ManufacturerDataModel>())).Throws(new
ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() =>
_manufacturerBusinessLogicContract.UpdateManufacturer(new(Guid.NewGuid().ToString
(), "name", null, null)), Throws.TypeOf<ElementExistsException>());
_manufacturerStorageContract.Verify(x =>
x.UpdElement(It.IsAny<ManufacturerDataModel>()), Times.Once);
}
[Test]
public void UpdateManufacturer_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_manufacturerBusinessLogicContract.UpdateManufacturer(null),
Throws.TypeOf<ArgumentNullException>());
_manufacturerStorageContract.Verify(x =>
x.UpdElement(It.IsAny<ManufacturerDataModel>()), Times.Never);
}
[Test]
public void UpdateManufacturer_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_manufacturerBusinessLogicContract.UpdateManufacturer(new
ManufacturerDataModel("id", "name", null, null)),
Throws.TypeOf<ValidationException>());
_manufacturerStorageContract.Verify(x =>
x.UpdElement(It.IsAny<ManufacturerDataModel>()), Times.Never);
}
[Test]
public void UpdateManufacturer_StorageThrowError_ThrowException_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x =>
x.UpdElement(It.IsAny<ManufacturerDataModel>())).Throws(new StorageException(new
InvalidOperationException()));
//Act&Assert
Assert.That(() =>
_manufacturerBusinessLogicContract.UpdateManufacturer(new(Guid.NewGuid().ToString
(), "name", null, null)), Throws.TypeOf<StorageException>());
_manufacturerStorageContract.Verify(x =>
x.UpdElement(It.IsAny<ManufacturerDataModel>()), Times.Once);
}
[Test]
public void DeleteManufacturer_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_manufacturerStorageContract.Setup(x => x.DelElement(It.Is((string x)
=> x == id))).Callback(() => { flag = true; });
//Act
_manufacturerBusinessLogicContract.DeleteManufacturer(id);
//Assert
_manufacturerStorageContract.Verify(x =>
x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void DeleteManufacturer_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_manufacturerStorageContract.Setup(x =>
x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() =>
_manufacturerBusinessLogicContract.DeleteManufacturer(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_manufacturerStorageContract.Verify(x =>
x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeleteManufacturer_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_manufacturerBusinessLogicContract.DeleteManufacturer(null),
Throws.TypeOf<ArgumentNullException>());
Assert.That(() =>
_manufacturerBusinessLogicContract.DeleteManufacturer(string.Empty),
Throws.TypeOf<ArgumentNullException>());
_manufacturerStorageContract.Verify(x =>
x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteManufacturer_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_manufacturerBusinessLogicContract.DeleteManufacturer("id"),
Throws.TypeOf<ValidationException>());
_manufacturerStorageContract.Verify(x =>
x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteManufacturer_StorageThrowError_ThrowException_Test()
{
//Arrange
_manufacturerStorageContract.Setup(x =>
x.DelElement(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException()));
//Act&Assert
Assert.That(() =>
_manufacturerBusinessLogicContract.DeleteManufacturer(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
_manufacturerStorageContract.Verify(x =>
x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -0,0 +1,556 @@
using Microsoft.Extensions.Logging;
using Moq;
using SmallSoftwareBusinessLogic.Implementations;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Enums;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.StoragesContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareTests.BusinessLogicsContractsTests;
[TestFixture]
internal class PostBusinessLogicContractTests
{
private PostBusinessLogicContract _postBusinessLogicContract;
private Mock<IPostStorageContract> _postStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_postStorageContract = new Mock<IPostStorageContract>();
_postBusinessLogicContract = new
PostBusinessLogicContract(_postStorageContract.Object, new
Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_postStorageContract.Reset();
}
[Test]
public void GetAllPosts_ReturnListOfRecords_Test()
{//Arrange
var listOriginal = new List<PostDataModel>()
{
new(Guid.NewGuid().ToString(),"name 1", PostType.SoftInstaller,
10),
new(Guid.NewGuid().ToString(), "name 2", PostType.SoftInstaller,
10),
new(Guid.NewGuid().ToString(), "name 3", PostType.SoftInstaller,
10),
};
_postStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
//Act
var list = _postBusinessLogicContract.GetAllPosts();
//Assert
Assert.Multiple(() =>
{
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_postStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllPosts_ReturnEmptyList_Test()
{
//Arrange
_postStorageContract.Setup(x =>
x.GetList()).Returns([]);
//Act
var listOnlyActive = _postBusinessLogicContract.GetAllPosts();
var listAll = _postBusinessLogicContract.GetAllPosts();
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(listAll, Is.Not.Null);
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(listAll, Has.Count.EqualTo(0));
});
_postStorageContract.Verify(x => x.GetList(),
Times.Exactly(2));
}
[Test]
public void GetAllPosts_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_postBusinessLogicContract.GetAllPosts(),
Throws.TypeOf<NullListException>());
_postStorageContract.Verify(x => x.GetList(),
Times.Once);
}
[Test]
public void GetAllPosts_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x =>
x.GetList()).Throws(new StorageException(new
InvalidOperationException()));
//Act&Assert
Assert.That(() =>
_postBusinessLogicContract.GetAllPosts(),
Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetList(),
Times.Once);
}
[Test]
public void GetAllDataOfPost_ReturnListOfRecords_Test()
{
//Arrange
var postId = Guid.NewGuid().ToString();
var listOriginal = new List<PostDataModel>()
{
new(postId, "name 1", PostType.SoftInstaller, 10),
new(postId, "name 2", PostType.SoftInstaller, 10)
};
_postStorageContract.Setup(x =>
x.GetPostWithHistory(It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _postBusinessLogicContract.GetAllDataOfPost(postId);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
_postStorageContract.Verify(x => x.GetPostWithHistory(postId),
Times.Once);
}
[Test]
public void GetAllDataOfPost_ReturnEmptyList_Test()
{
//Arrange
_postStorageContract.Setup(x =>
x.GetPostWithHistory(It.IsAny<string>())).Returns([]);
//Act
var list =
_postBusinessLogicContract.GetAllDataOfPost(Guid.NewGuid().ToString());
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_postStorageContract.Verify(x =>
x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllDataOfPost_PostIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(null),
Throws.TypeOf<ArgumentNullException>());
Assert.That(() =>
_postBusinessLogicContract.GetAllDataOfPost(string.Empty),
Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x =>
x.GetPostWithHistory(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllDataOfPost_PostIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost("id"),
Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x =>
x.GetPostWithHistory(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllDataOfPost_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_postBusinessLogicContract.GetAllDataOfPost(Guid.NewGuid().ToString()),
Throws.TypeOf<NullListException>());
_postStorageContract.Verify(x =>
x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllDataOfPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x =>
x.GetPostWithHistory(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException()));
//Act&Assert
Assert.That(() =>
_postBusinessLogicContract.GetAllDataOfPost(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x =>
x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new PostDataModel(id, "name", PostType.SoftInstaller, 10);
_postStorageContract.Setup(x =>
x.GetElementById(id)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_postStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_GetByName_ReturnRecord_Test()
{
//Arrange
var postName = "name";
var record = new PostDataModel(Guid.NewGuid().ToString(), postName,
PostType.SoftInstaller, 10);
_postStorageContract.Setup(x =>
x.GetElementByName(postName)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(postName);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.PostName, Is.EqualTo(postName));
_postStorageContract.Verify(x =>
x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData(null),
Throws.TypeOf<ArgumentNullException>());
Assert.That(() =>
_postBusinessLogicContract.GetPostByData(string.Empty),
Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Never);
_postStorageContract.Verify(x =>
x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetPostByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_postBusinessLogicContract.GetPostByData(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Once);
_postStorageContract.Verify(x =>
x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetPostByData_GetByName_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData("name"),
Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Never);
_postStorageContract.Verify(x =>
x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x =>
x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException()));
_postStorageContract.Setup(x =>
x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException()));
//Act&Assert
Assert.That(() =>
_postBusinessLogicContract.GetPostByData(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
Assert.That(() => _postBusinessLogicContract.GetPostByData("name"),
Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Once);
_postStorageContract.Verify(x =>
x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertPost_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name",
PostType.Supervisor, 10);
_postStorageContract.Setup(x =>
x.AddElement(It.IsAny<PostDataModel>()))
.Callback((PostDataModel x) =>
{
flag = x.Id == record.Id && x.PostName ==
record.PostName && x.PostType == record.PostType && x.Salary == record.Salary;
});
//Act
_postBusinessLogicContract.InsertPost(record);
//Assert
_postStorageContract.Verify(x =>
x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertPost_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x =>
x.AddElement(It.IsAny<PostDataModel>())).Throws(new
ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() =>
_postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name",
PostType.Supervisor, 10)),
Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x =>
x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void InsertPost_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(null),
Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x =>
x.AddElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void InsertPost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new
PostDataModel("id", "name", PostType.Supervisor, 10)),
Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x =>
x.AddElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void InsertPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x =>
x.AddElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new
InvalidOperationException()));
//Act&Assert
Assert.That(() =>
_postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name",
PostType.Supervisor, 10)),
Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x =>
x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void UpdatePost_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name",
PostType.Supervisor, 10);
_postStorageContract.Setup(x =>
x.UpdElement(It.IsAny<PostDataModel>()))
.Callback((PostDataModel x) =>
{
flag = x.Id == record.Id && x.PostName ==
record.PostName && x.PostType == record.PostType && x.Salary == record.Salary;
});
//Act
_postBusinessLogicContract.UpdatePost(record);
//Assert
_postStorageContract.Verify(x =>
x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdatePost_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x =>
x.UpdElement(It.IsAny<PostDataModel>())).Throws(new
ElementNotFoundException(""));
//Act&Assert
Assert.That(() =>
_postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name",
PostType.Supervisor, 10)),
Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x =>
x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void UpdatePost_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x =>
x.UpdElement(It.IsAny<PostDataModel>())).Throws(new
ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() =>
_postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme",
PostType.Supervisor, 10)),
Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x =>
x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void UpdatePost_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(null),
Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x =>
x.UpdElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void UpdatePost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new
PostDataModel("id", "name", PostType.Supervisor, 10)),
Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x =>
x.UpdElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void UpdatePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x =>
x.UpdElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new
InvalidOperationException()));
//Act&Assert
Assert.That(() =>
_postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name",
PostType.Supervisor, 10)),
Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x =>
x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void DeletePost_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_postStorageContract.Setup(x => x.DelElement(It.Is((string x) => x ==
id))).Callback(() => { flag = true; });
//Act
_postBusinessLogicContract.DeletePost(id);
//Assert
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()),
Times.Once);
Assert.That(flag);
}
[Test]
public void DeletePost_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_postStorageContract.Setup(x =>
x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() =>
_postBusinessLogicContract.DeletePost(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()),
Times.Once);
}
[Test]
public void DeletePost_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost(null),
Throws.TypeOf<ArgumentNullException>());
Assert.That(() =>
_postBusinessLogicContract.DeletePost(string.Empty),
Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()),
Times.Never);
}
[Test]
public void DeletePost_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost("id"),
Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()),
Times.Never);
}
[Test]
public void DeletePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x =>
x.DelElement(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException()));
//Act&Assert
Assert.That(() =>
_postBusinessLogicContract.DeletePost(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()),
Times.Once);
}
[Test]
public void RestorePost_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_postStorageContract.Setup(x => x.ResElement(It.Is((string x) => x ==
id))).Callback(() => { flag = true; });
//Act
_postBusinessLogicContract.RestorePost(id);
//Assert
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()),
Times.Once);
Assert.That(flag);
}
[Test]
public void RestorePost_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_postStorageContract.Setup(x =>
x.ResElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() =>
_postBusinessLogicContract.RestorePost(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()),
Times.Once);
}
[Test]
public void RestorePost_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost(null),
Throws.TypeOf<ArgumentNullException>());
Assert.That(() =>
_postBusinessLogicContract.RestorePost(string.Empty),
Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()),
Times.Never);
}
[Test]
public void RestorePost_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost("id"),
Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()),
Times.Never);
}
[Test]
public void RestorePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x =>
x.ResElement(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException()));
//Act&Assert
Assert.That(() =>
_postBusinessLogicContract.RestorePost(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()),
Times.Once);
}
}

View File

@@ -0,0 +1,535 @@
using Microsoft.Extensions.Logging;
using Moq;
using SmallSoftwareBusinessLogic.Implementations;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.StoragesContracts;
namespace SmallSoftwareTests.BusinessLogicsContractsTests;
[TestFixture]
internal class RequestBusinessLogicContractTests
{
private RequestBusinessLogicContract _requestBusinessLogicContract;
private Mock<IRequestStorageContract> _requestStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_requestStorageContract = new Mock<IRequestStorageContract>();
_requestBusinessLogicContract = new
RequestBusinessLogicContract(_requestStorageContract.Object, new
Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_requestStorageContract.Reset();
}
[Test]
public void GetAllRequestsByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var listOriginal = new List<RequestDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "test@mail.ru", false, [new InstallationRequestDataModel(Guid.NewGuid().ToString(),Guid.NewGuid().ToString(), 5, 10)], DateTime.UtcNow),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "test@mail.ru", false, [], DateTime.UtcNow), new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "test@mail.ru", false, [], DateTime.UtcNow),
};
_requestStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _requestBusinessLogicContract.GetAllRequestsByPeriod(date,
date.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_requestStorageContract.Verify(x => x.GetList(date, date.AddDays(1), null, null), Times.Once);
}
[Test]
public void GetAllRequestsByPeriod_ReturnEmptyList_Test()
{
//Arrange
_requestStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>())).Returns([]);
//Act
var list =
_requestBusinessLogicContract.GetAllRequestsByPeriod(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_requestStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllRequestsByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() =>
_requestBusinessLogicContract.GetAllRequestsByPeriod(date, date),
Throws.TypeOf<IncorrectDatesException>());
Assert.That(() =>
_requestBusinessLogicContract.GetAllRequestsByPeriod(date, date.AddSeconds(-1)),
Throws.TypeOf<IncorrectDatesException>());
_requestStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllRequestsByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_requestBusinessLogicContract.GetAllRequestsByPeriod(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_requestStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllRequestsByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_requestStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException()));
//Act&Assert
Assert.That(() =>
_requestBusinessLogicContract.GetAllRequestsByPeriod(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_requestStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllRequestsByWorkerByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var workerId = Guid.NewGuid().ToString();
var listOriginal = new List<RequestDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), false, [new InstallationRequestDataModel(Guid.NewGuid().ToString(),Guid.NewGuid().ToString(), 5, 10)], DateTime.UtcNow),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), false, [], DateTime.UtcNow), new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), false, [], DateTime.UtcNow),
};
_requestStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>())).Returns(listOriginal);
//Act
var list =
_requestBusinessLogicContract.GetAllRequestsByWorkerByPeriod(workerId, date,
date.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_requestStorageContract.Verify(x => x.GetList(date, date.AddDays(1),
workerId, null), Times.Once);
}
[Test]
public void GetAllRequestsByWorkerByPeriod_ReturnEmptyList_Test()
{
//Arrange
_requestStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>())).Returns([]);
//Act
var list =
_requestBusinessLogicContract.GetAllRequestsByWorkerByPeriod(Guid.NewGuid().ToString(),
DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_requestStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Once);
}
[Test]
public void
GetAllRequestsByWorkerByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() =>
_requestBusinessLogicContract.GetAllRequestsByWorkerByPeriod(Guid.NewGuid().ToString(),
date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() =>
_requestBusinessLogicContract.GetAllRequestsByWorkerByPeriod(Guid.NewGuid().ToString(),
date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_requestStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Never);
}
[Test]
public void
GetAllRequestsByWorkerByPeriod_WorkerIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_requestBusinessLogicContract.GetAllRequestsByWorkerByPeriod(null, DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() =>
_requestBusinessLogicContract.GetAllRequestsByWorkerByPeriod(string.Empty,
DateTime.UtcNow, DateTime.UtcNow.AddDays(1)),
Throws.TypeOf<ArgumentNullException>());
_requestStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllRequestsByWorkerByPeriod_WorkerIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_requestBusinessLogicContract.GetAllRequestsByWorkerByPeriod("workerId",
DateTime.UtcNow, DateTime.UtcNow.AddDays(1)),
Throws.TypeOf<ValidationException>());
_requestStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllRequestsByWorkerByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_requestBusinessLogicContract.GetAllRequestsByWorkerByPeriod(Guid.NewGuid().ToString(),
DateTime.UtcNow, DateTime.UtcNow.AddDays(1)),
Throws.TypeOf<NullListException>());
_requestStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Once);
}
[Test]
public void
GetAllRequestsByWorkerByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_requestStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException()));
//Act&Assert
Assert.That(() =>
_requestBusinessLogicContract.GetAllRequestsByWorkerByPeriod(Guid.NewGuid().ToString(),
DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_requestStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllRequestsBySoftwareByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var softwareId = Guid.NewGuid().ToString();
var listOriginal = new List<RequestDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "test@mail.ru", false, [new InstallationRequestDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 10)], DateTime.UtcNow),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "test@mail.ru", false, [], DateTime.UtcNow),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "test@mail.ru", false, [], DateTime.UtcNow),
};
_requestStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>())).Returns(listOriginal);
//Act
var list =
_requestBusinessLogicContract.GetAllRequestsBySoftwareByPeriod(softwareId, date,
date.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_requestStorageContract.Verify(x => x.GetList(date, date.AddDays(1), null, softwareId), Times.Once);
}
[Test]
public void GetAllRequestsBySoftwareByPeriod_ReturnEmptyList_Test()
{
//Arrange
_requestStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>())).Returns([]);
//Act
var list =
_requestBusinessLogicContract.GetAllRequestsBySoftwareByPeriod(Guid.NewGuid().ToString()
, DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_requestStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Once);
}
[Test]
public void
GetAllRequestsBySoftwareByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() =>
_requestBusinessLogicContract.GetAllRequestsBySoftwareByPeriod(Guid.NewGuid().ToString()
, date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() =>
_requestBusinessLogicContract.GetAllRequestsBySoftwareByPeriod(Guid.NewGuid().ToString()
, date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_requestStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Never);
}
[Test]
public void
GetAllRequestsBySoftwareByPeriod_SoftwareIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_requestBusinessLogicContract.GetAllRequestsBySoftwareByPeriod(null, DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() =>
_requestBusinessLogicContract.GetAllRequestsBySoftwareByPeriod(string.Empty, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)),
Throws.TypeOf<ArgumentNullException>());
_requestStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Never);
}
[Test]
public void
GetAllRequestsBySoftwareByPeriod_SoftwareIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_requestBusinessLogicContract.GetAllRequestsBySoftwareByPeriod("softwareId",
DateTime.UtcNow, DateTime.UtcNow.AddDays(1)),
Throws.TypeOf<ValidationException>());
_requestStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllRequestsBySoftwareByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_requestBusinessLogicContract.GetAllRequestsBySoftwareByPeriod(Guid.NewGuid().ToString()
, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)),
Throws.TypeOf<NullListException>());
_requestStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Once);
}
[Test]
public void
GetAllRequestsBySoftwareByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_requestStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException()));
//Act&Assert
Assert.That(() =>
_requestBusinessLogicContract.GetAllRequestsBySoftwareByPeriod(Guid.NewGuid().ToString()
, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)),
Throws.TypeOf<StorageException>());
_requestStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<string>(),
It.IsAny<string>()), Times.Once);
}
[Test]
public void GetRequestByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new RequestDataModel(id, Guid.NewGuid().ToString(), "test@mail.ru", false, [new InstallationRequestDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 10)], DateTime.UtcNow);
_requestStorageContract.Setup(x =>
x.GetElementById(id)).Returns(record);
//Act
var element = _requestBusinessLogicContract.GetRequestByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_requestStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetRequestByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _requestBusinessLogicContract.GetRequestByData(null),
Throws.TypeOf<ArgumentNullException>());
Assert.That(() =>
_requestBusinessLogicContract.GetRequestByData(string.Empty),
Throws.TypeOf<ArgumentNullException>());
_requestStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetRequestByData_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _requestBusinessLogicContract.GetRequestByData("requestId"),
Throws.TypeOf<ValidationException>());
_requestStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetRequestByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_requestBusinessLogicContract.GetRequestByData(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_requestStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetRequestByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_requestStorageContract.Setup(x =>
x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException()));
//Act&Assert
Assert.That(() =>
_requestBusinessLogicContract.GetRequestByData(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
_requestStorageContract.Verify(x =>
x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertRequest_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new RequestDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "valid.email@example.com", false,
[new InstallationRequestDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 10)], DateTime.UtcNow);
_requestStorageContract.Setup(x => x.AddElement(It.IsAny<RequestDataModel>()))
.Callback((RequestDataModel x) =>
{
flag = x.Id == record.Id && x.WorkerId == record.WorkerId && x.IsCancel ==
record.IsCancel && x.Softwares.Count == record.Softwares.Count &&
x.Softwares.First().SoftwareId ==
record.Softwares.First().SoftwareId &&
x.Softwares.First().RequestId ==
record.Softwares.First().RequestId &&
x.Softwares.First().Count ==
record.Softwares.First().Count;
});
//Act
_requestBusinessLogicContract.InsertRequest(record);
//Assert
_requestStorageContract.Verify(x =>
x.AddElement(It.IsAny<RequestDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertRequest_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_requestStorageContract.Setup(x =>
x.AddElement(It.IsAny<RequestDataModel>())).Throws(new
ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() =>
_requestBusinessLogicContract.InsertRequest(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "test@example.com", false,
[new InstallationRequestDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 10)], DateTime.UtcNow)), Throws.TypeOf<ElementExistsException>());
_requestStorageContract.Verify(x => x.AddElement(It.IsAny<RequestDataModel>()), Times.Once);
}
[Test]
public void InsertRequest_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _requestBusinessLogicContract.InsertRequest(null),
Throws.TypeOf<ArgumentNullException>());
_requestStorageContract.Verify(x =>
x.AddElement(It.IsAny<RequestDataModel>()), Times.Never);
}
[Test]
public void InsertRequest_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _requestBusinessLogicContract.InsertRequest(new RequestDataModel("id", Guid.NewGuid().ToString(), "test@mail.ru", false, [], DateTime.UtcNow)), Throws.TypeOf<ValidationException>());
_requestStorageContract.Verify(x =>
x.AddElement(It.IsAny<RequestDataModel>()), Times.Never);
}
[Test]
public void InsertRequest_StorageThrowError_ThrowException_Test()
{
//Arrange
_requestStorageContract.Setup(x =>
x.AddElement(It.IsAny<RequestDataModel>())).Throws(new StorageException(new
InvalidOperationException()));
//Act&Assert
Assert.That(() =>
_requestBusinessLogicContract.InsertRequest(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "test@example.com", false, [new InstallationRequestDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 10)], DateTime.UtcNow)), Throws.TypeOf<StorageException>());
_requestStorageContract.Verify(x =>
x.AddElement(It.IsAny<RequestDataModel>()), Times.Once);
}
[Test]
public void CancelRequest_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_requestStorageContract.Setup(x => x.DelElement(It.Is((string x) => x ==
id))).Callback(() => { flag = true; });
//Act
_requestBusinessLogicContract.CancelRequest(id);
//Assert
_requestStorageContract.Verify(x => x.DelElement(It.IsAny<string>()),
Times.Once);
Assert.That(flag);
}
[Test]
public void CancelRequest_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_requestStorageContract.Setup(x =>
x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() =>
_requestBusinessLogicContract.CancelRequest(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_requestStorageContract.Verify(x => x.DelElement(It.IsAny<string>()),
Times.Once);
}
[Test]
public void CancelRequest_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _requestBusinessLogicContract.CancelRequest(null),
Throws.TypeOf<ArgumentNullException>());
Assert.That(() =>
_requestBusinessLogicContract.CancelRequest(string.Empty),
Throws.TypeOf<ArgumentNullException>());
_requestStorageContract.Verify(x => x.DelElement(It.IsAny<string>()),
Times.Never);
}
[Test]
public void CancelRequest_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _requestBusinessLogicContract.CancelRequest("id"),
Throws.TypeOf<ValidationException>());
_requestStorageContract.Verify(x => x.DelElement(It.IsAny<string>()),
Times.Never);
}
[Test]
public void CancelRequest_StorageThrowError_ThrowException_Test()
{
//Arrange
_requestStorageContract.Setup(x =>
x.DelElement(It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException()));
//Act&Assert
Assert.That(() =>
_requestBusinessLogicContract.CancelRequest(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
_requestStorageContract.Verify(x => x.DelElement(It.IsAny<string>()),
Times.Once);
}
}

View File

@@ -0,0 +1,581 @@
using Microsoft.Extensions.Logging;
using Moq;
using SmallSoftwareBusinessLogic.Implementations;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Enums;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Infrastructure.PostConfigurations;
using SmallSoftwareContracts.StoragesContracts;
using SmallSoftwareDatabase.Implementations;
using SmallSoftwareTests.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareTests.BusinessLogicsContractsTests;
[TestFixture]
internal class SalaryBusinessLogicContractTests
{
private SalaryBusinessLogicContract _salaryBusinessLogicContract;
private Mock<ISalaryStorageContract> _salaryStorageContract;
private Mock<IRequestStorageContract> _requestStorageContract;
private Mock<IPostStorageContract> _postStorageContract;
private Mock<IWorkerStorageContract> _workerStorageContract;
private readonly ConfigurationSalaryTest _salaryConfigurationTest = new();
[OneTimeSetUp]
public void OneTimeSetUp()
{
_salaryStorageContract = new Mock<ISalaryStorageContract>();
_requestStorageContract = new Mock<IRequestStorageContract>();
_postStorageContract = new Mock<IPostStorageContract>();
_workerStorageContract = new Mock<IWorkerStorageContract>();
_salaryBusinessLogicContract = new SalaryBusinessLogicContract(_salaryStorageContract.Object, _requestStorageContract.Object,
_postStorageContract.Object, _workerStorageContract.Object, new Mock<ILogger>().Object, _salaryConfigurationTest);
}
[SetUp]
public void SetUp()
{
_salaryStorageContract.Reset();
_requestStorageContract.Reset();
_postStorageContract.Reset();
_workerStorageContract.Reset();
}
[Test]
public void GetAllSalaries_ReturnListOfRecords_Test()
{
//Arrange
var startDate = DateTime.UtcNow;
var endDate = DateTime.UtcNow.AddDays(1);
var listOriginal = new List<SalaryDataModel>()
{
new(Guid.NewGuid().ToString(), DateTime.UtcNow, 10),
new(Guid.NewGuid().ToString(), DateTime.UtcNow.AddDays(1),
14),
new(Guid.NewGuid().ToString(), DateTime.UtcNow.AddDays(-1),
30),
};
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list =
_salaryBusinessLogicContract.GetAllSalariesByPeriod(startDate, endDate);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_salaryStorageContract.Verify(x => x.GetList(startDate, endDate,
null), Times.Once);
}
[Test]
public void GetAllSalaries_ReturnEmptyList_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<string>())).Returns([]);
//Act
var list =
_salaryBusinessLogicContract.GetAllSalariesByPeriod(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalaries_IncorrectDates_ThrowException_Test()
{
//Arrange
var dateTime = DateTime.UtcNow;
//Act&Assert
Assert.That(() =>
_salaryBusinessLogicContract.GetAllSalariesByPeriod(dateTime, dateTime),
Throws.TypeOf<IncorrectDatesException>());
Assert.That(() =>
_salaryBusinessLogicContract.GetAllSalariesByPeriod(dateTime,
dateTime.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalaries_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_salaryBusinessLogicContract.GetAllSalariesByPeriod(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalaries_StorageThrowError_ThrowException_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException()));
//Act&Assert
Assert.That(() =>
_salaryBusinessLogicContract.GetAllSalariesByPeriod(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalariesByWorker_ReturnListOfRecords_Test()
{
//Arrange
var startDate = DateTime.UtcNow;
var endDate = DateTime.UtcNow.AddDays(1);
var workerId = Guid.NewGuid().ToString();
var listOriginal = new List<SalaryDataModel>()
{
new(Guid.NewGuid().ToString(), DateTime.UtcNow, 10),
new(Guid.NewGuid().ToString(), DateTime.UtcNow.AddDays(1),
14),
new(Guid.NewGuid().ToString(), DateTime.UtcNow.AddDays(-1),
30),
};
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list =
_salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(startDate, endDate,
workerId);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_salaryStorageContract.Verify(x => x.GetList(startDate, endDate,
workerId), Times.Once);
}
[Test]
public void GetAllSalariesByWorker_ReturnEmptyList_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<string>())).Returns([]);
//Act
var list =
_salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1), Guid.NewGuid().ToString());
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalariesByWorker_IncorrectDates_ThrowException_Test()
{
//Arrange
var dateTime = DateTime.UtcNow;
//Act&Assert
Assert.That(() =>
_salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(dateTime, dateTime,
Guid.NewGuid().ToString()), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() =>
_salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(dateTime,
dateTime.AddSeconds(-1), Guid.NewGuid().ToString()),
Throws.TypeOf<IncorrectDatesException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void
GetAllSalariesByWorker_WorkerIdIsNUllOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1), null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() =>
_salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1), string.Empty),
Throws.TypeOf<ArgumentNullException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalariesByWorker_WorkerIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1), "workerId"), Throws.TypeOf<ValidationException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalariesByWorker_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1), Guid.NewGuid().ToString()),
Throws.TypeOf<NullListException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalariesByWorker_StorageThrowError_ThrowException_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<string>())).Throws(new StorageException(new
InvalidOperationException()));
//Act&Assert
Assert.That(() =>
_salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(DateTime.UtcNow,
DateTime.UtcNow.AddDays(1), Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void CalculateSalaryByMonth_CalculateSalary_Test()
{
// Arrange
var workerId = Guid.NewGuid().ToString();
var postId = Guid.NewGuid().ToString();
var rate = 1000.0;
// Настраиваем моки
_postStorageContract.Setup(x => x.GetElementById(postId))
.Returns(new PostDataModel(postId, "TestPost", PostType.CashierConsultant, rate));
_requestStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(),
It.IsAny<string>()))
.Returns([new RequestDataModel(Guid.NewGuid().ToString(), workerId, "emmmail@mail.ru", false,
[new InstallationRequestDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)], DateTime.UtcNow)]);
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", postId,
DateTime.UtcNow.AddYears(-20), DateTime.UtcNow.AddYears(-1),
false, new PostConfiguration { Rate = rate })]);
double actualSum = 0;
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>())).Callback((SalaryDataModel x) => actualSum = x.Salary);
// Act
_salaryBusinessLogicContract.CalculateSalaryByMonth(DateTime.UtcNow);
// Assert
Assert.That(actualSum, Is.EqualTo(rate));
}
[Test]
public void CalculateSalaryByMonth_WithSeveralWorkers_Test()
{
// Arrange
var postId = Guid.NewGuid().ToString();
var rate = 1000.0;
// Настраиваем мок для PostStorage
_postStorageContract.Setup(x => x.GetElementById(postId))
.Returns(new PostDataModel(postId, "TestPost", PostType.SoftInstaller, rate));
var workers = new List<WorkerDataModel>
{
new(Guid.NewGuid().ToString(), "Test1", postId, DateTime.UtcNow.AddYears(-20), DateTime.UtcNow.AddYears(-1), false, new PostConfiguration { Rate = rate }),
new(Guid.NewGuid().ToString(), "Test2", postId, DateTime.UtcNow.AddYears(-20), DateTime.UtcNow.AddYears(-1), false, new PostConfiguration { Rate = rate }),
new(Guid.NewGuid().ToString(), "Test3", postId, DateTime.UtcNow.AddYears(-20), DateTime.UtcNow.AddYears(-1), false, new PostConfiguration { Rate = rate })
};
// Настраиваем мок для WorkerStorage
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns(workers);
// Настраиваем мок для RequestStorage
_requestStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns(workers.Select(w =>
new RequestDataModel(Guid.NewGuid().ToString(), w.Id, "email@mail.ru",false, [], DateTime.UtcNow)).ToList());
// Act
_salaryBusinessLogicContract.CalculateSalaryByMonth(DateTime.UtcNow);
// Assert
_salaryStorageContract.Verify(x => x.AddElement(It.IsAny<SalaryDataModel>()), Times.Exactly(workers.Count));
}
[Test]
public void CalculateSalaryByMonth_WithoutSalesByWorker_Test()
{
// Arrange
var workerId = Guid.NewGuid().ToString();
var postId = Guid.NewGuid().ToString();
var rate = 2000.0;
_postStorageContract.Setup(x => x.GetElementById(postId))
.Returns(new PostDataModel(postId, "TestPost", PostType.SoftInstaller, rate));
_requestStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>())).Returns([]);
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", postId,
DateTime.UtcNow.AddYears(-20), DateTime.UtcNow.AddYears(-1),
false, new PostConfiguration { Rate = rate })]);
double sum = 0;
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
.Callback((SalaryDataModel x) => sum = x.Salary);
// Act
_salaryBusinessLogicContract.CalculateSalaryByMonth(DateTime.UtcNow);
// Assert
Assert.That(sum, Is.EqualTo(rate));
}
[Test]
public void CalculateSalaryByMonth_RequestStorageReturnNull_ThrowException_Test()
{
// Arrange
var workerId = Guid.NewGuid().ToString();
var postId = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.GetElementById(postId))
.Returns(new PostDataModel(postId, "TestPost", PostType.SoftInstaller, 1000));
_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", postId,
DateTime.UtcNow.AddYears(-20), DateTime.UtcNow.AddYears(-1),
false, new PostConfiguration { Rate = 1000 })]);
// Act & Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMonth(DateTime.UtcNow),
Throws.TypeOf<NullListException>());
}
[Test]
public void CalculateSalaryByMonth_PostStorageReturnNull_ThrowException_Test()
{
// Arrange
var workerId = Guid.NewGuid().ToString();
var postId = Guid.NewGuid().ToString();
// Настраиваем моки
_requestStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(),
It.IsAny<string>(), It.IsAny<string>()))
.Returns([new RequestDataModel(Guid.NewGuid().ToString(), workerId, "email@mail.ru", false, [], DateTime.UtcNow)]);
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", postId,
DateTime.UtcNow.AddYears(-20), DateTime.UtcNow.AddYears(-1),
false, new PostConfiguration { Rate = 1000 })]);
// PostStorage возвращает null
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns((PostDataModel)null);
// Act & Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMonth(DateTime.UtcNow),
Throws.TypeOf<NullListException>());
}
[Test]
public void CalculateSalaryByMonth_WorkerStorageReturnNull_ThrowException_Test()
{
// Arrange
var workerId = Guid.NewGuid().ToString();
var postId = Guid.NewGuid().ToString();
// Настраиваем моки
_requestStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(),
It.IsAny<string>(), It.IsAny<string>()))
.Returns([new RequestDataModel(Guid.NewGuid().ToString(), workerId, "email@mail.ru", false, [], DateTime.UtcNow)]);
// WorkerStorage возвращает null
_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<WorkerDataModel>)null);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(postId, "TestPost", PostType.SoftInstaller, 1000));
// Act & Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMonth(DateTime.UtcNow),
Throws.TypeOf<NullListException>());
}
[Test]
public void CalculateSalaryByMonth_RequestStorageThrowException_ThrowException_Test()
{
// Arrange
var workerId = Guid.NewGuid().ToString();
var postId = Guid.NewGuid().ToString();
// RequestStorage выбрасывает исключение
_requestStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(),
It.IsAny<string>(), It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", postId,
DateTime.UtcNow.AddYears(-20), DateTime.UtcNow.AddYears(-1),
false, new PostConfiguration { Rate = 1000 })]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(postId, "TestPost", PostType.SoftInstaller, 1000));
// Act & Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMonth(DateTime.UtcNow),
Throws.TypeOf<StorageException>());
}
[Test]
public void CalculateSalaryByMonth_PostStorageThrowException_ThrowException_Test()
{
// Arrange
var workerId = Guid.NewGuid().ToString();
var postId = Guid.NewGuid().ToString();
// Настраиваем моки
_requestStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(),
It.IsAny<string>(), It.IsAny<string>()))
.Returns([new RequestDataModel(Guid.NewGuid().ToString(), workerId, "email@mail.ru", false, [], DateTime.UtcNow)]);
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", postId,
DateTime.UtcNow.AddYears(-20), DateTime.UtcNow.AddYears(-1),
false, new PostConfiguration { Rate = 1000 })]);
// PostStorage выбрасывает исключение
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMonth(DateTime.UtcNow),
Throws.TypeOf<StorageException>());
}
[Test]
public void CalculateSalaryByMonth_WorkerStorageThrowException_ThrowException_Test()
{
// Arrange
var workerId = Guid.NewGuid().ToString();
var postId = Guid.NewGuid().ToString();
// Настраиваем моки
_requestStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(),
It.IsAny<string>(), It.IsAny<string>()))
.Returns([new RequestDataModel(Guid.NewGuid().ToString(), workerId, "email@mail.ru", false, [], DateTime.UtcNow)]);
// WorkerStorage выбрасывает исключение
_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()));
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(postId, "TestPost", PostType.SoftInstaller, 1000));
// Act & Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMonth(DateTime.UtcNow),
Throws.TypeOf<StorageException>());
}
[Test]
public void CalculateSalaryByMonth_WithCashierPostConfiguration_CalculateSalary_Test()
{
// Arrange
var workerId = Guid.NewGuid().ToString();
var postId = Guid.NewGuid().ToString();
var config = new CashierPostConfiguration
{
Rate = 2000,
SalePercent = 0.1,
BonusForExtraSales = 0.5
};
var sales = new List<RequestDataModel>()
{
new(Guid.NewGuid().ToString(), workerId, "eemail@maiil.ru", false,
[new InstallationRequestDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)], DateTime.UtcNow),
new(Guid.NewGuid().ToString(), workerId, "eeemail@maiiil.ru", false,
[new InstallationRequestDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)], DateTime.UtcNow),
new(Guid.NewGuid().ToString(), workerId, "eeeemail@mail.ru", false,
[new InstallationRequestDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5000, 12)], DateTime.UtcNow)
};
_postStorageContract.Setup(x => x.GetElementById(postId))
.Returns(new PostDataModel(postId, "CashierConsultant", PostType.CashierConsultant, config.Rate));
_requestStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns(sales);
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", postId,
DateTime.UtcNow.AddYears(-20), DateTime.UtcNow.AddYears(-1),
false, config)]);
double sum = 0;
var expectedSum = config.Rate + (config.SalePercent * sales.Average(x => x.Sum)) +
(sales.Where(x => x.Sum > _salaryConfigurationTest.ExtraSaleSum).Sum(x => x.Sum) * config.BonusForExtraSales);
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
.Callback((SalaryDataModel x) => sum = x.Salary);
// Act
_salaryBusinessLogicContract.CalculateSalaryByMonth(DateTime.UtcNow);
// Assert
Assert.That(sum, Is.EqualTo(expectedSum));
}
[Test]
public void CalculateSalaryByMonth_WithSupervisorPostConfiguration_CalculateSalary_Test()
{
// Arrange
var workerId = Guid.NewGuid().ToString();
var postId = Guid.NewGuid().ToString();
var rate = 2000.0;
var trend = 3;
var bonus = 100;
// Конфигурация для супервайзера
var supervisorConfig = new SupervisorPostConfiguration()
{
Rate = rate,
PersonalCountTrendPremium = bonus
};
// Настраиваем моки
_requestStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(),
It.IsAny<string>(), It.IsAny<string>()))
.Returns([new RequestDataModel(Guid.NewGuid().ToString(), workerId, "email@mail.ru", false,
[new InstallationRequestDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)], DateTime.UtcNow)]);
_postStorageContract.Setup(x => x.GetElementById(postId))
.Returns(new PostDataModel(postId, "Supervisor", PostType.Supervisor, supervisorConfig.Rate));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(),
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", postId,
DateTime.UtcNow.AddYears(-20), DateTime.UtcNow.AddYears(-1),
false, supervisorConfig)]);
_workerStorageContract.Setup(x => x.GetWorkerTrend(It.IsAny<DateTime>(), It.IsAny<DateTime>()))
.Returns(trend);
double actualSum = 0;
var expectedSum = rate + (trend * bonus);
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
.Callback((SalaryDataModel x) => actualSum = x.Salary);
// Act
_salaryBusinessLogicContract.CalculateSalaryByMonth(DateTime.UtcNow);
// Assert
Assert.That(actualSum, Is.EqualTo(expectedSum));
}
}

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