7 Commits

Author SHA1 Message Date
IlyasValiulov
2e3e638492 правка 2025-04-24 09:25:21 +04:00
IlyasValiulov
9a212807f1 Правка ресурсов 2025-04-24 09:01:28 +04:00
IlyasValiulov
ccec9eb320 правка 2025-04-24 00:06:48 +04:00
IlyasValiulov
e7afcdbae4 лаба 7 2025-04-23 01:33:51 +04:00
IlyasValiulov
3d5bc1dfc0 лаба 6 пдф 2025-04-17 20:38:14 +04:00
IlyasValiulov
1bfb035c63 Отчеты word+excel 2025-04-16 19:38:27 +04:00
IlyasValiulov
ec71832652 Лаба 5(конфигурация в работнике) 2025-04-15 17:30:37 +04:00
127 changed files with 4380 additions and 1552 deletions

View File

@@ -13,7 +13,9 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.3" />
<PackageReference Include="DocumentFormat.OpenXml" Version="3.3.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.2" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
</ItemGroup>
<ItemGroup>

View File

@@ -2,21 +2,24 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Extentions;
using FurnitureAssemblyContracts.Resources;
using FurnitureAssemblyContracts.StoragesContracts;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace FurnitureAssemblyBusinessLogic.Implementations;
internal class ComponentBusinessLogicContract(IComponentStorageContract componentStorageContract, ILogger logger) : IComponentBusinessLogicContract
internal class ComponentBusinessLogicContract(IComponentStorageContract componentStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : IComponentBusinessLogicContract
{
private readonly IComponentStorageContract _componentStorageContract = componentStorageContract;
private readonly ILogger _logger = logger;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<ComponentDataModel> GetAllComponents()
{
_logger.LogInformation("GetAllComponents");
return _componentStorageContract.GetList() ?? throw new NullListException();
return _componentStorageContract.GetList();
}
public ComponentDataModel GetComponentByData(string data)
@@ -28,17 +31,17 @@ internal class ComponentBusinessLogicContract(IComponentStorageContract componen
}
if (data.IsGuid())
{
return _componentStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return _componentStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data, _localizer);
}
return _componentStorageContract.GetElementByName(data) ?? _componentStorageContract.GetElementByOldName(data) ??
throw new ElementNotFoundException(data);
throw new ElementNotFoundException(data, _localizer);
}
public void InsertComponent(ComponentDataModel componentDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(componentDataModel));
ArgumentNullException.ThrowIfNull(componentDataModel);
componentDataModel.Validate();
componentDataModel.Validate(_localizer);
_componentStorageContract.AddElement(componentDataModel);
}
@@ -46,7 +49,7 @@ internal class ComponentBusinessLogicContract(IComponentStorageContract componen
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(componentDataModel));
ArgumentNullException.ThrowIfNull(componentDataModel);
componentDataModel.Validate();
componentDataModel.Validate(_localizer);
_componentStorageContract.UpdElement(componentDataModel);
}
@@ -59,7 +62,7 @@ internal class ComponentBusinessLogicContract(IComponentStorageContract componen
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
}
_componentStorageContract.DelElement(id);
}

View File

@@ -2,21 +2,24 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Extentions;
using FurnitureAssemblyContracts.Resources;
using FurnitureAssemblyContracts.StoragesContracts;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace FurnitureAssemblyBusinessLogic.Implementations;
internal class FurnitureBusinessLogicContract(IFurnitureStorageContract furnitureStorageContract, ILogger logger) : IFurnitureBusinessLogicContract
internal class FurnitureBusinessLogicContract(IFurnitureStorageContract furnitureStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : IFurnitureBusinessLogicContract
{
IFurnitureStorageContract _furnitureStorageContract = furnitureStorageContract;
private readonly ILogger _logger = logger;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<FurnitureDataModel> GetAllFurnitures()
{
_logger.LogInformation("GetAllFurnitures");
return furnitureStorageContract.GetList() ?? throw new NullListException();
return furnitureStorageContract.GetList();
}
public FurnitureDataModel GetFurnitureByData(string data)
@@ -28,16 +31,16 @@ internal class FurnitureBusinessLogicContract(IFurnitureStorageContract furnitur
}
if (data.IsGuid())
{
return _furnitureStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return _furnitureStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data, _localizer);
}
return _furnitureStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data);
return _furnitureStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data, _localizer);
}
public void InsertFurniture(FurnitureDataModel furnitureDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(furnitureDataModel));
ArgumentNullException.ThrowIfNull(furnitureDataModel);
furnitureDataModel.Validate();
furnitureDataModel.Validate(_localizer);
_furnitureStorageContract.AddElement(furnitureDataModel);
}
@@ -45,7 +48,7 @@ internal class FurnitureBusinessLogicContract(IFurnitureStorageContract furnitur
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(furnitureDataModel));
ArgumentNullException.ThrowIfNull(furnitureDataModel);
furnitureDataModel.Validate();
furnitureDataModel.Validate(_localizer);
_furnitureStorageContract.UpdElement(furnitureDataModel);
}
@@ -58,7 +61,7 @@ internal class FurnitureBusinessLogicContract(IFurnitureStorageContract furnitur
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
}
_furnitureStorageContract.DelElement(id);
}

View File

@@ -2,23 +2,26 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Extentions;
using FurnitureAssemblyContracts.Resources;
using FurnitureAssemblyContracts.StoragesContracts;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace FurnitureAssemblyBusinessLogic.Implementations;
internal class ManifacturingBusinessLogicContract(IManifacturingStorageContract manifacturingStorageContract, ILogger logger) : IManifacturingBusinessLogicContract
internal class ManifacturingBusinessLogicContract(IManifacturingStorageContract manifacturingStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : IManifacturingBusinessLogicContract
{
IManifacturingStorageContract _manifacturingStorageContract = manifacturingStorageContract;
private readonly ILogger _logger = logger;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<ManifacturingFurnitureDataModel> GetAllManifacturingByFurnitureByPeriod(string furnitureId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {furnitureId}, {fromDate}, { toDate}", furnitureId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
throw new IncorrectDatesException(fromDate, toDate, _localizer);
}
if (furnitureId.IsEmpty())
{
@@ -26,9 +29,9 @@ internal class ManifacturingBusinessLogicContract(IManifacturingStorageContract
}
if (!furnitureId.IsGuid())
{
throw new ValidationException("The value in the field furnitureId is not a unique identifier.");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "FurnitureId"));
}
return _manifacturingStorageContract.GetList(fromDate, toDate, furnitureId: furnitureId) ?? throw new NullListException();
return _manifacturingStorageContract.GetList(fromDate, toDate, furnitureId: furnitureId);
}
public List<ManifacturingFurnitureDataModel> GetAllManifacturingByWorkerByPeriod(string workerId, DateTime fromDate, DateTime toDate)
@@ -36,7 +39,7 @@ internal class ManifacturingBusinessLogicContract(IManifacturingStorageContract
_logger.LogInformation("GetAllSales params: {workerId}, {fromDate}, { toDate}", workerId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
throw new IncorrectDatesException(fromDate, toDate, _localizer);
}
if (workerId.IsEmpty())
{
@@ -44,9 +47,9 @@ internal class ManifacturingBusinessLogicContract(IManifacturingStorageContract
}
if (!workerId.IsGuid())
{
throw new ValidationException("The value in the field workerId is not a unique identifier.");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "WorkerId"));
}
return _manifacturingStorageContract.GetList(fromDate, toDate, workerId: workerId) ?? throw new NullListException();
return _manifacturingStorageContract.GetList(fromDate, toDate, workerId: workerId);
}
public List<ManifacturingFurnitureDataModel> GetManifacturingByPeriod(DateTime fromDate, DateTime toDate)
@@ -54,9 +57,9 @@ internal class ManifacturingBusinessLogicContract(IManifacturingStorageContract
_logger.LogInformation("GetAllSales params: {fromDate}, {toDate}", fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
throw new IncorrectDatesException(fromDate, toDate, _localizer);
}
return _manifacturingStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
return _manifacturingStorageContract.GetList(fromDate, toDate);
}
public ManifacturingFurnitureDataModel GetManifacturingByData(string data)
@@ -68,16 +71,16 @@ internal class ManifacturingBusinessLogicContract(IManifacturingStorageContract
}
if (!data.IsGuid())
{
throw new ValidationException("Id is not a uniqueidentifier");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
}
return _manifacturingStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return _manifacturingStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data, _localizer);
}
public void InsertFurniture(ManifacturingFurnitureDataModel manifacturingDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(manifacturingDataModel));
ArgumentNullException.ThrowIfNull(manifacturingDataModel);
manifacturingDataModel.Validate();
manifacturingDataModel.Validate(_localizer);
_manifacturingStorageContract.AddElement(manifacturingDataModel);
}
@@ -85,7 +88,7 @@ internal class ManifacturingBusinessLogicContract(IManifacturingStorageContract
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(manifacturingDataModel));
ArgumentNullException.ThrowIfNull(manifacturingDataModel);
manifacturingDataModel.Validate();
manifacturingDataModel.Validate(_localizer);
_manifacturingStorageContract.UpdElement(manifacturingDataModel);
}
}

View File

@@ -2,16 +2,19 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Extentions;
using FurnitureAssemblyContracts.Resources;
using FurnitureAssemblyContracts.StoragesContracts;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace FurnitureAssemblyBusinessLogic.Implementations;
internal class PostBusinessLogicContract(IPostStorageContract postStorageContract, ILogger logger) : IPostBusinessLogicContract
internal class PostBusinessLogicContract(IPostStorageContract postStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : IPostBusinessLogicContract
{
IPostStorageContract _postStorageContract = postStorageContract;
private readonly ILogger _logger = logger;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<PostDataModel> GetAllDataOfPost(string postId)
{
@@ -22,15 +25,15 @@ internal class PostBusinessLogicContract(IPostStorageContract postStorageContrac
}
if (!postId.IsGuid())
{
throw new ValidationException("The value in the field postId is not a unique identifier.");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "PostId"));
}
return _postStorageContract.GetPostWithHistory(postId) ?? throw new NullListException();
return _postStorageContract.GetPostWithHistory(postId);
}
public List<PostDataModel> GetAllPosts()
{
_logger.LogInformation("GetAllPosts");
return _postStorageContract.GetList() ?? throw new NullListException();
return _postStorageContract.GetList();
}
public PostDataModel GetPostByData(string data)
@@ -42,16 +45,16 @@ internal class PostBusinessLogicContract(IPostStorageContract postStorageContrac
}
if (data.IsGuid())
{
return _postStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return _postStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data, _localizer); ;
}
return _postStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data);
return _postStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data, _localizer); ;
}
public void InsertPost(PostDataModel postDataModel)
{
logger.LogInformation("New data: {json}", JsonSerializer.Serialize(postDataModel));
ArgumentNullException.ThrowIfNull(postDataModel);
postDataModel.Validate();
postDataModel.Validate(_localizer);
_postStorageContract.AddElement(postDataModel);
}
@@ -59,7 +62,7 @@ internal class PostBusinessLogicContract(IPostStorageContract postStorageContrac
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(postDataModel));
ArgumentNullException.ThrowIfNull(postDataModel);
postDataModel.Validate();
postDataModel.Validate(_localizer);
_postStorageContract.UpdElement(postDataModel);
}
@@ -72,7 +75,7 @@ internal class PostBusinessLogicContract(IPostStorageContract postStorageContrac
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
}
_postStorageContract.DelElement(id);
}
@@ -86,7 +89,7 @@ internal class PostBusinessLogicContract(IPostStorageContract postStorageContrac
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
}
_postStorageContract.ResElement(id);
}

View File

@@ -0,0 +1,128 @@
using FurnitureAssemblyBusinessLogic.OfficePackage;
using FurnitureAssemblyContracts.BusinessLogicsContracts;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Extentions;
using FurnitureAssemblyContracts.Resources;
using FurnitureAssemblyContracts.StoragesContracts;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
namespace FurnitureAssemblyBusinessLogic.Implementations;
internal class ReportContract : IReportContract
{
private readonly IComponentStorageContract _componentStorageContract;
private readonly IManifacturingStorageContract _manifacturingStorageContract;
private readonly ISalaryStorageContract _salaryStorageContract;
private readonly BaseWordBuilder _baseWordBuilder;
private readonly BaseExcelBuilder _baseExcelBuilder;
private readonly BasePdfBuilder _basePdfBuilder;
private readonly ILogger _logger;
private readonly IStringLocalizer<Messages> _localizer;
internal readonly string[] _documentHeader;
internal readonly string[] _tableHeader;
public ReportContract(IComponentStorageContract componentStorageContract, IManifacturingStorageContract manifacturingStorageContract, ISalaryStorageContract salaryStorageContract, BaseWordBuilder baseWordBuilder, BaseExcelBuilder baseExcelBuilder, BasePdfBuilder basePdfBuilder, ILogger logger, IStringLocalizer<Messages> localizer)
{
_componentStorageContract = componentStorageContract;
_manifacturingStorageContract = manifacturingStorageContract;
_salaryStorageContract = salaryStorageContract;
_baseWordBuilder = baseWordBuilder;
_baseExcelBuilder = baseExcelBuilder;
_basePdfBuilder = basePdfBuilder;
_logger = logger;
_localizer = localizer;
_documentHeader = [ _localizer["DocumentDocCaptionName"], _localizer["DocumentDocCaptionPreviousNames"] ];
_tableHeader = [ _localizer["DocumentExcelCaptionDate"], _localizer["DocumentExcelCaptionCount"], _localizer["DocumentExcelCaptionWorker"], _localizer["DocumentExcelCaptionFurniture"] ];
}
public Task<List<ComponentHistoryDataModel>> GetDataComponentsHistoryAsync(CancellationToken ct)
{
_logger.LogInformation("Get data ComponentHistory");
return GetDataByComponentsAsync(ct);
}
public Task<List<ManifacturingFurnitureDataModel>> GetDataManifacturingByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
_logger.LogInformation("Get data SalesByPeriod from {dateStart} to { dateFinish}", dateStart, dateFinish);
return GetDataByManifacturingAsync(dateStart, dateFinish, ct);
}
public async Task<Stream> CreateDocumentComponentsHistoryAsync(CancellationToken ct)
{
_logger.LogInformation("Create report ComponentHistory");
var data = await GetDataByComponentsAsync(ct) ??
throw new InvalidOperationException(_localizer["NotFoundDataMessage"]);
return _baseWordBuilder
.AddHeader(_localizer["DocumentDocHeaderComponents"])
.AddParagraph(string.Format(_localizer["DocumentDocSubHeader"], DateTime.Now))
.AddTable([100, 100], [.. new List<string[]>() { _documentHeader }
.Union([.. data.SelectMany(x => (new List<string[]>() { new string[] { x.CurrentName, "" }})
.Union(x.HistoryNames!.Select(y => new string[] { "", y }))).ToList()]) ])
.Build();
}
private async Task<List<ComponentHistoryDataModel>> GetDataByComponentsAsync(CancellationToken ct)
=> [.. (await _componentStorageContract.GetListAsync(ct)).Select(c =>
new ComponentHistoryDataModel { CurrentName = c.Name, Type = c.Type, HistoryNames = new List<string> { c.PrevName ?? "N/A", c.PrevPrevName ?? "N/A" }.Where(h => h != "N/A").ToList() }).ToList()];
private async Task<List<ManifacturingFurnitureDataModel>> GetDataByManifacturingAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
if (dateStart.IsDateNotOlder(dateFinish))
{
throw new IncorrectDatesException(dateStart, dateFinish, _localizer);
}
return [.. (await _manifacturingStorageContract.GetListAsync(dateStart, dateFinish, ct)).OrderBy(x => x.ProductuionDate)];
}
public async Task<Stream> CreateDocumentSalesByPeriodAsync(
DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
_logger.LogInformation("Create report SalesByPeriod from {dateStart} to {dateFinish}", dateStart, dateFinish);
var data = await GetDataByManifacturingAsync(dateStart, dateFinish, ct) ??
throw new InvalidOperationException(_localizer["NotFoundDataMessage"]);
return _baseExcelBuilder
.AddHeader(_localizer["DocumentExcelHeaderManufacturing"], 0, 5)
.AddParagraph(string.Format(_localizer["DocumentExcelSubHeader"], dateStart.ToLocalTime().ToShortDateString(), dateFinish.ToLocalTime().ToShortDateString()), 2)
.AddTable([10, 10, 10, 10], [.. new List<string[]>() { _tableHeader }
.Union(data.SelectMany(x => new List<string[]>() { new string[] { x.ProductuionDate.ToLocalTime().ToShortDateString(), x.Count.ToString("N2"), x.WorkerFIO,x.FurnitureName }}))
.Union([[ _localizer["DocumentExcelCaptionTotal"], data.Sum(x => x.Count).ToString("N2"), "", "" ]])])
.Build();
}
public Task<List<WorkerSalaryByPeriodDataModel>> GetDataSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
_logger.LogInformation("Get data SalaryByPeriod from {dateStart} to { dateFinish}", dateStart, dateFinish);
return GetDataBySalaryAsync(dateStart, dateFinish, ct);
}
private async Task<List<WorkerSalaryByPeriodDataModel>> GetDataBySalaryAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
if (dateStart.IsDateNotOlder(dateFinish))
{
throw new IncorrectDatesException(dateStart, dateFinish, _localizer);
}
return [.. (await _salaryStorageContract.GetListAsync(dateStart, dateFinish, ct)).GroupBy(x => x.WorkerId)
.Select(x => new WorkerSalaryByPeriodDataModel { WorkerFIO = x.First().WorkerFIO, TotalSalary = x.Sum(y =>y.Salary), FromPeriod = x.Min(y => y.SalaryDate), ToPeriod = x.Max(y =>y.SalaryDate) })
.OrderBy(x => x.WorkerFIO)];
}
public async Task<Stream> CreateDocumentSalaryByPeriodAsync(
DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
_logger.LogInformation("Create report SalaryByPeriod from {dateStart} to {dateFinish}", dateStart, dateFinish);
var data = await GetDataBySalaryAsync(dateStart, dateFinish, ct) ??
throw new InvalidOperationException(_localizer["NotFoundDataMessage"]);
return _basePdfBuilder
.AddHeader(_localizer["DocumentPdfHeader"])
.AddParagraph(string.Format(_localizer["DocumentPdfSubHeader"], dateStart.ToLocalTime().ToShortDateString(), dateFinish.ToLocalTime().ToShortDateString()))
.AddPieChart(_localizer["DocumentPdfDiagramCaption"], [.. data.Select(x => (x.WorkerFIO, x.TotalSalary))])
.Build();
}
}

View File

@@ -1,23 +1,25 @@
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
using FurnitureAssemblyContracts.BusinessLogicsContracts;
using FurnitureAssemblyContracts.BusinessLogicsContracts;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Extentions;
using FurnitureAssemblyContracts.Infrastructure;
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
using FurnitureAssemblyContracts.Resources;
using FurnitureAssemblyContracts.StoragesContracts;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
namespace FurnitureAssemblyBusinessLogic.Implementations;
internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract, IManifacturingStorageContract manifacturingStorageContract, IPostStorageContract
postStorageContract, IWorkerStorageContract workerStorageContract, ILogger logger, IConfigurationSalary сonfiguration) : ISalaryBusinessLogicContract
internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract, IManifacturingStorageContract manifacturingStorageContract,
IWorkerStorageContract workerStorageContract, IStringLocalizer<Messages> localizer, ILogger logger, IConfigurationSalary сonfiguration) : ISalaryBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISalaryStorageContract _salaryStorageContract = salaryStorageContract;
private readonly IManifacturingStorageContract _manifacturingStorageContract = manifacturingStorageContract;
private readonly IPostStorageContract _postStorageContract = postStorageContract;
private readonly IWorkerStorageContract _workerStorageContract = workerStorageContract;
private readonly IConfigurationSalary _salaryConfiguration = сonfiguration;
private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly Lock _lockObject = new();
public List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate)
@@ -25,16 +27,16 @@ internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageC
_logger.LogInformation("GetAllSalaries params: {fromDate}, {toDate}", fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
throw new IncorrectDatesException(fromDate, toDate, _localizer);
}
return _salaryStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
return _salaryStorageContract.GetList(fromDate, toDate);
}
public List<SalaryDataModel> GetAllSalariesByPeriodByWorker(DateTime fromDate, DateTime toDate, string workerId)
{
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
throw new IncorrectDatesException(fromDate, toDate, _localizer);
}
if (workerId.IsEmpty())
{
@@ -42,31 +44,31 @@ internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageC
}
if (!workerId.IsGuid())
{
throw new ValidationException("The value in the field workerId is not a unique identifier.");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "WorkerId"));
}
_logger.LogInformation("GetAllSalaries params: {fromDate}, {toDate}, { workerId}", fromDate, toDate, workerId);
return _salaryStorageContract.GetList(fromDate, toDate, workerId) ?? throw new NullListException();
return _salaryStorageContract.GetList(fromDate, toDate, workerId);
}
public void CalculateSalaryByMounth(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();
var startDate = new DateTime(date.Year, date.Month, 1).ToUniversalTime();
var finishDate = new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month)).ToUniversalTime();
var workers = _workerStorageContract.GetList();
foreach (var worker in workers)
{
var sales = _manifacturingStorageContract.GetList(startDate, finishDate, workerId: worker.Id) ?? throw new NullListException();
var post = _postStorageContract.GetElementById(worker.PostId) ?? throw new NullListException();
var salary = post.ConfigurationModel switch
{
var sales = _manifacturingStorageContract.GetList(startDate, finishDate, workerId: worker.Id);
var salary = worker.ConfigurationModel switch
{
null => 0,
BuilderPostConfiguration cpc => CalculateSalaryForBuilder(sales, startDate, finishDate, cpc),
ChiefPostConfiguration spc => CalculateSalaryForChief(startDate, finishDate, spc),
PostConfiguration pc => pc.Rate,
};
_logger.LogDebug("The employee {workerId} was paid a salary of {salary}", worker.Id, salary);
_salaryStorageContract.AddElement(new SalaryDataModel(worker.Id, finishDate, salary));
_logger.LogDebug("The employee {workerId} was paid a salary of {salary}", worker.Id, salary);
_logger.LogDebug("The employee {workerId} was paid a salary of { salary}", worker.Id, salary);
_salaryStorageContract.AddElement(new SalaryDataModel(worker.Id, finishDate, salary));
}
}
@@ -81,7 +83,7 @@ internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageC
var parallelOptions = new ParallelOptions
{
MaxDegreeOfParallelism = _salaryConfiguration.MaxConcurrentThreads
MaxDegreeOfParallelism = _salaryConfiguration.MaxConcurrentThreads
};
Parallel.ForEach(dates, parallelOptions, date =>
@@ -100,7 +102,7 @@ internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageC
try
{
calcBonusTask = sales.Where(x => x.Count > _salaryConfiguration.ExtraMadeSum).Sum(x => x.Count) * config.PersonalCount;
}
catch (Exception ex)
{

View File

@@ -2,22 +2,25 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Extentions;
using FurnitureAssemblyContracts.Resources;
using FurnitureAssemblyContracts.StoragesContracts;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace FurnitureAssemblyBusinessLogic.Implementations;
internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageContract, ILogger logger) : IWorkerBusinessLogicContract
internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : IWorkerBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IWorkerStorageContract _workerStorageContract = workerStorageContract;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<WorkerDataModel> GetAllWorkers(bool onlyActive = true)
{
_logger.LogInformation("GetAllWorkers params: {onlyActive}", onlyActive);
return _workerStorageContract.GetList(onlyActive) ?? throw new NullListException();
return _workerStorageContract.GetList(onlyActive);
}
public List<WorkerDataModel> GetAllWorkersByPost(string postId, bool onlyActive = true)
@@ -29,9 +32,9 @@ internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageC
}
if (!postId.IsGuid())
{
throw new ValidationException("The value in the field postId is not a unique identifier.");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "PostId"));
}
return _workerStorageContract.GetList(onlyActive, postId) ?? throw new NullListException();
return _workerStorageContract.GetList(onlyActive, postId) ;
}
public List<WorkerDataModel> GetAllWorkersByBirthDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
@@ -39,9 +42,9 @@ internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageC
_logger.LogInformation("GetAllWorkers params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
throw new IncorrectDatesException(fromDate, toDate, _localizer);
}
return _workerStorageContract.GetList(onlyActive, fromBirthDate: fromDate, toBirthDate: toDate) ?? throw new NullListException();
return _workerStorageContract.GetList(onlyActive, fromBirthDate: fromDate, toBirthDate: toDate);
}
public List<WorkerDataModel> GetAllWorkersByEmploymentDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
@@ -49,9 +52,9 @@ internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageC
_logger.LogInformation("GetAllWorkers params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
throw new IncorrectDatesException(fromDate, toDate, _localizer);
}
return _workerStorageContract.GetList(onlyActive, fromEmploymentDate: fromDate, toEmploymentDate: toDate) ?? throw new NullListException();
return _workerStorageContract.GetList(onlyActive, fromEmploymentDate: fromDate, toEmploymentDate: toDate);
}
public WorkerDataModel GetWorkerByData(string data)
@@ -63,16 +66,16 @@ internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageC
}
if (data.IsGuid())
{
return _workerStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return _workerStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data, _localizer);
}
return _workerStorageContract.GetElementByFIO(data) ?? throw new ElementNotFoundException(data);
return _workerStorageContract.GetElementByFIO(data) ?? throw new ElementNotFoundException(data, _localizer);
}
public void InsertWorker(WorkerDataModel workerDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(workerDataModel));
ArgumentNullException.ThrowIfNull(workerDataModel);
workerDataModel.Validate();
workerDataModel.Validate(_localizer);
_workerStorageContract.AddElement(workerDataModel);
}
@@ -81,7 +84,7 @@ internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageC
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(workerDataModel));
ArgumentNullException.ThrowIfNull(workerDataModel);
workerDataModel.Validate();
workerDataModel.Validate(_localizer);
_workerStorageContract.UpdElement(workerDataModel);
}
@@ -94,7 +97,7 @@ internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageC
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
}
_workerStorageContract.DelElement(id);
}

View File

@@ -0,0 +1,9 @@
namespace FurnitureAssemblyBusinessLogic.OfficePackage;
public abstract class BaseExcelBuilder
{
public abstract BaseExcelBuilder AddHeader(string header, int startIndex, int count);
public abstract BaseExcelBuilder AddParagraph(string text, int columnIndex);
public abstract BaseExcelBuilder AddTable(int[] columnsWidths, List<string[]> data);
public abstract Stream Build();
}

View File

@@ -0,0 +1,9 @@
namespace FurnitureAssemblyBusinessLogic.OfficePackage;
public abstract class BasePdfBuilder
{
public abstract BasePdfBuilder AddHeader(string header);
public abstract BasePdfBuilder AddParagraph(string text);
public abstract BasePdfBuilder AddPieChart(string title, List<(string Caption, double Value)> data);
public abstract Stream Build();
}

View File

@@ -0,0 +1,9 @@
namespace FurnitureAssemblyBusinessLogic.OfficePackage;
public abstract class BaseWordBuilder
{
public abstract BaseWordBuilder AddHeader(string header);
public abstract BaseWordBuilder AddParagraph(string text);
public abstract BaseWordBuilder AddTable(int[] widths, List<string[]> data);
public abstract Stream Build();
}

View File

@@ -0,0 +1,85 @@
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Shapes.Charts;
using MigraDoc.Rendering;
using System.Text;
namespace FurnitureAssemblyBusinessLogic.OfficePackage;
public class MigraDocPdfBuilder : BasePdfBuilder
{
private readonly Document _document;
public MigraDocPdfBuilder()
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
_document = new Document();
DefineStyles();
}
public override BasePdfBuilder AddHeader(string header)
{
_document.AddSection().AddParagraph(header, "NormalBold");
return this;
}
public override BasePdfBuilder AddParagraph(string text)
{
_document.LastSection.AddParagraph(text, "Normal");
return this;
}
public override BasePdfBuilder AddPieChart(string title, List<(string Caption, double Value)> data)
{
if (data == null || data.Count == 0)
{
return this;
}
var chart = new Chart(ChartType.Pie2D);
var series = chart.SeriesCollection.AddSeries();
series.Add(data.Select(x => x.Value).ToArray());
var xseries = chart.XValues.AddXSeries();
xseries.Add(data.Select(x => x.Caption).ToArray());
chart.DataLabel.Type = DataLabelType.Percent;
chart.DataLabel.Position = DataLabelPosition.OutsideEnd;
chart.Width = Unit.FromCentimeter(16);
chart.Height = Unit.FromCentimeter(12);
chart.TopArea.AddParagraph(title);
chart.XAxis.MajorTickMark = TickMarkType.Outside;
chart.YAxis.MajorTickMark = TickMarkType.Outside;
chart.YAxis.HasMajorGridlines = true;
chart.PlotArea.LineFormat.Width = 1;
chart.PlotArea.LineFormat.Visible = true;
chart.TopArea.AddLegend();
_document.LastSection.Add(chart);
return this;
}
public override Stream Build()
{
var stream = new MemoryStream();
var renderer = new PdfDocumentRenderer(true)
{
Document = _document
};
renderer.RenderDocument();
renderer.PdfDocument.Save(stream);
return stream;
}
private void DefineStyles()
{
var style = _document.Styles.AddStyle("NormalBold", "Normal");
style.Font.Bold = true;
}
}

View File

@@ -0,0 +1,303 @@
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
namespace FurnitureAssemblyBusinessLogic.OfficePackage;
public class OpenXmlExcelBuilder : BaseExcelBuilder
{
private readonly SheetData _sheetData;
private readonly MergeCells _mergeCells;
private readonly Columns _columns;
private uint _rowIndex = 0;
public OpenXmlExcelBuilder()
{
_sheetData = new SheetData();
_mergeCells = new MergeCells();
_columns = new Columns();
_rowIndex = 1;
}
public override BaseExcelBuilder AddHeader(string header, int startIndex, int count)
{
CreateCell(startIndex, _rowIndex, header, StyleIndex.BoldTextWithoutBorder);
for (int i = startIndex + 1; i < startIndex + count; ++i)
{
CreateCell(i, _rowIndex, "", StyleIndex.SimpleTextWithoutBorder);
}
_mergeCells.Append(new MergeCell()
{
Reference =
new StringValue($"{GetExcelColumnName(startIndex)}{_rowIndex}:{GetExcelColumnName(startIndex + count - 1)}{_rowIndex}")
});
_rowIndex++;
return this;
}
public override BaseExcelBuilder AddParagraph(string text, int columnIndex)
{
CreateCell(columnIndex, _rowIndex++, text, StyleIndex.SimpleTextWithoutBorder);
return this;
}
public override BaseExcelBuilder AddTable(int[] columnsWidths, List<string[]> data)
{
if (columnsWidths == null || columnsWidths.Length == 0)
{
throw new ArgumentNullException(nameof(columnsWidths));
}
if (data == null || data.Count == 0)
{
throw new ArgumentNullException(nameof(data));
}
if (data.Any(x => x.Length != columnsWidths.Length))
{
throw new InvalidOperationException("widths.Length != data.Length");
}
uint counter = 1;
int coef = 2;
_columns.Append(columnsWidths.Select(x => new Column
{
Min = counter,
Max = counter++,
Width = x * coef,
CustomWidth = true
}));
for (var j = 0; j < data.First().Length; ++j)
{
CreateCell(j, _rowIndex, data.First()[j], StyleIndex.BoldTextWithBorder);
}
_rowIndex++;
for (var i = 1; i < data.Count - 1; ++i)
{
for (var j = 0; j < data[i].Length; ++j)
{
CreateCell(j, _rowIndex, data[i][j], StyleIndex.SimpleTextWithBorder);
}
_rowIndex++;
}
for (var j = 0; j < data.Last().Length; ++j)
{
CreateCell(j, _rowIndex, data.Last()[j], StyleIndex.BoldTextWithBorder);
}
_rowIndex++;
return this;
}
public override Stream Build()
{
var stream = new MemoryStream();
using var spreadsheetDocument = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook);
var workbookpart = spreadsheetDocument.AddWorkbookPart();
GenerateStyle(workbookpart);
workbookpart.Workbook = new Workbook();
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
if (_columns.HasChildren)
{
worksheetPart.Worksheet.Append(_columns);
}
worksheetPart.Worksheet.Append(_sheetData);
var sheets = spreadsheetDocument.WorkbookPart!.Workbook.AppendChild(new Sheets());
var sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Лист 1"
};
sheets.Append(sheet);
if (_mergeCells.HasChildren)
{
worksheetPart.Worksheet.InsertAfter(_mergeCells, worksheetPart.Worksheet.Elements<SheetData>().First());
}
return stream;
}
private static void GenerateStyle(WorkbookPart workbookPart)
{
var workbookStylesPart = workbookPart.AddNewPart<WorkbookStylesPart>();
workbookStylesPart.Stylesheet = new Stylesheet();
var fonts = new Fonts() { Count = 2, KnownFonts = BooleanValue.FromBoolean(true) };
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
{
FontSize = new FontSize() { Val = 11 },
FontName = new FontName() { Val = "Calibri" },
FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 },
FontScheme = new FontScheme() { Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor) }
});
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
{
FontSize = new FontSize() { Val = 11 },
FontName = new FontName() { Val = "Calibri" },
FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 },
FontScheme = new FontScheme() { Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor) },
Bold = new Bold()
});
workbookStylesPart.Stylesheet.Append(fonts);
// Default Fill
var fills = new Fills() { Count = 1 };
fills.Append(new Fill
{
PatternFill = new PatternFill() { PatternType = new EnumValue<PatternValues>(PatternValues.None) }
});
workbookStylesPart.Stylesheet.Append(fills);
// Default Border
var borders = new Borders() { Count = 2 };
borders.Append(new Border
{
LeftBorder = new LeftBorder(),
RightBorder = new RightBorder(),
TopBorder = new TopBorder(),
BottomBorder = new BottomBorder(),
DiagonalBorder = new DiagonalBorder()
});
borders.Append(new Border
{
LeftBorder = new LeftBorder() { Style = BorderStyleValues.Thin },
RightBorder = new RightBorder() { Style = BorderStyleValues.Thin },
TopBorder = new TopBorder() { Style = BorderStyleValues.Thin },
BottomBorder = new BottomBorder() { Style = BorderStyleValues.Thin }
});
workbookStylesPart.Stylesheet.Append(borders);
// Default cell format and a date cell format
var cellFormats = new CellFormats() { Count = 4 };
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 0,
BorderId = 0,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 0,
BorderId = 1,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 1,
BorderId = 0,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Center,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 1,
BorderId = 1,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Center,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
workbookStylesPart.Stylesheet.Append(cellFormats);
}
private enum StyleIndex
{
SimpleTextWithoutBorder = 0,
SimpleTextWithBorder = 1,
BoldTextWithoutBorder = 2,
BoldTextWithBorder = 3
}
private void CreateCell(int columnIndex, uint rowIndex, string text, StyleIndex styleIndex)
{
var columnName = GetExcelColumnName(columnIndex);
var cellReference = columnName + rowIndex;
var row = _sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex! == rowIndex);
if (row == null)
{
row = new Row() { RowIndex = rowIndex };
_sheetData.Append(row);
}
var newCell = row.Elements<Cell>()
.FirstOrDefault(c => c.CellReference != null && c.CellReference.Value == columnName + rowIndex);
if (newCell == null)
{
Cell? refCell = null;
foreach (Cell cell in row.Elements<Cell>())
{
if (cell.CellReference?.Value != null && cell.CellReference.Value.Length == cellReference.Length)
{
if (string.Compare(cell.CellReference.Value, cellReference, true) > 0)
{
refCell = cell;
break;
}
}
}
newCell = new Cell() { CellReference = cellReference };
row.InsertBefore(newCell, refCell);
}
newCell.CellValue = new CellValue(text);
newCell.DataType = CellValues.String;
newCell.StyleIndex = (uint)styleIndex;
}
private static string GetExcelColumnName(int columnNumber)
{
columnNumber += 1;
int dividend = columnNumber;
string columnName = string.Empty;
int modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
dividend = (dividend - modulo) / 26;
}
return columnName;
}
}

View File

@@ -0,0 +1,94 @@
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace FurnitureAssemblyBusinessLogic.OfficePackage;
public class OpenXmlWordBuilder : BaseWordBuilder
{
private readonly Document _document;
private readonly Body _body;
public OpenXmlWordBuilder()
{
_document = new Document();
_body = _document.AppendChild(new Body());
}
public override BaseWordBuilder AddHeader(string header)
{
var paragraph = _body.AppendChild(new Paragraph());
var run = paragraph.AppendChild(new Run());
run.AppendChild(new RunProperties(new Bold()));
run.AppendChild(new Text(header));
return this;
}
public override BaseWordBuilder AddParagraph(string text)
{
var paragraph = _body.AppendChild(new Paragraph());
var run = paragraph.AppendChild(new Run());
run.AppendChild(new Text(text));
return this;
}
public override BaseWordBuilder AddTable(int[] widths, List<string[]> data)
{
if (widths == null || widths.Length == 0)
{
throw new ArgumentNullException(nameof(widths));
}
if (data == null || data.Count == 0)
{
throw new ArgumentNullException(nameof(data));
}
if (data.Any(x => x.Length != widths.Length))
{
throw new InvalidOperationException("widths.Length != data.Length");
}
var table = new Table();
table.AppendChild(new TableProperties(
new TableBorders(
new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 }
)
));
// Заголовок
var tr = new TableRow();
for (var j = 0; j < widths.Length; ++j)
{
tr.Append(new TableCell(
new TableCellProperties(new TableCellWidth() { Width = widths[j].ToString() }),
new Paragraph(new Run(new RunProperties(new Bold()), new Text(data.First()[j])))));
}
table.Append(tr);
// Данные
table.Append(data.Skip(1).Select(x =>
new TableRow(x.Select(y => new TableCell(new Paragraph(new Run(new Text(y))))))));
_body.Append(table);
return this;
}
public override Stream Build()
{
var stream = new MemoryStream();
using var wordDocument = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document);
var mainPart = wordDocument.AddMainDocumentPart();
mainPart.Document = _document;
return stream;
}
}

View File

@@ -0,0 +1,13 @@
using FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
namespace FurnitureAssemblyContracts.AdapterContracts;
public interface IReportAdapter
{
Task<ReportOperationResponse> GetDataComponentsHistoryAsync(CancellationToken ct);
Task<ReportOperationResponse> GetDataManifacturingByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<ReportOperationResponse> GetDataSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<ReportOperationResponse> CreateDocumentComponentHistoryAsync(CancellationToken ct);
Task<ReportOperationResponse> CreateDocumentSalesByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<ReportOperationResponse> CreateDocumentSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
}

View File

@@ -0,0 +1,15 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Infrastructure;
using FurnitureAssemblyContracts.ViewModels;
namespace FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
public class ReportOperationResponse : OperationResponse
{
public static ReportOperationResponse OK(List<ComponentHistoryViewModel> data) => OK<ReportOperationResponse, List<ComponentHistoryViewModel>>(data);
public static ReportOperationResponse OK(List<ManifacturingFurnitureViewModel> data) => OK<ReportOperationResponse, List<ManifacturingFurnitureViewModel>>(data);
public static ReportOperationResponse OK(List<WorkerSalaryByPeriodViewModel> data) => OK<ReportOperationResponse, List<WorkerSalaryByPeriodViewModel>>(data);
public static ReportOperationResponse OK(Stream data, string fileName) => OK<ReportOperationResponse, Stream>(data, fileName);
public static ReportOperationResponse BadRequest(string message) => BadRequest<ReportOperationResponse>(message);
public static ReportOperationResponse InternalServerError(string message) => InternalServerError<ReportOperationResponse>(message);
}

View File

@@ -6,5 +6,5 @@ public class PostBindingModel
public string? PostId => Id;
public string? PostName { get; set; }
public string? PostType { get; set; }
public string? ConfigurationJson { get; set; }
public double Salary { get; set; }
}

View File

@@ -7,4 +7,5 @@ public class WorkerBindingModel
public string? PostId { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
public string? ConfigurationJson { get; set; }
}

View File

@@ -2,7 +2,7 @@
namespace FurnitureAssemblyContracts.BusinessLogicsContracts;
public interface IComponentBusinessLogicContract
internal interface IComponentBusinessLogicContract
{
List<ComponentDataModel> GetAllComponents();
ComponentDataModel GetComponentByData(string data);

View File

@@ -2,7 +2,7 @@
namespace FurnitureAssemblyContracts.BusinessLogicsContracts;
public interface IFurnitureBusinessLogicContract
internal interface IFurnitureBusinessLogicContract
{
List<FurnitureDataModel> GetAllFurnitures();
FurnitureDataModel GetFurnitureByData(string data);

View File

@@ -2,7 +2,7 @@
namespace FurnitureAssemblyContracts.BusinessLogicsContracts;
public interface IManifacturingBusinessLogicContract
internal interface IManifacturingBusinessLogicContract
{
List<ManifacturingFurnitureDataModel> GetManifacturingByPeriod(DateTime fromDate, DateTime toDate);
List<ManifacturingFurnitureDataModel> GetAllManifacturingByWorkerByPeriod(string workerId, DateTime fromDate, DateTime toDate);

View File

@@ -2,7 +2,7 @@
namespace FurnitureAssemblyContracts.BusinessLogicsContracts;
public interface IPostBusinessLogicContract
internal interface IPostBusinessLogicContract
{
List<PostDataModel> GetAllPosts();
List<PostDataModel> GetAllDataOfPost(string postId);

View File

@@ -0,0 +1,13 @@
using FurnitureAssemblyContracts.DataModels;
namespace FurnitureAssemblyContracts.BusinessLogicsContracts;
internal interface IReportContract
{
Task<List<ComponentHistoryDataModel>> GetDataComponentsHistoryAsync(CancellationToken ct);
Task<List<ManifacturingFurnitureDataModel>> GetDataManifacturingByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<List<WorkerSalaryByPeriodDataModel>> GetDataSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<Stream> CreateDocumentComponentsHistoryAsync(CancellationToken ct);
Task<Stream> CreateDocumentSalesByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<Stream> CreateDocumentSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
}

View File

@@ -2,7 +2,7 @@
namespace FurnitureAssemblyContracts.BusinessLogicsContracts;
public interface ISalaryBusinessLogicContract
internal interface ISalaryBusinessLogicContract
{
List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate);
List<SalaryDataModel> GetAllSalariesByPeriodByWorker(DateTime fromDate, DateTime toDate, string workerId);

View File

@@ -2,7 +2,7 @@
namespace FurnitureAssemblyContracts.BusinessLogicsContracts;
public interface IWorkerBusinessLogicContract
internal interface IWorkerBusinessLogicContract
{
List<WorkerDataModel> GetAllWorkers(bool onlyActive = true);
List<WorkerDataModel> GetAllWorkersByPost(string postId, bool onlyActive = true);

View File

@@ -2,10 +2,12 @@
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Extentions;
using FurnitureAssemblyContracts.Infrastructure;
using FurnitureAssemblyContracts.Resources;
using Microsoft.Extensions.Localization;
namespace FurnitureAssemblyContracts.DataModels;
public class ComponentDataModel(string id, string name, ComponentType type, string? prevName = null, string? prevPrevName = null) : IValidation
internal class ComponentDataModel(string id, string name, ComponentType type, string? prevName = null, string? prevPrevName = null) : IValidation
{
public string Id { get; private set; } = id;
public string Name { get; private set; } = name;
@@ -13,15 +15,15 @@ public class ComponentDataModel(string id, string name, ComponentType type, stri
public string? PrevPrevName { get; private set; } = prevPrevName;
public ComponentType Type { get; private set; } = type;
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
if (Name.IsEmpty())
throw new ValidationException("Field Name is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Name"));
if (Type == ComponentType.None)
throw new ValidationException("Field Type is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Type"));
}
}

View File

@@ -0,0 +1,9 @@
using FurnitureAssemblyContracts.Enums;
namespace FurnitureAssemblyContracts.DataModels;
public class ComponentHistoryDataModel
{
public required string CurrentName { get; set; }
public required ComponentType Type { get; set; }
public List<string>? HistoryNames { get; set; }
}

View File

@@ -1,26 +1,28 @@
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Extentions;
using FurnitureAssemblyContracts.Infrastructure;
using FurnitureAssemblyContracts.Resources;
using Microsoft.Extensions.Localization;
namespace FurnitureAssemblyContracts.DataModels;
public class FurnitureComponentDataModel(string furnitureId, string componentId, int count) : IValidation
internal class FurnitureComponentDataModel(string furnitureId, string componentId, int count) : IValidation
{
public string FurnitureId { get; private set; } = furnitureId;
public string ComponentId { get; private set; } = componentId;
public int Count { get; private set; } = count;
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (FurnitureId.IsEmpty())
throw new ValidationException("Field FurnitureId is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "FurnitureId"));
if (!FurnitureId.IsGuid())
throw new ValidationException("The value in the field FurnitureId is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "FurnitureId"));
if (ComponentId.IsEmpty())
throw new ValidationException("Field ComponentId is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "ComponentId"));
if (!ComponentId.IsGuid())
throw new ValidationException("The value in the field ComponentId is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "ComponentId"));
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Count"));
}
}

View File

@@ -1,27 +1,29 @@
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Extentions;
using FurnitureAssemblyContracts.Infrastructure;
using FurnitureAssemblyContracts.Resources;
using Microsoft.Extensions.Localization;
namespace FurnitureAssemblyContracts.DataModels;
public class FurnitureDataModel(string id, string name, int weight, List<FurnitureComponentDataModel> components) : IValidation
internal class FurnitureDataModel(string id, string name, int weight, List<FurnitureComponentDataModel> components) : IValidation
{
public string Id { get; private set; } = id;
public string Name { get; private set; } = name;
public int Weight { get; private set; } = weight;
public List<FurnitureComponentDataModel> Components { get; private set; } = components;
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
if (Name.IsEmpty())
throw new ValidationException("Field Name is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Name"));
if (Weight <= 0)
throw new ValidationException("Field Weight is less than or equal to 0");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Weight"));
if ((Components?.Count ?? 0) == 0)
throw new ValidationException("The furniture must include Components");
throw new ValidationException(localizer["ValidationExceptionMessageNoComponents"]);
}
}

View File

@@ -1,10 +1,12 @@
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Extentions;
using FurnitureAssemblyContracts.Infrastructure;
using FurnitureAssemblyContracts.Resources;
using Microsoft.Extensions.Localization;
namespace FurnitureAssemblyContracts.DataModels;
public class ManifacturingFurnitureDataModel : IValidation
internal class ManifacturingFurnitureDataModel : IValidation
{
private readonly WorkerDataModel? _worker;
private readonly FurnitureDataModel? _furniture;
@@ -31,21 +33,21 @@ public class ManifacturingFurnitureDataModel : IValidation
_furniture = furniture;
}
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
if (FurnitureId.IsEmpty())
throw new ValidationException("Field FurnitureId is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "FurnitureId"));
if (!FurnitureId.IsGuid())
throw new ValidationException("The value in the field FurnitureId is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "FurnitureId"));
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Count"));
if (WorkerId.IsEmpty())
throw new ValidationException("Field WorkerId is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "WorkerId"));
if (!WorkerId.IsGuid())
throw new ValidationException("The value in the field WorkerId is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "WorkerId"));
}
}

View File

@@ -1,48 +1,30 @@
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Extentions;
using FurnitureAssemblyContracts.Infrastructure;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using FurnitureAssemblyContracts.Resources;
using Microsoft.Extensions.Localization;
namespace FurnitureAssemblyContracts.DataModels;
public class PostDataModel(string postid, string postName, PostType postType, PostConfiguration configuration) : IValidation
internal 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 PostConfiguration ConfigurationModel { get; private set; } = configuration;
public double Salary { get; private set; } = salary;
public PostDataModel(string postId, string postName, PostType postType, string configurationJson) : this(postId, postName, postType, (PostConfiguration)null)
{
var obj = JToken.Parse(configurationJson);
if (obj is not null)
{
ConfigurationModel = obj.Value<string>("Type") switch
{
nameof(BuilderPostConfiguration) => JsonConvert.DeserializeObject<BuilderPostConfiguration>(configurationJson)!,
nameof(ChiefPostConfiguration) => JsonConvert.DeserializeObject<ChiefPostConfiguration>(configurationJson)!,
_ => JsonConvert.DeserializeObject<PostConfiguration>(configurationJson)!,
};
}
}
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
if (PostName.IsEmpty())
throw new ValidationException("Field PostName is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "PostName"));
if (PostType == PostType.None)
throw new ValidationException("Field PostType is empty");
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");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "PostType"));
if (Salary <= 0)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Salary"));
}
}

View File

@@ -1,14 +1,16 @@
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Extentions;
using FurnitureAssemblyContracts.Infrastructure;
using FurnitureAssemblyContracts.Resources;
using Microsoft.Extensions.Localization;
namespace FurnitureAssemblyContracts.DataModels;
public class SalaryDataModel(string workerId, DateTime salaryDate, double workerSalary) : IValidation
internal 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 DateTime SalaryDate { get; private set; } = salaryDate.ToUniversalTime();
public double Salary { get; private set; } = workerSalary;
public string WorkerFIO => _worker?.FIO ?? string.Empty;
@@ -17,13 +19,13 @@ public class SalaryDataModel(string workerId, DateTime salaryDate, double worker
_worker = worker;
}
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (WorkerId.IsEmpty())
throw new ValidationException("Field WorkerId is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "WorkerId"));
if (!WorkerId.IsGuid())
throw new ValidationException("The value in the field WorkerId is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "WorkerId"));
if (Salary <= 0)
throw new ValidationException("Field Salary is less than or equal to 0");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Salary"));
}
}

View File

@@ -2,10 +2,15 @@
using FurnitureAssemblyContracts.Infrastructure;
using FurnitureAssemblyContracts.Exceptions;
using System.Text.RegularExpressions;
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using FurnitureAssemblyContracts.Resources;
using Microsoft.Extensions.Localization;
namespace FurnitureAssemblyContracts.DataModels;
public class WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted) : IValidation
internal class WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted, PostConfiguration configuration) : IValidation
{
private readonly PostDataModel? _post;
@@ -15,48 +20,60 @@ public class WorkerDataModel(string id, string fio, string postId, DateTime birt
public string PostId { get; private set; } = postId;
public DateTime BirthDate { get; private set; } = birthDate;
public DateTime BirthDate { get; private set; } = birthDate.ToUniversalTime();
public DateTime EmploymentDate { get; private set; } = employmentDate;
public DateTime EmploymentDate { get; private set; } = employmentDate.ToUniversalTime();
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)
public WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted, PostConfiguration configuration, PostDataModel post) : this(id, fio, postId, birthDate, employmentDate, isDeleted, configuration)
{
_post = post;
}
public WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate) : this(id, fio, postId, birthDate, employmentDate, false) { }
public WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate, string configurationJson) : this(id, fio, postId, birthDate, employmentDate, false, (PostConfiguration)null)
{
var obj = JToken.Parse(configurationJson);
if (obj is not null)
{
ConfigurationModel = obj.Value<string>("Type") switch
{
nameof(BuilderPostConfiguration) => JsonConvert.DeserializeObject<BuilderPostConfiguration>(configurationJson)!,
nameof(ChiefPostConfiguration) => JsonConvert.DeserializeObject<ChiefPostConfiguration>(configurationJson)!,
_ => JsonConvert.DeserializeObject<PostConfiguration>(configurationJson)!,
};
}
}
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
if (FIO.IsEmpty())
throw new ValidationException("Field FIO is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "FIO"));
if (!Regex.IsMatch(FIO, @"^([А-ЯЁ][а-яё]*(-[А-ЯЁ][а-яё]*)?)\s([А-ЯЁ]\.?\s?([А-ЯЁ]\.?\s?)?)?$"))
throw new ValidationException("Field FIO is not a fio");
throw new ValidationException(localizer["ValidationExceptionMessageIncorrectFIO"]);
if (PostId.IsEmpty())
throw new ValidationException("Field PostId is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "PostId"));
if (!PostId.IsGuid())
throw new ValidationException("The value in the field PostId is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "PostId"));
if (BirthDate.Date > DateTime.Now.AddYears(-14).Date)
throw new ValidationException($"Minors cannot be hired (BirthDate = {BirthDate.ToShortDateString()})");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageMinorsBirthDate"], BirthDate.ToShortDateString()));
if (EmploymentDate.Date < BirthDate.Date)
throw new ValidationException("The date of employment cannot be less than the date of birth");
if ((EmploymentDate - BirthDate).TotalDays / 365 < 14) // EmploymentDate.Year - BirthDate.Year
throw new ValidationException($"Minors cannot be hired (EmploymentDate - {EmploymentDate.ToShortDateString()}, BirthDate - {BirthDate.ToShortDateString()})");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmploymentDateAndBirthDate"],
EmploymentDate.ToShortDateString(), BirthDate.ToShortDateString()));
if ((EmploymentDate - BirthDate).TotalDays / 365 < 14)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageMinorsEmploymentDate"],
EmploymentDate.ToShortDateString(), BirthDate.ToShortDateString()));
if (ConfigurationModel is null)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotInitialized"], "ConfigurationModel"));
if (ConfigurationModel!.Rate <= 0)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Rate"));
}
}

View File

@@ -0,0 +1,9 @@
namespace FurnitureAssemblyContracts.DataModels;
public class WorkerSalaryByPeriodDataModel
{
public required string WorkerFIO { get; set; }
public double TotalSalary { get; set; }
public DateTime FromPeriod { get; set; }
public DateTime ToPeriod { get; set; }
}

View File

@@ -5,5 +5,5 @@ public enum PostType
None = 0,
ComponentMaker = 1,
Builder = 2,
Chief = 3,
Chief = 3
}

View File

@@ -1,6 +1,7 @@
namespace FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Resources;
using Microsoft.Extensions.Localization;
public class ElementDeletedException : Exception
{
public ElementDeletedException(string id) : base($"Cannot modify a deleted item(id: { id})") { }
}
namespace FurnitureAssemblyContracts.Exceptions;
internal class ElementDeletedException(string id, IStringLocalizer<Messages> localizer) : Exception(string.Format(localizer["ElementDeletedExceptionMessage"], id))
{ }

View File

@@ -1,12 +1,12 @@
namespace FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Resources;
using Microsoft.Extensions.Localization;
public class ElementExistsException : Exception
namespace FurnitureAssemblyContracts.Exceptions;
internal class ElementExistsException(string paramName, string paramValue, IStringLocalizer<Messages> localizer) :
Exception(string.Format(localizer["ElementExistsExceptionMessage"], paramValue, paramName))
{
public string ParamName { get; private set; }
public string ParamValue { get; private set; }
public ElementExistsException(string paramName, string paramValue) : base($"There is already an element with value {paramValue} of parameter { paramName}")
{
ParamName = paramName;
ParamValue = paramValue;
}
public string ParamName { get; private set; } = paramName;
public string ParamValue { get; private set; } = paramValue;
}

View File

@@ -1,10 +1,10 @@
namespace FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Resources;
using Microsoft.Extensions.Localization;
public class ElementNotFoundException : Exception
namespace FurnitureAssemblyContracts.Exceptions;
internal class ElementNotFoundException(string value, IStringLocalizer<Messages> localizer) :
Exception(string.Format(localizer["ElementNotFoundExceptionMessage"], value))
{
public string Value { get; private set; }
public ElementNotFoundException(string value) : base($"Element not found at value = { value }")
{
Value = value;
}
public string Value { get; private set; } = value;
}

View File

@@ -1,6 +1,8 @@
namespace FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Resources;
using Microsoft.Extensions.Localization;
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}") { }
}
namespace FurnitureAssemblyContracts.Exceptions;
internal class IncorrectDatesException(DateTime start, DateTime end, IStringLocalizer<Messages> localizer) :
Exception(string.Format(localizer["IncorrectDatesExceptionMessage"], start.ToShortDateString(), end.ToShortDateString()))
{ }

View File

@@ -1,6 +0,0 @@
namespace FurnitureAssemblyContracts.Exceptions;
public class NullListException : Exception
{
public NullListException() : base("The returned list is null") { }
}

View File

@@ -1,6 +1,8 @@
namespace FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Resources;
using Microsoft.Extensions.Localization;
namespace FurnitureAssemblyContracts.Exceptions;
internal class StorageException(Exception ex, IStringLocalizer<Messages> localizer) : Exception(string.Format(localizer["StorageExceptionMessage"], ex.Message), ex)
{ }
public class StorageException : Exception
{
public StorageException(Exception ex) : base($"Error while working in storage: { ex.Message}", ex) { }
}

View File

@@ -10,6 +10,30 @@
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.3.0" />
<PackageReference Include="Microsoft.Extensions.Localization.Abstractions" Version="9.0.4" />
</ItemGroup>
<ItemGroup>
<Compile Update="Resources\Messages.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Messages.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Resources\Messages.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Messages.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="FurnitureAssemblyBusinessLogic" />
<InternalsVisibleTo Include="FurnitureAssemblyDatebase" />
<InternalsVisibleTo Include="FurnitureAssemblyWebApi" />
<InternalsVisibleTo Include="FurnitureAssemblyTests" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
</Project>

View File

@@ -1,5 +1,6 @@
namespace FurnitureAssemblyContracts.Infrastructure;
public interface IConfigurationSalary
{
double ExtraMadeSum { get; }

View File

@@ -1,6 +1,9 @@
namespace FurnitureAssemblyContracts.Infrastructure;
using FurnitureAssemblyContracts.Resources;
using Microsoft.Extensions.Localization;
public interface IValidation
namespace FurnitureAssemblyContracts.Infrastructure;
internal interface IValidation
{
void Validate();
void Validate(IStringLocalizer<Messages> localizer);
}

View File

@@ -10,6 +10,8 @@ public class OperationResponse
protected object? Result { get; set; }
protected string? FileName { get; set; }
public IActionResult GetResponse(HttpRequest request, HttpResponse response)
{
ArgumentNullException.ThrowIfNull(request);
@@ -19,12 +21,22 @@ public class OperationResponse
{
return new StatusCodeResult((int)StatusCode);
}
if (Result is Stream stream)
{
return new FileStreamResult(stream, "application/octetstream")
{
FileDownloadName = FileName
};
}
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 OK<TResult, TData>(TData data, string fileName) where TResult : OperationResponse, new()
=> new() { StatusCode = HttpStatusCode.OK, Result = data, FileName = fileName };
protected static TResult NoContent<TResult>() where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.NoContent };
protected static TResult BadRequest<TResult>(string? errorMessage = null)

View File

@@ -1,7 +1,10 @@
namespace FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
using System.Globalization;
namespace FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
public class PostConfiguration
{
public virtual string Type => nameof(PostConfiguration);
public double Rate { get; set; }
public string CultureName { get; set; } = CultureInfo.CurrentCulture.Name;
}

View File

@@ -0,0 +1,387 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace FurnitureAssemblyContracts.Resources {
using System;
/// <summary>
/// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
/// </summary>
// Этот класс создан автоматически классом StronglyTypedResourceBuilder
// с помощью такого средства, как ResGen или Visual Studio.
// Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
// с параметром /str или перестройте свой проект VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Messages {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Messages() {
}
/// <summary>
/// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("FurnitureAssemblyContracts.Resources.Messages", typeof(Messages).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Не найден элемент по данным: {0}.
/// </summary>
internal static string AdapterMessageElementNotFoundException {
get {
return ResourceManager.GetString("AdapterMessageElementNotFoundException", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Данные пусты.
/// </summary>
internal static string AdapterMessageEmptyDate {
get {
return ResourceManager.GetString("AdapterMessageEmptyDate", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Неправильные даты: {0}.
/// </summary>
internal static string AdapterMessageIncorrectDatesException {
get {
return ResourceManager.GetString("AdapterMessageIncorrectDatesException", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Ошибка при обработке данных: {0}.
/// </summary>
internal static string AdapterMessageInvalidOperationException {
get {
return ResourceManager.GetString("AdapterMessageInvalidOperationException", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Ошибка при работе с хранилищем данных: {0}.
/// </summary>
internal static string AdapterMessageStorageException {
get {
return ResourceManager.GetString("AdapterMessageStorageException", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Переданы неверные данные: {0}.
/// </summary>
internal static string AdapterMessageValidationException {
get {
return ResourceManager.GetString("AdapterMessageValidationException", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Название.
/// </summary>
internal static string DocumentDocCaptionName {
get {
return ResourceManager.GetString("DocumentDocCaptionName", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Предыдущие названия.
/// </summary>
internal static string DocumentDocCaptionPreviousNames {
get {
return ResourceManager.GetString("DocumentDocCaptionPreviousNames", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на История изменение компонентов.
/// </summary>
internal static string DocumentDocHeaderComponents {
get {
return ResourceManager.GetString("DocumentDocHeaderComponents", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Сформировано на дату {0}.
/// </summary>
internal static string DocumentDocSubHeader {
get {
return ResourceManager.GetString("DocumentDocSubHeader", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Количество.
/// </summary>
internal static string DocumentExcelCaptionCount {
get {
return ResourceManager.GetString("DocumentExcelCaptionCount", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Дата.
/// </summary>
internal static string DocumentExcelCaptionDate {
get {
return ResourceManager.GetString("DocumentExcelCaptionDate", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Мебель.
/// </summary>
internal static string DocumentExcelCaptionFurniture_ {
get {
return ResourceManager.GetString("DocumentExcelCaptionFurniture ", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Всего.
/// </summary>
internal static string DocumentExcelCaptionTotal {
get {
return ResourceManager.GetString("DocumentExcelCaptionTotal", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Работник.
/// </summary>
internal static string DocumentExcelCaptionWorker_ {
get {
return ResourceManager.GetString("DocumentExcelCaptionWorker ", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Продажи за период.
/// </summary>
internal static string DocumentExcelHeader {
get {
return ResourceManager.GetString("DocumentExcelHeader", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на c {0} по {1}.
/// </summary>
internal static string DocumentExcelSubHeader {
get {
return ResourceManager.GetString("DocumentExcelSubHeader", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Начисления.
/// </summary>
internal static string DocumentPdfDiagramCaption {
get {
return ResourceManager.GetString("DocumentPdfDiagramCaption", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Зарплатная ведомость.
/// </summary>
internal static string DocumentPdfHeader {
get {
return ResourceManager.GetString("DocumentPdfHeader", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на за период с {0} по {1}.
/// </summary>
internal static string DocumentPdfSubHeader {
get {
return ResourceManager.GetString("DocumentPdfSubHeader", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Нельзя изменить удаленный элемент (идентификатор: {0}).
/// </summary>
internal static string ElementDeletedExceptionMessage {
get {
return ResourceManager.GetString("ElementDeletedExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Уже существует элемент со значением {0} параметра {1}.
/// </summary>
internal static string ElementExistsExceptionMessage {
get {
return ResourceManager.GetString("ElementExistsExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Элемент не найден по значению = {0}.
/// </summary>
internal static string ElementNotFoundExceptionMessage {
get {
return ResourceManager.GetString("ElementNotFoundExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Дата окончания должна быть позже даты начала. Дата начала: {0}. ​​Дата окончания: {1}.
/// </summary>
internal static string IncorrectDatesExceptionMessage {
get {
return ResourceManager.GetString("IncorrectDatesExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Недостаточно данных для обработки: {0}.
/// </summary>
internal static string NotEnoughDataToProcessExceptionMessage {
get {
return ResourceManager.GetString("NotEnoughDataToProcessExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Не найдены данные.
/// </summary>
internal static string NotFoundDataMessage {
get {
return ResourceManager.GetString("NotFoundDataMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Ошибка при работе в хранилище: {0}.
/// </summary>
internal static string StorageExceptionMessage {
get {
return ResourceManager.GetString("StorageExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Дата трудоустройства не может быть раньше даты рождения ({0}, {1}).
/// </summary>
internal static string ValidationExceptionMessageEmploymentDateAndBirthDate_ {
get {
return ResourceManager.GetString("ValidationExceptionMessageEmploymentDateAndBirthDate ", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле {0} пусто.
/// </summary>
internal static string ValidationExceptionMessageEmptyField {
get {
return ResourceManager.GetString("ValidationExceptionMessageEmptyField", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Некорректный формат ФИО.
/// </summary>
internal static string ValidationExceptionMessageIncorrectFIO_ {
get {
return ResourceManager.GetString("ValidationExceptionMessageIncorrectFIO ", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле {0} меньше или равно 0.
/// </summary>
internal static string ValidationExceptionMessageLessOrEqualZero {
get {
return ResourceManager.GetString("ValidationExceptionMessageLessOrEqualZero", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Несовершеннолетние не могут быть приняты на работу (Дата рождения: {0}).
/// </summary>
internal static string ValidationExceptionMessageMinorsBirthDate {
get {
return ResourceManager.GetString("ValidationExceptionMessageMinorsBirthDate", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Несовершеннолетние не могут быть приняты на работу (Дата трудоустройства: {0}, Дата рождения: {1}).
/// </summary>
internal static string ValidationExceptionMessageMinorsEmploymentDate {
get {
return ResourceManager.GetString("ValidationExceptionMessageMinorsEmploymentDate", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Отсутствуют компоненты.
/// </summary>
internal static string ValidationExceptionMessageNoComponents {
get {
return ResourceManager.GetString("ValidationExceptionMessageNoComponents", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле {0} не является типом уникального идентификатора.
/// </summary>
internal static string ValidationExceptionMessageNotAId {
get {
return ResourceManager.GetString("ValidationExceptionMessageNotAId", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле {0} не проинициализировано.
/// </summary>
internal static string ValidationExceptionMessageNotInitialized {
get {
return ResourceManager.GetString("ValidationExceptionMessageNotInitialized", resourceCulture);
}
}
}
}

View File

@@ -0,0 +1,228 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="AdapterMessageElementNotFoundException" xml:space="preserve">
<value>Not found element by data: {0}</value>
</data>
<data name="AdapterMessageEmptyDate" xml:space="preserve">
<value>Data is empty</value>
</data>
<data name="AdapterMessageIncorrectDatesException" xml:space="preserve">
<value>Incorrect dates: {0}</value>
</data>
<data name="AdapterMessageInvalidOperationException" xml:space="preserve">
<value>Error processing data: {0}</value>
</data>
<data name="AdapterMessageStorageException" xml:space="preserve">
<value>Error while working with data storage: {0}</value>
</data>
<data name="AdapterMessageValidationException" xml:space="preserve">
<value>Incorrect data transmitted: {0}</value>
</data>
<data name="DocumentDocCaptionName" xml:space="preserve">
<value>Names</value>
</data>
<data name="DocumentDocCaptionPreviousNames" xml:space="preserve">
<value>Previous names</value>
</data>
<data name="DocumentDocHeaderComponents" xml:space="preserve">
<value>HistoryNames of Component</value>
</data>
<data name="DocumentDocSubHeader" xml:space="preserve">
<value>Make In Date {0}</value>
</data>
<data name="DocumentExcelCaptionCount" xml:space="preserve">
<value>Count</value>
</data>
<data name="DocumentExcelCaptionDate" xml:space="preserve">
<value>Date</value>
</data>
<data name="DocumentExcelCaptionFurniture " xml:space="preserve">
<value>Furniture</value>
</data>
<data name="DocumentExcelCaptionTotal" xml:space="preserve">
<value>Total</value>
</data>
<data name="DocumentExcelCaptionWorker " xml:space="preserve">
<value>Worker</value>
</data>
<data name="DocumentExcelHeader" xml:space="preserve">
<value>Sales for the period</value>
</data>
<data name="DocumentExcelSubHeader" xml:space="preserve">
<value>from {0} to {1}</value>
</data>
<data name="DocumentPdfDiagramCaption" xml:space="preserve">
<value>Accruals</value>
</data>
<data name="DocumentPdfHeader" xml:space="preserve">
<value>Payroll</value>
</data>
<data name="DocumentPdfSubHeader" xml:space="preserve">
<value>for the period from {0} to {1}</value>
</data>
<data name="ElementDeletedExceptionMessage" xml:space="preserve">
<value>Cannot modify a deleted item (id: {0})</value>
</data>
<data name="ElementExistsExceptionMessage" xml:space="preserve">
<value>There is already an element with value {0} of parameter {1}</value>
</data>
<data name="ElementNotFoundExceptionMessage" xml:space="preserve">
<value>Element not found at value = {0}</value>
</data>
<data name="IncorrectDatesExceptionMessage" xml:space="preserve">
<value>The end date must be later than the start date.. StartDate: {0}. EndDate: {1}</value>
</data>
<data name="NotEnoughDataToProcessExceptionMessage" xml:space="preserve">
<value>Not enough data to process: {0}</value>
</data>
<data name="NotFoundDataMessage" xml:space="preserve">
<value>No data found</value>
</data>
<data name="StorageExceptionMessage" xml:space="preserve">
<value>Error while working in storage: {0}</value>
</data>
<data name="ValidationExceptionMessageEmploymentDateAndBirthDate " xml:space="preserve">
<value>Date of employment cannot be earlier than date of birth ({0}, {1})</value>
</data>
<data name="ValidationExceptionMessageEmptyField" xml:space="preserve">
<value>The value in field {0} is empty</value>
</data>
<data name="ValidationExceptionMessageIncorrectFIO " xml:space="preserve">
<value>Fio is not correct</value>
</data>
<data name="ValidationExceptionMessageLessOrEqualZero" xml:space="preserve">
<value>The value in field {0} is less than or equal to 0</value>
</data>
<data name="ValidationExceptionMessageMinorsBirthDate" xml:space="preserve">
<value>Minors cannot be hired (BirthDate = {0})</value>
</data>
<data name="ValidationExceptionMessageMinorsEmploymentDate" xml:space="preserve">
<value>Minors cannot be hired (EmploymentDate: {0}, BirthDate {1})</value>
</data>
<data name="ValidationExceptionMessageNoComponents" xml:space="preserve">
<value>There must be at least one item on components</value>
</data>
<data name="ValidationExceptionMessageNotAId" xml:space="preserve">
<value>The value in the {0} field is not a unique identifier type.</value>
</data>
<data name="ValidationExceptionMessageNotInitialized" xml:space="preserve">
<value>The value in field {0} is not initialized</value>
</data>
</root>

View File

@@ -0,0 +1,228 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="AdapterMessageElementNotFoundException" xml:space="preserve">
<value>Не найден элемент по данным: {0}</value>
</data>
<data name="AdapterMessageEmptyDate" xml:space="preserve">
<value>Данные пусты</value>
</data>
<data name="AdapterMessageIncorrectDatesException" xml:space="preserve">
<value>Неправильные даты: {0}</value>
</data>
<data name="AdapterMessageInvalidOperationException" xml:space="preserve">
<value>Ошибка при обработке данных: {0}</value>
</data>
<data name="AdapterMessageStorageException" xml:space="preserve">
<value>Ошибка при работе с хранилищем данных: {0}</value>
</data>
<data name="AdapterMessageValidationException" xml:space="preserve">
<value>Переданы неверные данные: {0}</value>
</data>
<data name="DocumentDocCaptionName" xml:space="preserve">
<value>Название</value>
</data>
<data name="DocumentDocCaptionPreviousNames" xml:space="preserve">
<value>Предыдущие названия</value>
</data>
<data name="DocumentDocHeaderComponents" xml:space="preserve">
<value>История изменение компонентов</value>
</data>
<data name="DocumentDocSubHeader" xml:space="preserve">
<value>Сформировано на дату {0}</value>
</data>
<data name="DocumentExcelCaptionCount" xml:space="preserve">
<value>Количество</value>
</data>
<data name="DocumentExcelCaptionDate" xml:space="preserve">
<value>Дата</value>
</data>
<data name="DocumentExcelCaptionFurniture " xml:space="preserve">
<value>Мебель</value>
</data>
<data name="DocumentExcelCaptionTotal" xml:space="preserve">
<value>Всего</value>
</data>
<data name="DocumentExcelCaptionWorker " xml:space="preserve">
<value>Работник</value>
</data>
<data name="DocumentExcelHeader" xml:space="preserve">
<value>Продажи за период</value>
</data>
<data name="DocumentExcelSubHeader" xml:space="preserve">
<value>c {0} по {1}</value>
</data>
<data name="DocumentPdfDiagramCaption" xml:space="preserve">
<value>Начисления</value>
</data>
<data name="DocumentPdfHeader" xml:space="preserve">
<value>Зарплатная ведомость</value>
</data>
<data name="DocumentPdfSubHeader" xml:space="preserve">
<value>за период с {0} по {1}</value>
</data>
<data name="ElementDeletedExceptionMessage" xml:space="preserve">
<value>Нельзя изменить удаленный элемент (идентификатор: {0})</value>
</data>
<data name="ElementExistsExceptionMessage" xml:space="preserve">
<value>Уже существует элемент со значением {0} параметра {1}</value>
</data>
<data name="ElementNotFoundExceptionMessage" xml:space="preserve">
<value>Элемент не найден по значению = {0}</value>
</data>
<data name="IncorrectDatesExceptionMessage" xml:space="preserve">
<value>Дата окончания должна быть позже даты начала. Дата начала: {0}. ​​Дата окончания: {1}</value>
</data>
<data name="NotEnoughDataToProcessExceptionMessage" xml:space="preserve">
<value>Недостаточно данных для обработки: {0}</value>
</data>
<data name="NotFoundDataMessage" xml:space="preserve">
<value>Не найдены данные</value>
</data>
<data name="StorageExceptionMessage" xml:space="preserve">
<value>Ошибка при работе в хранилище: {0}</value>
</data>
<data name="ValidationExceptionMessageEmploymentDateAndBirthDate " xml:space="preserve">
<value>Дата трудоустройства не может быть раньше даты рождения ({0}, {1})</value>
</data>
<data name="ValidationExceptionMessageEmptyField" xml:space="preserve">
<value>Значение в поле {0} пусто</value>
</data>
<data name="ValidationExceptionMessageIncorrectFIO " xml:space="preserve">
<value>Некорректный формат ФИО</value>
</data>
<data name="ValidationExceptionMessageLessOrEqualZero" xml:space="preserve">
<value>Значение в поле {0} меньше или равно 0</value>
</data>
<data name="ValidationExceptionMessageMinorsBirthDate" xml:space="preserve">
<value>Несовершеннолетние не могут быть приняты на работу (Дата рождения: {0})</value>
</data>
<data name="ValidationExceptionMessageMinorsEmploymentDate" xml:space="preserve">
<value>Несовершеннолетние не могут быть приняты на работу (Дата трудоустройства: {0}, Дата рождения: {1})</value>
</data>
<data name="ValidationExceptionMessageNoComponents" xml:space="preserve">
<value>Отсутствуют компоненты</value>
</data>
<data name="ValidationExceptionMessageNotAId" xml:space="preserve">
<value>Значение в поле {0} не является типом уникального идентификатора</value>
</data>
<data name="ValidationExceptionMessageNotInitialized" xml:space="preserve">
<value>Значение в поле {0} не проинициализировано</value>
</data>
</root>

View File

@@ -0,0 +1,228 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="AdapterMessageElementNotFoundException" xml:space="preserve">
<value>未找到元素数据: {0}</value>
</data>
<data name="AdapterMessageEmptyDate" xml:space="preserve">
<value>数据为空</value>
</data>
<data name="AdapterMessageIncorrectDatesException" xml:space="preserve">
<value>不正确的日期:{0}</value>
</data>
<data name="AdapterMessageInvalidOperationException" xml:space="preserve">
<value>数据处理过程中的错误:{0}</value>
</data>
<data name="AdapterMessageStorageException" xml:space="preserve">
<value>使用数据仓库时出错:{0}</value>
</data>
<data name="AdapterMessageValidationException" xml:space="preserve">
<value>传递的数据不正确: {0}</value>
</data>
<data name="DocumentDocCaptionName" xml:space="preserve">
<value>标题</value>
</data>
<data name="DocumentDocCaptionPreviousNames" xml:space="preserve">
<value>以前的名字</value>
</data>
<data name="DocumentDocHeaderComponents" xml:space="preserve">
<value>组件修改历史</value>
</data>
<data name="DocumentDocSubHeader" xml:space="preserve">
<value>在日期{0}生成</value>
</data>
<data name="DocumentExcelCaptionCount" xml:space="preserve">
<value>数量</value>
</data>
<data name="DocumentExcelCaptionDate" xml:space="preserve">
<value>日期</value>
</data>
<data name="DocumentExcelCaptionFurniture " xml:space="preserve">
<value>家具</value>
</data>
<data name="DocumentExcelCaptionTotal" xml:space="preserve">
<value>总计</value>
</data>
<data name="DocumentExcelCaptionWorker " xml:space="preserve">
<value>工人</value>
</data>
<data name="DocumentExcelHeader" xml:space="preserve">
<value>期间的销售额</value>
</data>
<data name="DocumentExcelSubHeader" xml:space="preserve">
<value>从{0}到{1}</value>
</data>
<data name="DocumentPdfDiagramCaption" xml:space="preserve">
<value>应计事项</value>
</data>
<data name="DocumentPdfHeader" xml:space="preserve">
<value>薪金表</value>
</data>
<data name="DocumentPdfSubHeader" xml:space="preserve">
<value>从{0}到{1}的期间</value>
</data>
<data name="ElementDeletedExceptionMessage" xml:space="preserve">
<value>无法更改已删除的项目(id:{0})</value>
</data>
<data name="ElementExistsExceptionMessage" xml:space="preserve">
<value>已存在具有值的元素</value>
</data>
<data name="ElementNotFoundExceptionMessage" xml:space="preserve">
<value>值={0}未找到该元素</value>
</data>
<data name="IncorrectDatesExceptionMessage" xml:space="preserve">
<value>结束日期必须晚于开始日期。 开始日期:{0}。 ​​结束日期:{1}</value>
</data>
<data name="NotEnoughDataToProcessExceptionMessage" xml:space="preserve">
<value>处理数据不足:{0}</value>
</data>
<data name="NotFoundDataMessage" xml:space="preserve">
<value>未找到数据</value>
</data>
<data name="StorageExceptionMessage" xml:space="preserve">
<value>在存储中工作时出错:{0}</value>
</data>
<data name="ValidationExceptionMessageEmploymentDateAndBirthDate " xml:space="preserve">
<value>就业日期不能早于出生日期({0},{1})</value>
</data>
<data name="ValidationExceptionMessageEmptyField" xml:space="preserve">
<value>字段 {0} 的值为空</value>
</data>
<data name="ValidationExceptionMessageIncorrectFIO " xml:space="preserve">
<value>名称格式不正确</value>
</data>
<data name="ValidationExceptionMessageLessOrEqualZero" xml:space="preserve">
<value>{0}字段中的值小于或等于0</value>
</data>
<data name="ValidationExceptionMessageMinorsBirthDate" xml:space="preserve">
<value>未成年人不能就业(出生日期:{0}</value>
</data>
<data name="ValidationExceptionMessageMinorsEmploymentDate" xml:space="preserve">
<value>未成年人不能就业(就业日期:{0},出生日期:{1}</value>
</data>
<data name="ValidationExceptionMessageNoComponents" xml:space="preserve">
<value>缺少组件</value>
</data>
<data name="ValidationExceptionMessageNotAId" xml:space="preserve">
<value>字段 {0} 的值不是唯一标识符类型</value>
</data>
<data name="ValidationExceptionMessageNotInitialized" xml:space="preserve">
<value>字段 Id 的值为空</value>
</data>
</root>

View File

@@ -2,12 +2,13 @@
namespace FurnitureAssemblyContracts.StoragesContracts;
public interface IComponentStorageContract
internal interface IComponentStorageContract
{
List<ComponentDataModel> GetList();
ComponentDataModel? GetElementById(string id);
ComponentDataModel? GetElementByName(string name);
ComponentDataModel? GetElementByOldName(string name);
Task<List<ComponentDataModel>> GetListAsync(CancellationToken ct);
void AddElement(ComponentDataModel manufacturerDataModel);
void UpdElement(ComponentDataModel manufacturerDataModel);
void DelElement(string id);

View File

@@ -2,7 +2,7 @@
namespace FurnitureAssemblyContracts.StoragesContracts;
public interface IFurnitureStorageContract
internal interface IFurnitureStorageContract
{
List<FurnitureDataModel> GetList();
FurnitureDataModel GetElementById(string id);

View File

@@ -2,9 +2,10 @@
namespace FurnitureAssemblyContracts.StoragesContracts;
public interface IManifacturingStorageContract
internal interface IManifacturingStorageContract
{
List<ManifacturingFurnitureDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? workerId = null, string? furnitureId = null);
Task<List<ManifacturingFurnitureDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct);
ManifacturingFurnitureDataModel? GetElementById(string id);
void AddElement(ManifacturingFurnitureDataModel manifacturingFurnitureDataModel);
void UpdElement(ManifacturingFurnitureDataModel manifacturingFurnitureDataModel);

View File

@@ -2,7 +2,7 @@
namespace FurnitureAssemblyContracts.StoragesContracts;
public interface IPostStorageContract
internal interface IPostStorageContract
{
List<PostDataModel> GetList();
List<PostDataModel> GetPostWithHistory(string postId);

View File

@@ -2,8 +2,9 @@
namespace FurnitureAssemblyContracts.StoragesContracts;
public interface ISalaryStorageContract
internal interface ISalaryStorageContract
{
List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? workerId = null);
Task<List<SalaryDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct);
void AddElement(SalaryDataModel salaryDataModel);
}

View File

@@ -2,7 +2,7 @@
namespace FurnitureAssemblyContracts.StoragesContracts;
public interface IWorkerStorageContract
internal interface IWorkerStorageContract
{
List<WorkerDataModel> GetList(bool onlyActive = true, string? postId =null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null,
DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null);

View File

@@ -0,0 +1,10 @@
using FurnitureAssemblyContracts.Enums;
namespace FurnitureAssemblyContracts.ViewModels;
public class ComponentHistoryViewModel
{
public required string CurrentName { get; set; }
public required ComponentType Type { get; set; }
public List<string>? HistoryNames { get; set; }
}

View File

@@ -5,5 +5,5 @@ public class PostViewModel
public required string Id { get; set; }
public required string PostName { get; set; }
public required string PostType { get; set; }
public required string Configuration { get; set; }
public double Salary { get; set; }
}

View File

@@ -0,0 +1,9 @@
namespace FurnitureAssemblyContracts.ViewModels;
public class WorkerSalaryByPeriodViewModel
{
public required string WorkerFIO { get; set; }
public double TotalSalary { get; set; }
public DateTime FromPeriod { get; set; }
public DateTime ToPeriod { get; set; }
}

View File

@@ -9,4 +9,5 @@ public class WorkerViewModel
public bool IsDeleted { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
public required string Configuration { get; set; }
}

View File

@@ -8,23 +8,23 @@
<ItemGroup>
<PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Newtonsoft.Json" Version="9.0.1" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\FurnitureAssemblyContracts\FurnitureAssemblyContracts.csproj" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\FurnitureAssemblyContracts\FurnitureAssemblyContracts.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="FurnitureAssemblyTests" />
<InternalVisibleTo Include="FurnitureAssemblyWebApi"/>
<InternalsVisibleTo Include="DynamicProxyGenAssembly2"/>
<InternalsVisibleTo Include="FurnitureAssemblyWebApi" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
</Project>

View File

@@ -1,21 +1,19 @@
using FurnitureAssemblyContracts.Infrastructure;
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
using Newtonsoft.Json.Linq;
namespace FurnitureAssemblyDatebase;
public class FurnitureAssemblyDbContext : DbContext
internal class FurnitureAssemblyDbContext : DbContext
{
private readonly IConfigurationDatabase? _configurationDatabase;
public FurnitureAssemblyDbContext(IConfigurationDatabase configurationDatabase)
{
_configurationDatabase = configurationDatabase;
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
@@ -51,7 +49,7 @@ public class FurnitureAssemblyDbContext : DbContext
.HasForeignKey(fc => fc.FurnitureId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Post>()
modelBuilder.Entity<Worker>()
.Property(x => x.Configuration)
.HasColumnType("jsonb")
.HasConversion(
@@ -68,6 +66,7 @@ public class FurnitureAssemblyDbContext : DbContext
public DbSet<Worker> Workers { get; set; }
private static string SerializePostConfiguration(PostConfiguration postConfiguration) => JsonConvert.SerializeObject(postConfiguration);
private static PostConfiguration DeserialzePostConfiguration(string jsonString) => JToken.Parse(jsonString).Value<string>("Type") switch
{
nameof(BuilderPostConfiguration) => JsonConvert.DeserializeObject<BuilderPostConfiguration>(jsonString)!,

View File

@@ -1,19 +1,22 @@
using AutoMapper;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Resources;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
namespace FurnitureAssemblyDatebase.Implementations;
public class ComponentStorageContract : IComponentStorageContract
internal class ComponentStorageContract : IComponentStorageContract
{
private readonly FurnitureAssemblyDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public ComponentStorageContract(FurnitureAssemblyDbContext dbContext)
public ComponentStorageContract(FurnitureAssemblyDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
@@ -21,6 +24,7 @@ public class ComponentStorageContract : IComponentStorageContract
cfg.AddMaps(typeof(Component));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<ComponentDataModel> GetList()
@@ -32,7 +36,20 @@ public class ComponentStorageContract : IComponentStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public async Task<List<ComponentDataModel>> GetListAsync(CancellationToken ct)
{
try
{
return [.. await _dbContext.Components.Select(x => _mapper.Map<ComponentDataModel>(x)).ToListAsync(ct)];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
}
}
@@ -45,7 +62,7 @@ public class ComponentStorageContract : IComponentStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -58,7 +75,7 @@ public class ComponentStorageContract : IComponentStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -72,7 +89,7 @@ public class ComponentStorageContract : IComponentStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -86,17 +103,17 @@ public class ComponentStorageContract : IComponentStorageContract
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", manufacturerDataModel.Id);
throw new ElementExistsException("Id", manufacturerDataModel.Id, _localizer);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Components_Name" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Name", manufacturerDataModel.Name);
throw new ElementExistsException("Name", manufacturerDataModel.Name, _localizer);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -104,7 +121,7 @@ public class ComponentStorageContract : IComponentStorageContract
{
try
{
var element = GetComponentById(manufacturerDataModel.Id) ?? throw new ElementNotFoundException(manufacturerDataModel.Id);
var element = GetComponentById(manufacturerDataModel.Id) ?? throw new ElementNotFoundException(manufacturerDataModel.Id, _localizer);
if (element.Name != manufacturerDataModel.Name)
{
element.PrevPrevName = element.PrevName;
@@ -126,12 +143,12 @@ public class ComponentStorageContract : IComponentStorageContract
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Components_Name" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Name", manufacturerDataModel.Name);
throw new ElementExistsException("Name", manufacturerDataModel.Name, _localizer);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -139,7 +156,7 @@ public class ComponentStorageContract : IComponentStorageContract
{
try
{
var element = GetComponentById(id) ?? throw new ElementNotFoundException(id);
var element = GetComponentById(id) ?? throw new ElementNotFoundException(id, _localizer);
_dbContext.Components.Remove(element);
_dbContext.SaveChanges();
}
@@ -151,7 +168,7 @@ public class ComponentStorageContract : IComponentStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}

View File

@@ -1,19 +1,22 @@
using AutoMapper;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Resources;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
namespace FurnitureAssemblyDatebase;
public class FurnitureStorageContract : IFurnitureStorageContract
internal class FurnitureStorageContract : IFurnitureStorageContract
{
private readonly FurnitureAssemblyDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public FurnitureStorageContract(FurnitureAssemblyDbContext dbContext)
public FurnitureStorageContract(FurnitureAssemblyDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
@@ -24,6 +27,7 @@ public class FurnitureStorageContract : IFurnitureStorageContract
cfg.CreateMap<FurnitureComponentDataModel, FurnitureComponent>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<FurnitureDataModel> GetList()
@@ -35,7 +39,7 @@ public class FurnitureStorageContract : IFurnitureStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -48,7 +52,7 @@ public class FurnitureStorageContract : IFurnitureStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -61,7 +65,7 @@ public class FurnitureStorageContract : IFurnitureStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -75,17 +79,17 @@ public class FurnitureStorageContract : IFurnitureStorageContract
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", furnitureDataModel.Id);
throw new ElementExistsException("Id", furnitureDataModel.Id, _localizer);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Furnitures_Name" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Name", furnitureDataModel.Name);
throw new ElementExistsException("Name", furnitureDataModel.Name, _localizer);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -93,7 +97,7 @@ public class FurnitureStorageContract : IFurnitureStorageContract
{
try
{
var element = GetFurnitureById(furnitureDataModel.Id) ?? throw new ElementNotFoundException(furnitureDataModel.Id);
var element = GetFurnitureById(furnitureDataModel.Id) ?? throw new ElementNotFoundException(furnitureDataModel.Id, _localizer);
_dbContext.Furnitures.Update(_mapper.Map(furnitureDataModel, element));
_dbContext.SaveChanges();
}
@@ -105,12 +109,12 @@ public class FurnitureStorageContract : IFurnitureStorageContract
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Furnitures_Name" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Name", furnitureDataModel.Name);
throw new ElementExistsException("Name", furnitureDataModel.Name, _localizer);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -118,7 +122,7 @@ public class FurnitureStorageContract : IFurnitureStorageContract
{
try
{
var element = GetFurnitureById(id) ?? throw new ElementNotFoundException(id);
var element = GetFurnitureById(id) ?? throw new ElementNotFoundException(id, _localizer);
_dbContext.Furnitures.Remove(element);
_dbContext.SaveChanges();
}
@@ -130,7 +134,7 @@ public class FurnitureStorageContract : IFurnitureStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}

View File

@@ -1,19 +1,22 @@
using AutoMapper;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Resources;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
namespace FurnitureAssemblyDatebase.Implementations;
public class ManifacturingStorageContract : IManifacturingStorageContract
internal class ManifacturingStorageContract : IManifacturingStorageContract
{
private readonly FurnitureAssemblyDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public ManifacturingStorageContract(FurnitureAssemblyDbContext dbContext)
public ManifacturingStorageContract(FurnitureAssemblyDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
@@ -24,6 +27,7 @@ public class ManifacturingStorageContract : IManifacturingStorageContract
cfg.CreateMap<ManifacturingFurnitureDataModel, ManifacturingFurniture>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<ManifacturingFurnitureDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? workerId = null, string? furnitureId = null)
@@ -48,7 +52,21 @@ public class ManifacturingStorageContract : IManifacturingStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public async Task<List<ManifacturingFurnitureDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct)
{
try
{
return [.. await _dbContext.Manufacturing.Include(x => x.Worker).Include(x => x.Furniture).Where(x => x.ProductuionDate >= startDate && x.ProductuionDate < endDate)
.Select(x => _mapper.Map<ManifacturingFurnitureDataModel>(x)).ToListAsync(ct)];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
}
}
@@ -61,7 +79,7 @@ public class ManifacturingStorageContract : IManifacturingStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -75,7 +93,7 @@ public class ManifacturingStorageContract : IManifacturingStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -83,7 +101,7 @@ public class ManifacturingStorageContract : IManifacturingStorageContract
{
try
{
var element = GetManifacturingById(manifacturingFurnitureDataModel.Id) ?? throw new ElementNotFoundException(manifacturingFurnitureDataModel.Id);
var element = GetManifacturingById(manifacturingFurnitureDataModel.Id) ?? throw new ElementNotFoundException(manifacturingFurnitureDataModel.Id, _localizer);
_dbContext.Manufacturing.Update(_mapper.Map(manifacturingFurnitureDataModel, element));
_dbContext.SaveChanges();
}
@@ -95,12 +113,12 @@ public class ManifacturingStorageContract : IManifacturingStorageContract
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Manifacturing_Id" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostId", manifacturingFurnitureDataModel.Id);
throw new ElementExistsException("PostId", manifacturingFurnitureDataModel.Id, _localizer);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}

View File

@@ -1,20 +1,23 @@
using AutoMapper;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Resources;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
using System.Xml.Linq;
namespace FurnitureAssemblyDatebase.Implementations;
public class PostStorageContract : IPostStorageContract
internal class PostStorageContract : IPostStorageContract
{
private readonly FurnitureAssemblyDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public PostStorageContract(FurnitureAssemblyDbContext dbContext)
public PostStorageContract(FurnitureAssemblyDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
@@ -26,10 +29,10 @@ public class PostStorageContract : IPostStorageContract
.ForMember(x => x.Id, x => x.Ignore())
.ForMember(x => x.PostId, x => x.MapFrom(src => src.Id))
.ForMember(x => x.IsActual, x => x.MapFrom(src => true))
.ForMember(x => x.ChangeDate, x => x.MapFrom(src => DateTime.UtcNow))
.ForMember(x => x.Configuration, x => x.MapFrom(src => src.ConfigurationModel));
.ForMember(x => x.ChangeDate, x => x.MapFrom(src => DateTime.UtcNow));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<PostDataModel> GetList()
@@ -41,7 +44,7 @@ public class PostStorageContract : IPostStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -54,7 +57,7 @@ public class PostStorageContract : IPostStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -67,7 +70,7 @@ public class PostStorageContract : IPostStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -80,7 +83,7 @@ public class PostStorageContract : IPostStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -94,17 +97,17 @@ public class PostStorageContract : IPostStorageContract
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostName", postDataModel.PostName);
throw new ElementExistsException("PostName", postDataModel.PostName, _localizer);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostId_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostId", postDataModel.Id);
throw new ElementExistsException("PostId", postDataModel.Id, _localizer);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -115,11 +118,11 @@ public class PostStorageContract : IPostStorageContract
var transaction = _dbContext.Database.BeginTransaction();
try
{
var element = GetPostById(postDataModel.Id) ?? throw new ElementNotFoundException(postDataModel.Id);
var element = GetPostById(postDataModel.Id) ?? throw new ElementNotFoundException(postDataModel.Id, _localizer);
if (!element.IsActual)
{
throw new
ElementDeletedException(postDataModel.Id);
ElementDeletedException(postDataModel.Id, _localizer);
}
element.IsActual = false;
_dbContext.SaveChanges();
@@ -137,7 +140,7 @@ public class PostStorageContract : IPostStorageContract
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostName", postDataModel.PostName);
throw new ElementExistsException("PostName", postDataModel.PostName, _localizer);
}
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
{
@@ -147,7 +150,7 @@ public class PostStorageContract : IPostStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -155,10 +158,10 @@ public class PostStorageContract : IPostStorageContract
{
try
{
var element = GetPostById(id) ?? throw new ElementNotFoundException(id);
var element = GetPostById(id) ?? throw new ElementNotFoundException(id, _localizer);
if (!element.IsActual)
{
throw new ElementDeletedException(id);
throw new ElementDeletedException(id, _localizer);
}
element.IsActual = false;
_dbContext.SaveChanges();
@@ -174,7 +177,7 @@ public class PostStorageContract : IPostStorageContract
{
try
{
var element = GetPostById(id) ?? throw new ElementNotFoundException(id);
var element = GetPostById(id) ?? throw new ElementNotFoundException(id, _localizer);
element.IsActual = true;
_dbContext.SaveChanges();
}

View File

@@ -1,18 +1,21 @@
using AutoMapper;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Resources;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
namespace FurnitureAssemblyDatebase.Implementations;
public class SalaryStorageContract : ISalaryStorageContract
internal class SalaryStorageContract : ISalaryStorageContract
{
private readonly FurnitureAssemblyDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public SalaryStorageContract(FurnitureAssemblyDbContext dbContext)
public SalaryStorageContract(FurnitureAssemblyDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
@@ -23,6 +26,7 @@ public class SalaryStorageContract : ISalaryStorageContract
.ForMember(dest => dest.WorkerSalary, opt => opt.MapFrom(src => src.Salary));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? workerId = null)
{
@@ -38,7 +42,20 @@ public class SalaryStorageContract : ISalaryStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public async Task<List<SalaryDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct)
{
try
{
return [.. await _dbContext.Salaries.Include(x => x.Worker).Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate).Select(x => _mapper.Map<SalaryDataModel>(x)).ToListAsync(ct)];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
}
}
@@ -52,7 +69,7 @@ public class SalaryStorageContract : ISalaryStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
}

View File

@@ -1,17 +1,22 @@
using AutoMapper;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Resources;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
namespace FurnitureAssemblyDatebase.Implementations;
public class WorkerStorageContract : IWorkerStorageContract
internal class WorkerStorageContract : IWorkerStorageContract
{
private readonly FurnitureAssemblyDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public WorkerStorageContract(FurnitureAssemblyDbContext dbContext)
public WorkerStorageContract(FurnitureAssemblyDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
@@ -19,9 +24,12 @@ public class WorkerStorageContract : IWorkerStorageContract
cfg.CreateMap<Post, PostDataModel>()
.ForMember(x => x.Id, x => x.MapFrom(src => src.PostId));
cfg.CreateMap<Worker, WorkerDataModel>();
cfg.CreateMap<WorkerDataModel, Worker>();
cfg.CreateMap<WorkerDataModel, Worker>()
.ForMember(x => x.Configuration, x => x.MapFrom(src => src.ConfigurationModel));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<WorkerDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null)
@@ -50,7 +58,7 @@ public class WorkerStorageContract : IWorkerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -63,7 +71,7 @@ public class WorkerStorageContract : IWorkerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -76,7 +84,7 @@ public class WorkerStorageContract : IWorkerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -90,12 +98,17 @@ public class WorkerStorageContract : IWorkerStorageContract
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", workerDataModel.Id);
throw new ElementExistsException("Id", workerDataModel.Id, _localizer);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "PK_Workers" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", workerDataModel.Id, _localizer);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -103,7 +116,7 @@ public class WorkerStorageContract : IWorkerStorageContract
{
try
{
var element = GetWorkerById(workerDataModel.Id) ?? throw new ElementNotFoundException(workerDataModel.Id);
var element = GetWorkerById(workerDataModel.Id) ?? throw new ElementNotFoundException(workerDataModel.Id, _localizer);
_dbContext.Workers.Update(_mapper.Map(workerDataModel, element));
_dbContext.SaveChanges();
}
@@ -115,7 +128,7 @@ public class WorkerStorageContract : IWorkerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -123,7 +136,7 @@ public class WorkerStorageContract : IWorkerStorageContract
{
try
{
var element = GetWorkerById(id) ?? throw new ElementNotFoundException(id);
var element = GetWorkerById(id) ?? throw new ElementNotFoundException(id, _localizer);
element.IsDeleted = true;
element.DateOfDelete = DateTime.UtcNow;
_dbContext.SaveChanges();
@@ -136,7 +149,7 @@ public class WorkerStorageContract : IWorkerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -151,7 +164,7 @@ public class WorkerStorageContract : IWorkerStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}

View File

@@ -1,279 +0,0 @@
// <auto-generated />
using System;
using FurnitureAssemblyDatebase;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace FurnitureAssemblyDatebase.Migrations
{
[DbContext(typeof(FurnitureAssemblyDbContext))]
[Migration("20250331133531_ChangeFieldsInPost")]
partial class ChangeFieldsInPost
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Component", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PrevName")
.HasColumnType("text");
b.Property<string>("PrevPrevName")
.HasColumnType("text");
b.Property<int>("Type")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("Components");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Furniture", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Weight")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("Furnitures");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.FurnitureComponent", b =>
{
b.Property<string>("FurnitureId")
.HasColumnType("text");
b.Property<string>("ComponentId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.HasKey("FurnitureId", "ComponentId");
b.HasIndex("ComponentId");
b.ToTable("FurnitureComponents");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.ManifacturingFurniture", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<string>("FurnitureId")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("ProductuionDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("FurnitureId");
b.HasIndex("WorkerId");
b.ToTable("Manufacturing");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Post", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Configuration")
.IsRequired()
.HasColumnType("jsonb");
b.Property<bool>("IsActual")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PostName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("PostType")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("PostId", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.HasIndex("PostName", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.ToTable("Posts");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Salary", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("SalaryDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("WorkerSalary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("WorkerId");
b.ToTable("Salaries");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Worker", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("BirthDate")
.HasColumnType("timestamp without time zone");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<DateTime>("EmploymentDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Workers");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.FurnitureComponent", b =>
{
b.HasOne("FurnitureAssemblyDatebase.Models.Component", "Component")
.WithMany("FurnitureComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FurnitureAssemblyDatebase.Models.Furniture", "Furniture")
.WithMany("Components")
.HasForeignKey("FurnitureId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Component");
b.Navigation("Furniture");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.ManifacturingFurniture", b =>
{
b.HasOne("FurnitureAssemblyDatebase.Models.Furniture", "Furniture")
.WithMany()
.HasForeignKey("FurnitureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FurnitureAssemblyDatebase.Models.Worker", "Worker")
.WithMany("ManifacturingFurniture")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Furniture");
b.Navigation("Worker");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Salary", b =>
{
b.HasOne("FurnitureAssemblyDatebase.Models.Worker", "Worker")
.WithMany("Salaries")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Worker");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Component", b =>
{
b.Navigation("FurnitureComponents");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Furniture", b =>
{
b.Navigation("Components");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Worker", b =>
{
b.Navigation("ManifacturingFurniture");
b.Navigation("Salaries");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -1,40 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace FurnitureAssemblyDatebase.Migrations
{
/// <inheritdoc />
public partial class ChangeFieldsInPost : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Salary",
table: "Posts");
migrationBuilder.AddColumn<string>(
name: "Configuration",
table: "Posts",
type: "jsonb",
nullable: false,
defaultValue: "{\"Rate\": 0, \"Type\": \"PostConfiguration\"}");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Configuration",
table: "Posts");
migrationBuilder.AddColumn<double>(
name: "Salary",
table: "Posts",
type: "double precision",
nullable: false,
defaultValue: 0.0);
}
}
}

View File

@@ -12,7 +12,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace FurnitureAssemblyDatebase.Migrations
{
[DbContext(typeof(FurnitureAssemblyDbContext))]
[Migration("20250331085649_FirstMigration")]
[Migration("20250404123937_FirstMigration")]
partial class FirstMigration
{
/// <inheritdoc />
@@ -20,7 +20,7 @@ namespace FurnitureAssemblyDatebase.Migrations
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.3")
.HasAnnotation("ProductVersion", "9.0.2")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);

View File

@@ -12,7 +12,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace FurnitureAssemblyDatebase.Migrations
{
[DbContext(typeof(FurnitureAssemblyDbContext))]
[Migration("20250401182232_ChangeWorker")]
[Migration("20250415132953_ChangeWorker")]
partial class ChangeWorker
{
/// <inheritdoc />
@@ -20,7 +20,7 @@ namespace FurnitureAssemblyDatebase.Migrations
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.3")
.HasAnnotation("ProductVersion", "9.0.2")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
@@ -125,10 +125,6 @@ namespace FurnitureAssemblyDatebase.Migrations
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Configuration")
.IsRequired()
.HasColumnType("jsonb");
b.Property<bool>("IsActual")
.HasColumnType("boolean");
@@ -143,6 +139,9 @@ namespace FurnitureAssemblyDatebase.Migrations
b.Property<int>("PostType")
.HasColumnType("integer");
b.Property<double>("Salary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("PostId", "IsActual")
@@ -189,6 +188,10 @@ namespace FurnitureAssemblyDatebase.Migrations
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Configuration")
.IsRequired()
.HasColumnType("jsonb");
b.Property<DateTime?>("DateOfDelete")
.HasColumnType("timestamp without time zone");

View File

@@ -11,6 +11,13 @@ namespace FurnitureAssemblyDatebase.Migrations
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Configuration",
table: "Workers",
type: "jsonb",
nullable: false,
defaultValue: "");
migrationBuilder.AddColumn<DateTime>(
name: "DateOfDelete",
table: "Workers",
@@ -21,6 +28,10 @@ namespace FurnitureAssemblyDatebase.Migrations
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Configuration",
table: "Workers");
migrationBuilder.DropColumn(
name: "DateOfDelete",
table: "Workers");

View File

@@ -17,7 +17,7 @@ namespace FurnitureAssemblyDatebase.Migrations
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.3")
.HasAnnotation("ProductVersion", "9.0.2")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
@@ -122,10 +122,6 @@ namespace FurnitureAssemblyDatebase.Migrations
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Configuration")
.IsRequired()
.HasColumnType("jsonb");
b.Property<bool>("IsActual")
.HasColumnType("boolean");
@@ -140,6 +136,9 @@ namespace FurnitureAssemblyDatebase.Migrations
b.Property<int>("PostType")
.HasColumnType("integer");
b.Property<double>("Salary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("PostId", "IsActual")
@@ -186,6 +185,10 @@ namespace FurnitureAssemblyDatebase.Migrations
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Configuration")
.IsRequired()
.HasColumnType("jsonb");
b.Property<DateTime?>("DateOfDelete")
.HasColumnType("timestamp without time zone");

View File

@@ -6,7 +6,7 @@ using System.ComponentModel.DataAnnotations.Schema;
namespace FurnitureAssemblyDatebase.Models;
[AutoMap(typeof(ComponentDataModel), ReverseMap = true)]
public class Component
internal class Component
{
public required string Id { get; set; }
public required string Name { get; set; }

View File

@@ -3,7 +3,7 @@ using System.ComponentModel.DataAnnotations.Schema;
namespace FurnitureAssemblyDatebase.Models;
public class Furniture
internal class Furniture
{
public required string Id { get; set; }
public required string Name { get; set; }

View File

@@ -1,6 +1,6 @@
namespace FurnitureAssemblyDatebase.Models;
public class FurnitureComponent
internal class FurnitureComponent
{
public required string FurnitureId { get; set; }
public required string ComponentId { get; set; }

View File

@@ -1,6 +1,6 @@
namespace FurnitureAssemblyDatebase.Models;
public class ManifacturingFurniture
internal class ManifacturingFurniture
{
public required string Id { get; set; }
public required string FurnitureId { get; set; }

View File

@@ -1,15 +1,14 @@
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
namespace FurnitureAssemblyDatebase.Models;
public class Post
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 required PostConfiguration Configuration { get; set; }
public double Salary { get; set; }
public bool IsActual { get; set; }
public DateTime ChangeDate { get; set; }
}

View File

@@ -1,6 +1,6 @@
namespace FurnitureAssemblyDatebase.Models;
public class Salary
internal class Salary
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string WorkerId { get; set; }

View File

@@ -1,9 +1,10 @@
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
using System.ComponentModel.DataAnnotations.Schema;
namespace FurnitureAssemblyDatebase.Models;
public class Worker
internal class Worker
{
public required string Id { get; set; }
public required string FIO { get; set; }
@@ -24,4 +25,6 @@ public class Worker
return this;
}
public DateTime? DateOfDelete { get; set; }
public required PostConfiguration Configuration { get; set; }
}

View File

@@ -2,10 +2,10 @@
namespace FurnitureAssemblyDatebase;
public class SampleContextFactory : IDesignTimeDbContextFactory<FurnitureAssemblyDbContext>
internal class SampleContextFactory : IDesignTimeDbContextFactory<FurnitureAssemblyDbContext>
{
public FurnitureAssemblyDbContext CreateDbContext(string[] args)
{
return new FurnitureAssemblyDbContext(new DefaultConfigurationDatabase());
}
}
}

View File

@@ -4,6 +4,7 @@ using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyTests.Infrastructure;
using Microsoft.Extensions.Logging;
using Moq;
@@ -19,7 +20,7 @@ internal class ComponentBusinessLogicContractTests
public void OneTimeSetUp()
{
_componentStorageContract = new Mock<IComponentStorageContract>();
_componentBusinessLogicContract = new ComponentBusinessLogicContract(_componentStorageContract.Object, new Mock<ILogger>().Object);
_componentBusinessLogicContract = new ComponentBusinessLogicContract(_componentStorageContract.Object, StringLocalizerMockCreator.GetStringLocalizerMockObject(), new Mock<ILogger>().Object);
}
[TearDown]
@@ -59,18 +60,11 @@ internal class ComponentBusinessLogicContractTests
_componentStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllComponents_ReturnNull_ThrowException_Test()
{
Assert.That(() => _componentBusinessLogicContract.GetAllComponents(), Throws.TypeOf<NullListException>());
_componentStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllComponents_StorageThrowError_ThrowException_Test()
{
//Arrange
_componentStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
_componentStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _componentBusinessLogicContract.GetAllComponents(), Throws.TypeOf<StorageException>());
_componentStorageContract.Verify(x => x.GetList(), Times.Once);
@@ -159,8 +153,8 @@ internal class ComponentBusinessLogicContractTests
public void GetComponentsByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_componentStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_componentStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_componentStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
_componentStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _componentBusinessLogicContract.GetComponentByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _componentBusinessLogicContract.GetComponentByData("name"), Throws.TypeOf<StorageException>());
@@ -173,7 +167,7 @@ internal class ComponentBusinessLogicContractTests
public void GetComponentsByData_GetByOldName_StorageThrowError_ThrowException_Test()
{
//Arrange
_componentStorageContract.Setup(x => x.GetElementByOldName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_componentStorageContract.Setup(x => x.GetElementByOldName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _componentBusinessLogicContract.GetComponentByData("name"), Throws.TypeOf<StorageException>());
_componentStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
@@ -201,7 +195,7 @@ internal class ComponentBusinessLogicContractTests
public void InsertComponents_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_componentStorageContract.Setup(x => x.AddElement(It.IsAny<ComponentDataModel>())).Throws(new ElementExistsException("Data", "Data"));
_componentStorageContract.Setup(x => x.AddElement(It.IsAny<ComponentDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _componentBusinessLogicContract.InsertComponent(new(Guid.NewGuid().ToString(), "name", ComponentType.Panel)), Throws.TypeOf<ElementExistsException>());
_componentStorageContract.Verify(x => x.AddElement(It.IsAny<ComponentDataModel>()), Times.Once);
@@ -228,7 +222,7 @@ internal class ComponentBusinessLogicContractTests
public void InsertComponents_StorageThrowError_ThrowException_Test()
{
//Arrange
_componentStorageContract.Setup(x => x.AddElement(It.IsAny<ComponentDataModel>())).Throws(new StorageException(new InvalidOperationException()));
_componentStorageContract.Setup(x => x.AddElement(It.IsAny<ComponentDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _componentBusinessLogicContract.InsertComponent(new(Guid.NewGuid().ToString(), "name", ComponentType.Panel)), Throws.TypeOf<StorageException>());
_componentStorageContract.Verify(x => x.AddElement(It.IsAny<ComponentDataModel>()), Times.Once);
@@ -255,7 +249,7 @@ internal class ComponentBusinessLogicContractTests
public void UpdateComponents_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_componentStorageContract.Setup(x => x.UpdElement(It.IsAny<ComponentDataModel>())).Throws(new ElementNotFoundException(""));
_componentStorageContract.Setup(x => x.UpdElement(It.IsAny<ComponentDataModel>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _componentBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), "name", ComponentType.Panel)), Throws.TypeOf<ElementNotFoundException>());
_componentStorageContract.Verify(x => x.UpdElement(It.IsAny<ComponentDataModel>()), Times.Once);
@@ -265,7 +259,7 @@ internal class ComponentBusinessLogicContractTests
public void UpdateComponents_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_componentStorageContract.Setup(x => x.UpdElement(It.IsAny<ComponentDataModel>())).Throws(new ElementExistsException("Data", "Data"));
_componentStorageContract.Setup(x => x.UpdElement(It.IsAny<ComponentDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _componentBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), "name", ComponentType.Panel)), Throws.TypeOf<ElementExistsException>());
_componentStorageContract.Verify(x => x.UpdElement(It.IsAny<ComponentDataModel>()), Times.Once);
@@ -291,7 +285,7 @@ internal class ComponentBusinessLogicContractTests
public void UpdateComponents_StorageThrowError_ThrowException_Test()
{
//Arrange
_componentStorageContract.Setup(x => x.UpdElement(It.IsAny<ComponentDataModel>())).Throws(new StorageException(new InvalidOperationException()));
_componentStorageContract.Setup(x => x.UpdElement(It.IsAny<ComponentDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _componentBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), "name", ComponentType.Panel)), Throws.TypeOf<StorageException>());
_componentStorageContract.Verify(x => x.UpdElement(It.IsAny<ComponentDataModel>()), Times.Once);
@@ -315,7 +309,7 @@ internal class ComponentBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
_componentStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
_componentStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _componentBusinessLogicContract.DeleteComponent(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
@@ -344,7 +338,7 @@ internal class ComponentBusinessLogicContractTests
public void DeleteComponents_StorageThrowError_ThrowException_Test()
{
//Arrange
_componentStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_componentStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _componentBusinessLogicContract.DeleteComponent(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());

View File

@@ -3,6 +3,7 @@ using FurnitureAssemblyContracts.BusinessLogicsContracts;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyTests.Infrastructure;
using Microsoft.Extensions.Logging;
using Moq;
@@ -17,7 +18,7 @@ public class FurnitureBusinessLogicContractTests
public void OneTimeSetUp()
{
_furnitureStorageContract = new Mock<IFurnitureStorageContract>();
_furnitureBusinessLogicContract = new FurnitureBusinessLogicContract(_furnitureStorageContract.Object, new Mock<ILogger>().Object);
_furnitureBusinessLogicContract = new FurnitureBusinessLogicContract(_furnitureStorageContract.Object, StringLocalizerMockCreator.GetStringLocalizerMockObject(), new Mock<ILogger>().Object);
}
[TearDown]
@@ -57,19 +58,11 @@ public class FurnitureBusinessLogicContractTests
_furnitureStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllFurnitures_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _furnitureBusinessLogicContract.GetAllFurnitures(), Throws.TypeOf<NullListException>());
_furnitureStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllFurnitures_StorageThrowError_ThrowException_Test()
{
//Arrange
_furnitureStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
_furnitureStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _furnitureBusinessLogicContract.GetAllFurnitures(),Throws.TypeOf<StorageException>());
_furnitureStorageContract.Verify(x => x.GetList(), Times.Once);
@@ -139,8 +132,8 @@ public class FurnitureBusinessLogicContractTests
public void GetFurnituresByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_furnitureStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_furnitureStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_furnitureStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
_furnitureStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _furnitureBusinessLogicContract.GetFurnitureByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _furnitureBusinessLogicContract.GetFurnitureByData("name"), Throws.TypeOf<StorageException>());
@@ -169,7 +162,7 @@ public class FurnitureBusinessLogicContractTests
public void InsertFurnitures_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_furnitureStorageContract.Setup(x => x.AddElement(It.IsAny<FurnitureDataModel>())).Throws(new ElementExistsException("Data", "Data"));
_furnitureStorageContract.Setup(x => x.AddElement(It.IsAny<FurnitureDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _furnitureBusinessLogicContract.InsertFurniture(new(Guid.NewGuid().ToString(), "name", 10,
[new FurnitureComponentDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
@@ -197,7 +190,7 @@ public class FurnitureBusinessLogicContractTests
public void InsertFurnitures_StorageThrowError_ThrowException_Test()
{
//Arrange
_furnitureStorageContract.Setup(x => x.AddElement(It.IsAny<FurnitureDataModel>())).Throws(new StorageException(new InvalidOperationException()));
_furnitureStorageContract.Setup(x => x.AddElement(It.IsAny<FurnitureDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _furnitureBusinessLogicContract.InsertFurniture(new(Guid.NewGuid().ToString(), "name", 10,
[new FurnitureComponentDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
@@ -225,7 +218,7 @@ public class FurnitureBusinessLogicContractTests
public void UpdateFurnitures_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_furnitureStorageContract.Setup(x => x.UpdElement(It.IsAny<FurnitureDataModel>())).Throws(new ElementNotFoundException(""));
_furnitureStorageContract.Setup(x => x.UpdElement(It.IsAny<FurnitureDataModel>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _furnitureBusinessLogicContract.UpdateFurniture(new(Guid.NewGuid().ToString(), "name", 10,
[new FurnitureComponentDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementNotFoundException>());
@@ -236,7 +229,7 @@ public class FurnitureBusinessLogicContractTests
public void UpdateFurnitures_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_furnitureStorageContract.Setup(x => x.UpdElement(It.IsAny<FurnitureDataModel>())).Throws(new ElementExistsException("Data", "Data"));
_furnitureStorageContract.Setup(x => x.UpdElement(It.IsAny<FurnitureDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _furnitureBusinessLogicContract.UpdateFurniture(new(Guid.NewGuid().ToString(), "name", 10,
[new FurnitureComponentDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
@@ -264,7 +257,7 @@ public class FurnitureBusinessLogicContractTests
public void UpdateFurnitures_StorageThrowError_ThrowException_Test()
{
//Arrange
_furnitureStorageContract.Setup(x => x.UpdElement(It.IsAny<FurnitureDataModel>())).Throws(new StorageException(new InvalidOperationException()));
_furnitureStorageContract.Setup(x => x.UpdElement(It.IsAny<FurnitureDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _furnitureBusinessLogicContract.UpdateFurniture(new(Guid.NewGuid().ToString(), "name", 10,
[new FurnitureComponentDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),5)])), Throws.TypeOf<StorageException>());
@@ -289,7 +282,7 @@ public class FurnitureBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
_furnitureStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
_furnitureStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _furnitureBusinessLogicContract.DeleteFurniture(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
@@ -319,7 +312,7 @@ public class FurnitureBusinessLogicContractTests
public void DeleteFurnitures_StorageThrowError_ThrowException_Test()
{
//Arrange
_furnitureStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_furnitureStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _furnitureBusinessLogicContract.DeleteFurniture(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());

View File

@@ -3,6 +3,7 @@ using FurnitureAssemblyContracts.BusinessLogicsContracts;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyTests.Infrastructure;
using Microsoft.Extensions.Logging;
using Moq;
@@ -17,7 +18,7 @@ internal class ManifacturingBusinessLogicContractTests
public void OneTimeSetUp()
{
_manifacturingStorageContract = new Mock<IManifacturingStorageContract>();
_manifacturingBusinessLogicContract = new ManifacturingBusinessLogicContract(_manifacturingStorageContract.Object, new Mock<ILogger>().Object);
_manifacturingBusinessLogicContract = new ManifacturingBusinessLogicContract(_manifacturingStorageContract.Object, StringLocalizerMockCreator.GetStringLocalizerMockObject(), new Mock<ILogger>().Object);
}
[TearDown]
@@ -70,20 +71,12 @@ internal class ManifacturingBusinessLogicContractTests
_manifacturingStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllManifacturingByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _manifacturingBusinessLogicContract.GetManifacturingByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_manifacturingStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllManifacturingByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
.Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _manifacturingBusinessLogicContract.GetManifacturingByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_manifacturingStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
@@ -152,21 +145,12 @@ internal class ManifacturingBusinessLogicContractTests
_manifacturingStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllManifacturingByWorkerByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() =>
_manifacturingBusinessLogicContract.GetAllManifacturingByWorkerByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_manifacturingStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllManifacturingByWorkerByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
.Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _manifacturingBusinessLogicContract.GetAllManifacturingByWorkerByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)),Throws.TypeOf<StorageException>());
_manifacturingStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
@@ -235,21 +219,12 @@ internal class ManifacturingBusinessLogicContractTests
_manifacturingStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllManifacturingByFurnitureByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _manifacturingBusinessLogicContract.GetAllManifacturingByFurnitureByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)),
Throws.TypeOf<NullListException>());
_manifacturingStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllManifacturingByFurnitureByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
.Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _manifacturingBusinessLogicContract.GetAllManifacturingByFurnitureByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)),
Throws.TypeOf<StorageException>());
@@ -300,7 +275,7 @@ internal class ManifacturingBusinessLogicContractTests
public void GetManifacturingByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_manifacturingStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_manifacturingStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _manifacturingBusinessLogicContract.GetManifacturingByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_manifacturingStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
@@ -328,7 +303,7 @@ internal class ManifacturingBusinessLogicContractTests
public void InsertManifacturing_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_manifacturingStorageContract.Setup(x => x.AddElement(It.IsAny<ManifacturingFurnitureDataModel>())).Throws(new ElementExistsException("Data", "Data"));
_manifacturingStorageContract.Setup(x => x.AddElement(It.IsAny<ManifacturingFurnitureDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _manifacturingBusinessLogicContract.InsertFurniture(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, Guid.NewGuid().ToString())), Throws.TypeOf<ElementExistsException>());
_manifacturingStorageContract.Verify(x => x.AddElement(It.IsAny<ManifacturingFurnitureDataModel>()), Times.Once);
@@ -355,7 +330,7 @@ internal class ManifacturingBusinessLogicContractTests
public void InsertManifacturing_StorageThrowError_ThrowException_Test()
{
//Arrange
_manifacturingStorageContract.Setup(x => x.AddElement(It.IsAny<ManifacturingFurnitureDataModel>())).Throws(new StorageException(new InvalidOperationException()));
_manifacturingStorageContract.Setup(x => x.AddElement(It.IsAny<ManifacturingFurnitureDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _manifacturingBusinessLogicContract.InsertFurniture(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, Guid.NewGuid().ToString())),
Throws.TypeOf<StorageException>());
@@ -383,7 +358,7 @@ internal class ManifacturingBusinessLogicContractTests
public void UpdateManifacturing_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_manifacturingStorageContract.Setup(x => x.UpdElement(It.IsAny<ManifacturingFurnitureDataModel>())).Throws(new ElementNotFoundException(""));
_manifacturingStorageContract.Setup(x => x.UpdElement(It.IsAny<ManifacturingFurnitureDataModel>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _manifacturingBusinessLogicContract.UpdateFurniture(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, Guid.NewGuid().ToString())),
Throws.TypeOf<ElementNotFoundException>());
@@ -394,7 +369,7 @@ internal class ManifacturingBusinessLogicContractTests
public void UpdateManifacturing_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_manifacturingStorageContract.Setup(x => x.UpdElement(It.IsAny<ManifacturingFurnitureDataModel>())).Throws(new ElementExistsException("Data", "Data"));
_manifacturingStorageContract.Setup(x => x.UpdElement(It.IsAny<ManifacturingFurnitureDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _manifacturingBusinessLogicContract.UpdateFurniture(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, Guid.NewGuid().ToString())),
Throws.TypeOf<ElementExistsException>());
@@ -421,7 +396,7 @@ internal class ManifacturingBusinessLogicContractTests
public void UpdateManifacturing_StorageThrowError_ThrowException_Test()
{
//Arrange
_manifacturingStorageContract.Setup(x => x.UpdElement(It.IsAny<ManifacturingFurnitureDataModel>())).Throws(new StorageException(new InvalidOperationException()));
_manifacturingStorageContract.Setup(x => x.UpdElement(It.IsAny<ManifacturingFurnitureDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _manifacturingBusinessLogicContract.UpdateFurniture(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, Guid.NewGuid().ToString())), Throws.TypeOf<StorageException>());
_manifacturingStorageContract.Verify(x => x.UpdElement(It.IsAny<ManifacturingFurnitureDataModel>()), Times.Once);

View File

@@ -2,8 +2,8 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyTests.Infrastructure;
using Microsoft.Extensions.Logging;
using Moq;
@@ -18,7 +18,7 @@ internal class PostBusinessLogicContractTests
public void OneTimeSetUp()
{
_postStorageContract = new Mock<IPostStorageContract>();
_postBusinessLogicContract = new PostBusinessLogicContract(_postStorageContract.Object, new Mock<ILogger>().Object);
_postBusinessLogicContract = new PostBusinessLogicContract(_postStorageContract.Object, StringLocalizerMockCreator.GetStringLocalizerMockObject(), new Mock<ILogger>().Object);
}
[TearDown]
@@ -33,9 +33,9 @@ internal class PostBusinessLogicContractTests
//Arrange
var listOriginal = new List<PostDataModel>()
{
new(Guid.NewGuid().ToString(),"name 1", PostType.Builder, new PostConfiguration() { Rate = 10 }),
new(Guid.NewGuid().ToString(), "name 2", PostType.Builder, new PostConfiguration() { Rate = 10 }),
new(Guid.NewGuid().ToString(), "name 3", PostType.Builder, new PostConfiguration() { Rate = 10 }),
new(Guid.NewGuid().ToString(), "name 1", PostType.Builder, 10),
new(Guid.NewGuid().ToString(), "name 2", PostType.Builder, 10),
new(Guid.NewGuid().ToString(), "name 3", PostType.Builder, 10),
};
_postStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
//Act
@@ -64,19 +64,11 @@ internal class PostBusinessLogicContractTests
});
}
[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()));
_postStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllPosts(), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetList(), Times.Once);
@@ -89,8 +81,8 @@ internal class PostBusinessLogicContractTests
var postId = Guid.NewGuid().ToString();
var listOriginal = new List<PostDataModel>()
{
new(postId, "name 1", PostType.Builder, new PostConfiguration() { Rate = 10 }),
new(postId, "name 2", PostType.Builder, new PostConfiguration() { Rate = 10 })
new(postId, "name 1", PostType.Builder, 10),
new(postId, "name 2", PostType.Builder, 10)
};
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns(listOriginal);
//Act
@@ -131,19 +123,11 @@ internal class PostBusinessLogicContractTests
_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()));
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
@@ -154,7 +138,7 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new PostDataModel(id, "name", PostType.Builder, new PostConfiguration() { Rate = 10 });
var record = new PostDataModel(id, "name", PostType.Builder, 10);
_postStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(id);
@@ -169,7 +153,7 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var postName = "name";
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.Builder, new PostConfiguration() { Rate = 10 });
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.Builder, 10);
_postStorageContract.Setup(x => x.GetElementByName(postName)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(postName);
@@ -211,8 +195,8 @@ internal class PostBusinessLogicContractTests
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()));
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
_postStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _postBusinessLogicContract.GetPostByData("name"), Throws.TypeOf<StorageException>());
@@ -225,12 +209,13 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, new PostConfiguration() { Rate = 10 });
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 10);
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>()))
.Callback((PostDataModel x) =>
{
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.ConfigurationModel.Rate == record.ConfigurationModel.Rate;
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary;
});
//Act
_postBusinessLogicContract.InsertPost(record);
//Assert
@@ -242,9 +227,9 @@ internal class PostBusinessLogicContractTests
public void InsertPost_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementExistsException>());
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, 10)), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
}
@@ -260,7 +245,7 @@ internal class PostBusinessLogicContractTests
public void InsertPost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Builder, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ValidationException>());
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Builder, 10)), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Never);
}
@@ -268,9 +253,9 @@ internal class PostBusinessLogicContractTests
public void InsertPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<StorageException>());
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, 10)), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
}
@@ -279,12 +264,11 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, new PostConfiguration() { Rate = 10 });
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>()))
.Callback((PostDataModel x) =>
{
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.ConfigurationModel.Rate == record.ConfigurationModel.Rate;
});
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 10);
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Callback((PostDataModel x) =>
{
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary;
});
//Act
_postBusinessLogicContract.UpdatePost(record);
//Assert
@@ -296,9 +280,9 @@ internal class PostBusinessLogicContractTests
public void UpdatePost_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementNotFoundException(""));
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementNotFoundException>());
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, 10)), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
@@ -306,9 +290,9 @@ internal class PostBusinessLogicContractTests
public void UpdatePost_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.Builder, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementExistsException>());
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.Builder, 10)), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
@@ -324,7 +308,7 @@ internal class PostBusinessLogicContractTests
public void UpdatePost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Builder, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ValidationException>());
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Builder, 10)), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Never);
}
@@ -332,9 +316,9 @@ internal class PostBusinessLogicContractTests
public void UpdatePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<StorageException>());
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, 10)), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
@@ -357,7 +341,7 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
_postStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
@@ -372,24 +356,6 @@ internal class PostBusinessLogicContractTests
_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()
{
@@ -409,7 +375,7 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
_postStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);
@@ -436,7 +402,7 @@ internal class PostBusinessLogicContractTests
public void RestorePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);

View File

@@ -0,0 +1,334 @@
using FurnitureAssemblyBusinessLogic.Implementations;
using FurnitureAssemblyBusinessLogic.OfficePackage;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyTests.Infrastructure;
using Microsoft.Extensions.Logging;
using Moq;
namespace FurnitureAssemblyTests.BusinessLogicContractsTests;
[TestFixture]
internal class ReportContractTests
{
private ReportContract _reportContract;
private Mock<IComponentStorageContract> _componentStorageContract;
private Mock<IManifacturingStorageContract> _manifactiringStorageContract;
private Mock<ISalaryStorageContract> _salaryStorageContract;
private Mock<BaseWordBuilder> _baseWordBuilder;
private Mock<BaseExcelBuilder> _baseExcelBuilder;
private Mock<BasePdfBuilder> _basePdfBuilder;
[OneTimeSetUp]
public void Setup()
{
_componentStorageContract = new Mock<IComponentStorageContract>();
_manifactiringStorageContract = new Mock<IManifacturingStorageContract>();
_salaryStorageContract = new Mock<ISalaryStorageContract>();
_baseWordBuilder = new Mock<BaseWordBuilder>();
_baseExcelBuilder = new Mock<BaseExcelBuilder>();
_basePdfBuilder = new Mock<BasePdfBuilder>();
_reportContract = new ReportContract(
_componentStorageContract.Object,
_manifactiringStorageContract.Object,
_salaryStorageContract.Object,
_baseWordBuilder.Object,
_baseExcelBuilder.Object,
_basePdfBuilder.Object,
Mock.Of<ILogger>(),
StringLocalizerMockCreator.GetStringLocalizerMockObject());
}
[SetUp]
public void SetUp()
{
_componentStorageContract.Reset();
_manifactiringStorageContract.Reset();
_salaryStorageContract.Reset();
}
[Test]
public async Task GetDataComponentsHistoryAsync_ReturnsCorrectData()
{
// Arrange
var components = new List<ComponentDataModel>
{
new("1", "Component1", ComponentType.Handle, "OldName1", "VeryOldName1"),
new("2", "Component2", ComponentType.Panel, null, null),
new("3", "Component3", ComponentType.Legs, "OldName3", null)
};
_componentStorageContract.Setup(x => x.GetListAsync(It.IsAny<CancellationToken>())).ReturnsAsync(components);
// Act
var data = await _reportContract.GetDataComponentsHistoryAsync(CancellationToken.None);
// Assert
Assert.That(data, Is.Not.Null);
Assert.That(data.Count, Is.EqualTo(3));
var first = data[0];
Assert.That(first.CurrentName, Is.EqualTo("Component1"));
Assert.That(first.HistoryNames, Is.EquivalentTo(new[] { "OldName1", "VeryOldName1" }));
var second = data[1];
Assert.That(second.CurrentName, Is.EqualTo("Component2"));
Assert.That(second.HistoryNames, Is.Empty);
var third = data[2];
Assert.That(third.CurrentName, Is.EqualTo("Component3"));
Assert.That(third.HistoryNames, Is.EquivalentTo(new[] { "OldName3" }));
}
[Test]
public async Task GetDataProductsByManufacturer_WhenNoRecords_ShouldSuccess_Test()
{
//Arrange
_componentStorageContract.Setup(x => x.GetListAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult(new List<ComponentDataModel>()));
//Act
var data = await
_reportContract.GetDataComponentsHistoryAsync(CancellationToken.None);
//Assert
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(0));
_componentStorageContract.Verify(x => x.GetListAsync(It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public async Task CreateDocumentProductsByManufacturer_ShouldeSuccess_Test()
{
// Arrange
var components = new List<ComponentDataModel>
{
new("1", "Component1", ComponentType.Panel, "OldName1", null)
};
_componentStorageContract.Setup(x => x.GetListAsync(It.IsAny<CancellationToken>())).ReturnsAsync(components);
_baseWordBuilder.Setup(x => x.AddHeader(It.IsAny<string>())).Returns(_baseWordBuilder.Object);
_baseWordBuilder.Setup(x => x.AddParagraph(It.IsAny<string>())).Returns(_baseWordBuilder.Object);
_baseWordBuilder.Setup(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>())).Returns(_baseWordBuilder.Object);
_baseWordBuilder.Setup(x => x.Build()).Returns(new MemoryStream());
// Act
var result = await _reportContract.CreateDocumentComponentsHistoryAsync(CancellationToken.None);
// Assert
Assert.That(result, Is.Not.Null);
_baseWordBuilder.Verify(x => x.AddHeader(It.IsAny<string>()), Times.Once);
_baseWordBuilder.Verify(x => x.AddTable(
It.Is<int[]>(w => w.SequenceEqual(new[] { 100, 100 })),
It.Is<List<string[]>>(d =>
d.Count == 3 &&
d[1].SequenceEqual(new[] { "Component1", "" }) &&
d[2].SequenceEqual(new[] { "", "OldName1" }))),
Times.Once);
}
[Test]
public async Task GetDataManifacturingsByPeriod_ShouldSuccess_Test()
{
//Arrange
var furniture = new FurnitureDataModel(Guid.NewGuid().ToString(), "test", 5, []);
_manifactiringStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(new List<ManifacturingFurnitureDataModel>()
{
new(Guid.NewGuid().ToString(), furniture.Id, 5, null),
new(Guid.NewGuid().ToString(), furniture.Id, 5, null)
}));
//Act
var data = await _reportContract.GetDataManifacturingByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None);
//Assert
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(2));
_manifactiringStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public async Task GetDataManifacturingsByPeriod_WhenNoRecords_ShouldSuccess_Test()
{
//Arrange
_manifactiringStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(new List<ManifacturingFurnitureDataModel>()));
//Act
var data = await _reportContract.GetDataManifacturingByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None);
//Assert
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(0));
_manifactiringStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public void GetDataManifacturingsByPeriod_WhenIncorrectDates_ShouldFail_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(async () => await _reportContract.GetDataManifacturingByPeriodAsync(date, date, CancellationToken.None), Throws.TypeOf<IncorrectDatesException>());
Assert.That(async () => await _reportContract.GetDataManifacturingByPeriodAsync(date, DateTime.UtcNow.AddDays(-1), CancellationToken.None), Throws.TypeOf<IncorrectDatesException>());
}
[Test]
public void GetDataByManifacturingsByPeriod_WhenStorageThrowError_ShouldFail_Test()
{
//Arrange
_manifactiringStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(async () => await _reportContract.GetDataManifacturingByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None), Throws.TypeOf<StorageException>());
_manifactiringStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public async Task CreateDocumentSalesByPeriod_ShouldeSuccess_Test()
{
// Arrange
var furniture = new FurnitureDataModel(Guid.NewGuid().ToString(), "test", 5, []);
var manufacturings = new List<ManifacturingFurnitureDataModel>
{
new(Guid.NewGuid().ToString(), furniture.Id, 5, null),
new(Guid.NewGuid().ToString(), furniture.Id, 5, null),
new(Guid.NewGuid().ToString(), furniture.Id, 5, null)
};
_manifactiringStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>())).ReturnsAsync(manufacturings);
_baseExcelBuilder.Setup(x => x.AddHeader(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>())).Returns(_baseExcelBuilder.Object);
_baseExcelBuilder.Setup(x => x.AddParagraph(It.IsAny<string>(), It.IsAny<int>())).Returns(_baseExcelBuilder.Object);
_baseExcelBuilder.Setup(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>())).Returns(_baseExcelBuilder.Object);
_baseExcelBuilder.Setup(x => x.Build()).Returns(new MemoryStream());
var countRows = 0;
string[] firstRow = [];
string[] secondRow = [];
_baseExcelBuilder.Setup(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>()))
.Callback((int[] widths, List<string[]> data) =>
{
countRows = data.Count;
firstRow = data[0];
secondRow = data[1];
}).Returns(_baseExcelBuilder.Object);
// Act
var data = await _reportContract.CreateDocumentSalesByPeriodAsync(DateTime.Now.AddDays(-1), DateTime.Now, CancellationToken.None);
//Assert
Assert.Multiple(() =>
{
Assert.That(countRows, Is.EqualTo(5));
Assert.That(firstRow, Is.Not.EqualTo(default));
Assert.That(secondRow, Is.Not.EqualTo(default));
});
Assert.That(data, Is.Not.Null);
_manifactiringStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
_baseExcelBuilder.Verify(x => x.AddHeader(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()), Times.Once);
_baseExcelBuilder.Verify(x => x.AddParagraph(It.IsAny<string>(), It.IsAny<int>()), Times.Once);
_baseExcelBuilder.Verify(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>()), Times.Once);
_baseExcelBuilder.Verify(x => x.Build(), Times.Once);
}
[Test]
public async Task GetDataSalaryByPeriod_ShouldSuccess_Test()
{
//Arrange
var startDate = DateTime.UtcNow.AddDays(-20);
var endDate = DateTime.UtcNow.AddDays(5);
var worker1 = new WorkerDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-20), DateTime.UtcNow.AddDays(-3), false, new PostConfiguration());
var worker2 = new WorkerDataModel(Guid.NewGuid().ToString(), "Ванов И.И.", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-20), DateTime.UtcNow.AddDays(-3), false, new PostConfiguration());
_salaryStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(new List<SalaryDataModel>()
{
new(worker1.Id, DateTime.UtcNow.AddDays(-10), 100, worker1),
new(worker1.Id, endDate, 1000, worker1),
new(worker1.Id, startDate, 1000, worker1),
new(worker2.Id, DateTime.UtcNow.AddDays(-10), 100, worker2),
new(worker2.Id, DateTime.UtcNow.AddDays(-5), 200, worker2)
}));
//Act
var data = await _reportContract.GetDataSalaryByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None);
//Assert
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(2));
var worker1Salary = data.First(x => x.WorkerFIO == worker1.FIO);
Assert.That(worker1Salary, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(worker1Salary.TotalSalary, Is.EqualTo(2100));
Assert.That(worker1Salary.FromPeriod, Is.EqualTo(startDate));
Assert.That(worker1Salary.ToPeriod, Is.EqualTo(endDate));
});
var worker2Salary = data.First(x => x.WorkerFIO == worker2.FIO);
Assert.That(worker2Salary, Is.Not.Null);
Assert.That(worker2Salary.TotalSalary, Is.EqualTo(300));
_salaryStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public async Task GetDataSalaryByPeriod_WhenNoRecords_ShouldSuccess_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(new List<SalaryDataModel>()));
//Act
var data = await _reportContract.GetDataSalaryByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None);
//Assert
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(0));
_salaryStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public void GetDataSalaryByPeriod_WhenIncorrectDates_ShouldFail_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(async () => await _reportContract.GetDataSalaryByPeriodAsync(date, date, CancellationToken.None), Throws.TypeOf<IncorrectDatesException>());
Assert.That(async () => await _reportContract.GetDataSalaryByPeriodAsync(date, DateTime.UtcNow.AddDays(-1), CancellationToken.None), Throws.TypeOf<IncorrectDatesException>());
}
[Test]
public void GetDataSalaryByPeriod_WhenStorageThrowError_ShouldFail_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(async () => await _reportContract.GetDataSalaryByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None), Throws.TypeOf<StorageException>());
_salaryStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public async Task CreateDocumentSalaryByPeriod_ShouldeSuccess_Test()
{
//Arrange
var startDate = DateTime.UtcNow.AddDays(-20);
var endDate = DateTime.UtcNow.AddDays(5);
var worker1 = new WorkerDataModel(Guid.NewGuid().ToString(), "Ванов И.И.", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-20), DateTime.UtcNow.AddDays(-3), false, new PostConfiguration());
var worker2 = new WorkerDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-20), DateTime.UtcNow.AddDays(-3), false, new PostConfiguration());
_salaryStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(new List<SalaryDataModel>()
{
new(worker1.Id, DateTime.UtcNow.AddDays(-10), 100, worker1),
new(worker1.Id, endDate, 1000, worker1),
new(worker1.Id, startDate, 1000, worker1),
new(worker2.Id, DateTime.UtcNow.AddDays(-10), 100, worker2),
new(worker2.Id, DateTime.UtcNow.AddDays(-5), 200, worker2)
}));
_basePdfBuilder.Setup(x => x.AddHeader(It.IsAny<string>())).Returns(_basePdfBuilder.Object);
_basePdfBuilder.Setup(x => x.AddParagraph(It.IsAny<string>())).Returns(_basePdfBuilder.Object);
var countRows = 0;
(string, double) firstRow = default;
(string, double) secondRow = default;
_basePdfBuilder.Setup(x => x.AddPieChart(It.IsAny<string>(), It.IsAny<List<(string, double)>>()))
.Callback((string header, List<(string, double)> data) =>
{
countRows = data.Count;
firstRow = data[0];
secondRow = data[1];
})
.Returns(_basePdfBuilder.Object);
//Act
var data = await _reportContract.CreateDocumentSalaryByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None);
//Assert
Assert.Multiple(() =>
{
Assert.That(countRows, Is.EqualTo(2));
Assert.That(firstRow, Is.Not.EqualTo(default));
Assert.That(secondRow, Is.Not.EqualTo(default));
});
Assert.Multiple(() =>
{
Assert.That(firstRow.Item1, Is.EqualTo(worker1.FIO));
Assert.That(firstRow.Item2, Is.EqualTo(2100));
Assert.That(secondRow.Item1, Is.EqualTo(worker2.FIO));
Assert.That(secondRow.Item2, Is.EqualTo(300));
});
_salaryStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
_basePdfBuilder.Verify(x => x.AddHeader(It.IsAny<string>()), Times.Once);
_basePdfBuilder.Verify(x => x.AddParagraph(It.IsAny<string>()), Times.Once);
_basePdfBuilder.Verify(x => x.AddPieChart(It.IsAny<string>(), It.IsAny<List<(string, double)>>()), Times.Once);
_basePdfBuilder.Verify(x => x.Build(), Times.Once);
}
}

View File

@@ -1,6 +1,5 @@
using FurnitureAssemblyBusinessLogic.Implementations;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
using FurnitureAssemblyContracts.StoragesContracts;
@@ -15,7 +14,6 @@ internal class SalaryBuisnessLogicContractTests
private SalaryBusinessLogicContract _salaryBusinessLogicContract;
private Mock<ISalaryStorageContract> _salaryStorageContract;
private Mock<IManifacturingStorageContract> _manifacturingStorageContract;
private Mock<IPostStorageContract> _postStorageContract;
private Mock<IWorkerStorageContract> _workerStorageContract;
private readonly ConfigurationSalaryTest _salaryConfigurationTest = new();
@@ -24,10 +22,9 @@ internal class SalaryBuisnessLogicContractTests
{
_salaryStorageContract = new Mock<ISalaryStorageContract>();
_manifacturingStorageContract = new Mock<IManifacturingStorageContract>();
_postStorageContract = new Mock<IPostStorageContract>();
_workerStorageContract = new Mock<IWorkerStorageContract>();
_salaryBusinessLogicContract = new SalaryBusinessLogicContract(_salaryStorageContract.Object,
_manifacturingStorageContract.Object, _postStorageContract.Object, _workerStorageContract.Object, new Mock<ILogger>().Object, _salaryConfigurationTest);
_manifacturingStorageContract.Object, _workerStorageContract.Object, StringLocalizerMockCreator.GetStringLocalizerMockObject(), new Mock<ILogger>().Object, _salaryConfigurationTest);
}
[TearDown]
@@ -35,7 +32,6 @@ internal class SalaryBuisnessLogicContractTests
{
_salaryStorageContract.Reset();
_manifacturingStorageContract.Reset();
_postStorageContract.Reset();
_workerStorageContract.Reset();
}
@@ -84,19 +80,11 @@ internal class SalaryBuisnessLogicContractTests
_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()));
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//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);
@@ -165,19 +153,11 @@ internal class SalaryBuisnessLogicContractTests
_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()));
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//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);
@@ -186,17 +166,14 @@ internal class SalaryBuisnessLogicContractTests
[Test]
public void CalculateSalaryByMounth_CalculateSalary_Test()
{
////Arrange
//Arrange
var workerId = Guid.NewGuid().ToString();
var saleSum = 200;
var postSalary = 2000;
var rate = 2000.0;
var rate = 10.0;
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), saleSum, workerId)]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, new PostConfiguration() { Rate = rate }));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false, new PostConfiguration() { Rate = rate })]);
var sum = 0.0;
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
.Callback((SalaryDataModel x) =>
@@ -217,9 +194,9 @@ internal class SalaryBuisnessLogicContractTests
var worker2Id = Guid.NewGuid().ToString();
var worker3Id = Guid.NewGuid().ToString();
var list = new List<WorkerDataModel>() {
new(worker1Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
new(worker2Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
new(worker3Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)
new(worker1Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false, new PostConfiguration() { Rate = 10 }),
new(worker2Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false, new PostConfiguration() { Rate = 10 }),
new(worker3Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false, new PostConfiguration() { Rate = 10 })
};
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, worker1Id),
@@ -227,8 +204,6 @@ internal class SalaryBuisnessLogicContractTests
new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, worker2Id),
new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, worker3Id),
new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, worker3Id)]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, new PostConfiguration() { Rate = 100 }));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns(list);
//Act
@@ -241,15 +216,14 @@ internal class SalaryBuisnessLogicContractTests
public void CalculateSalaryByMounth_WithoitSalesByWorker_Test()
{
//Arrange
var rate = 2000.0;
var postSalary = 10;
var workerId = Guid.NewGuid().ToString();
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, new PostConfiguration() { Rate = rate }));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false, new PostConfiguration() { Rate = 10 })]);
var sum = 0.0;
var expectedSum = postSalary;
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
.Callback((SalaryDataModel x) =>
{
@@ -258,46 +232,7 @@ internal class SalaryBuisnessLogicContractTests
//Act
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
//Assert
Assert.That(sum, Is.EqualTo(rate));
}
[Test]
public void CalculateSalaryByMounth_SaleStorageReturnNull_ThrowException_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, new PostConfiguration() { Rate = 100 }));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
[Test]
public void CalculateSalaryByMounth_PostStorageReturnNull_ThrowException_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, workerId)]);
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
[Test]
public void CalculateSalaryByMounth_WorkerStorageReturnNull_ThrowException_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, workerId)]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, new PostConfiguration() { Rate = 100 }));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
Assert.That(sum, Is.EqualTo(expectedSum));
}
[Test]
@@ -306,26 +241,9 @@ internal class SalaryBuisnessLogicContractTests
//Arrange
var workerId = Guid.NewGuid().ToString();
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, new PostConfiguration() { Rate = 100 }));
.Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
}
[Test]
public void CalculateSalaryByMounth_PostStorageThrowException_ThrowException_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, workerId)]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false, new PostConfiguration() { Rate = 10 })]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
}
@@ -337,10 +255,8 @@ internal class SalaryBuisnessLogicContractTests
var workerId = Guid.NewGuid().ToString();
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, workerId)]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, new PostConfiguration() { Rate = 100 }));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Throws(new StorageException(new InvalidOperationException()));
.Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
}
@@ -361,10 +277,8 @@ internal class SalaryBuisnessLogicContractTests
};
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns(sales);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, new BuilderPostConfiguration() { Rate = rate, PersonalCount = bonus }));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false, new BuilderPostConfiguration() { Rate = rate, PersonalCount = bonus })]);
var sum = 0.0;
var expectedSum = rate + (sales.Sum(x => x.Count) / sales.Count) + sales.Where(x => x.Count > _salaryConfigurationTest.ExtraMadeSum).Sum(x => x.Count) * bonus;
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
@@ -388,10 +302,8 @@ internal class SalaryBuisnessLogicContractTests
var bonus = 100;
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, workerId)]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chief, new ChiefPostConfiguration() { Rate = rate, PersonalCountTrendPremium = bonus }));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false, new ChiefPostConfiguration() { Rate = rate, PersonalCountTrendPremium = bonus })]);
_workerStorageContract.Setup(x => x.GetWorkerTrend(It.IsAny<DateTime>(), It.IsAny<DateTime>()))
.Returns(trend);
var sum = 0.0;

View File

@@ -1,7 +1,9 @@
using FurnitureAssemblyBusinessLogic.Implementations;
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyTests.Infrastructure;
using Microsoft.Extensions.Logging;
using Moq;
@@ -16,7 +18,7 @@ internal class WorkerBusinessLogicContractTests
public void OneTimeSetUp()
{
_workerStorageContract = new Mock<IWorkerStorageContract>();
_workerBusinessLogicContract = new WorkerBusinessLogicContract(_workerStorageContract.Object, new Mock<ILogger>().Object);
_workerBusinessLogicContract = new WorkerBusinessLogicContract(_workerStorageContract.Object, StringLocalizerMockCreator.GetStringLocalizerMockObject(), new Mock<ILogger>().Object);
}
[TearDown]
@@ -31,9 +33,9 @@ internal class WorkerBusinessLogicContractTests
//Arrange
var listOriginal = new List<WorkerDataModel>()
{
new(Guid.NewGuid().ToString(), "Иванов И.И.1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "Иванов И.И.2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "Иванов И.И.3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "Иванов И.И.1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 }),
new(Guid.NewGuid().ToString(), "Иванов И.И.2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true, new PostConfiguration() { Rate = 10 }),
new(Guid.NewGuid().ToString(), "Иванов И.И.3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 }),
};
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
@@ -70,19 +72,11 @@ internal class WorkerBusinessLogicContractTests
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), null, null, null, null, null), Times.Exactly(2));
}
[Test]
public void GetAllWorkers_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkers(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkers_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkers(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), null, null, null, null, null), Times.Once);
@@ -95,9 +89,9 @@ internal class WorkerBusinessLogicContractTests
var postId = Guid.NewGuid().ToString();
var listOriginal = new List<WorkerDataModel>()
{
new(Guid.NewGuid().ToString(), "Иванов И.И.1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "Иванов И.И.2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "Иванов И.И.3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "Иванов И.И.1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 }),
new(Guid.NewGuid().ToString(), "Иванов И.И.2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true, new PostConfiguration() { Rate = 10 }),
new(Guid.NewGuid().ToString(), "Иванов И.И.3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 }),
};
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
@@ -151,19 +145,11 @@ internal class WorkerBusinessLogicContractTests
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllWorkersByPost_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByPost(Guid.NewGuid().ToString(), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkersByPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByPost(Guid.NewGuid().ToString(), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
@@ -176,9 +162,9 @@ internal class WorkerBusinessLogicContractTests
var date = DateTime.UtcNow;
var listOriginal = new List<WorkerDataModel>()
{
new(Guid.NewGuid().ToString(), "Иванов И.И.1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "Иванов И.И.2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "Иванов И.И.3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "Иванов И.И.1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 }),
new(Guid.NewGuid().ToString(), "Иванов И.И.2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true, new PostConfiguration() { Rate = 10 }),
new(Guid.NewGuid().ToString(), "Иванов И.И.3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 }),
};
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
@@ -227,19 +213,11 @@ internal class WorkerBusinessLogicContractTests
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllWorkersByBirthDate_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByBirthDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkersByBirthDate_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByBirthDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
@@ -252,9 +230,9 @@ internal class WorkerBusinessLogicContractTests
var date = DateTime.UtcNow;
var listOriginal = new List<WorkerDataModel>()
{
new(Guid.NewGuid().ToString(), "Иванов И.И.1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "Иванов И.И.2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "Иванов И.И.3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "Иванов И.И.1", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 }),
new(Guid.NewGuid().ToString(), "Иванов И.И.2", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, true, new PostConfiguration() { Rate = 10 }),
new(Guid.NewGuid().ToString(), "Иванов И.И.3", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 }),
};
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
@@ -303,19 +281,11 @@ internal class WorkerBusinessLogicContractTests
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllWorkersByEmploymentDate_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllWorkersByEmploymentDate_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
@@ -326,7 +296,7 @@ internal class WorkerBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new WorkerDataModel(id, "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false);
var record = new WorkerDataModel(id, "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 });
_workerStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _workerBusinessLogicContract.GetWorkerByData(id);
@@ -341,7 +311,7 @@ internal class WorkerBusinessLogicContractTests
{
//Arrange
var fio = "Иванов И.И.";
var record = new WorkerDataModel(Guid.NewGuid().ToString(), fio, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false);
var record = new WorkerDataModel(Guid.NewGuid().ToString(), fio, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 });
_workerStorageContract.Setup(x => x.GetElementByFIO(fio)).Returns(record);
//Act
var element = _workerBusinessLogicContract.GetWorkerByData(fio);
@@ -383,8 +353,8 @@ internal class WorkerBusinessLogicContractTests
public void GetWorkerByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.GetElementByFIO(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
_workerStorageContract.Setup(x => x.GetElementByFIO(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData("Иванов И.И."), Throws.TypeOf<StorageException>());
@@ -397,7 +367,7 @@ internal class WorkerBusinessLogicContractTests
{
//Arrange
var flag = false;
var record = new WorkerDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false);
var record = new WorkerDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 1 });
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>()))
.Callback((WorkerDataModel x) =>
{
@@ -415,9 +385,9 @@ internal class WorkerBusinessLogicContractTests
public void InsertWorker_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>())).Throws(new ElementExistsException("Data", "Data"));
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-14).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementExistsException>());
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-14).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementExistsException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Once);
}
@@ -433,7 +403,7 @@ internal class WorkerBusinessLogicContractTests
public void InsertWorker_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new WorkerDataModel("id", "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ValidationException>());
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new WorkerDataModel("id", "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ValidationException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Never);
}
@@ -441,9 +411,9 @@ internal class WorkerBusinessLogicContractTests
public void InsertWorker_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.AddElement(It.IsAny<WorkerDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>());
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Once);
}
@@ -452,7 +422,7 @@ internal class WorkerBusinessLogicContractTests
{
//Arrange
var flag = false;
var record = new WorkerDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false);
var record = new WorkerDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 });
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>()))
.Callback((WorkerDataModel x) =>
{
@@ -470,9 +440,9 @@ internal class WorkerBusinessLogicContractTests
public void UpdateWorker_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>())).Throws(new ElementNotFoundException(""));
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementNotFoundException>());
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Once);
}
@@ -488,7 +458,7 @@ internal class WorkerBusinessLogicContractTests
public void UpdateWorker_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new WorkerDataModel("id", "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ValidationException>());
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new WorkerDataModel("id", "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ValidationException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Never);
}
@@ -496,9 +466,9 @@ internal class WorkerBusinessLogicContractTests
public void UpdateWorker_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>());
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(-1), DateTime.Now, false, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Once);
}
@@ -521,7 +491,7 @@ internal class WorkerBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
_workerStorageContract.Setup(x => x.DelElement(It.Is((string x) => x != id))).Throws(new ElementNotFoundException(id));
_workerStorageContract.Setup(x => x.DelElement(It.Is((string x) => x != id))).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.DeleteWorker(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
@@ -548,7 +518,7 @@ internal class WorkerBusinessLogicContractTests
public void DeleteWorker_StorageThrowError_ThrowException_Test()
{
//Arrange
_workerStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_workerStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetStringLocalizerMockObject()));
//Act&Assert
Assert.That(() => _workerBusinessLogicContract.DeleteWorker(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);

View File

@@ -1,6 +1,7 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyTests.Infrastructure;
namespace FurnitureAssemblyTests.DataModelsTests;
@@ -11,9 +12,9 @@ internal class ComponentDataModelTests
public void IdIsNullOrEmptyTest()
{
var component = CreateDataModel(null, "name", ComponentType.Box);
Assert.That(() => component.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => component.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
component = CreateDataModel(string.Empty, "name", ComponentType.Box);
Assert.That(() => component.Validate(),
Assert.That(() => component.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()),
Throws.TypeOf<ValidationException>());
}
@@ -21,23 +22,23 @@ internal class ComponentDataModelTests
public void IdIsNotGuidTest()
{
var component = CreateDataModel("id", "name", ComponentType.Box);
Assert.That(() => component.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => component.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void NameIsNullOrEmptyTest()
{
var component = CreateDataModel(Guid.NewGuid().ToString(), null, ComponentType.Box);
Assert.That(() => component.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => component.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
component = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, ComponentType.Box);
Assert.That(() => component.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => component.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostTypeIsNoneTest()
{
var component = CreateDataModel(Guid.NewGuid().ToString(), "name", ComponentType.None);
Assert.That(() => component.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => component.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -47,7 +48,7 @@ internal class ComponentDataModelTests
var name = "name";
var componentType = ComponentType.Box;
var component = CreateDataModel(componentId, name, componentType);
Assert.That(() => component.Validate(), Throws.Nothing);
Assert.That(() => component.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(component.Id, Is.EqualTo(componentId));

View File

@@ -1,5 +1,6 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyTests.Infrastructure;
namespace FurnitureAssemblyTests.DataModelsTests;
@@ -10,43 +11,43 @@ internal class FurnitureComponentDataModelTests
public void FurnitureIdIsNullOrEmptyTest()
{
var model = CreateDataModel(null, Guid.NewGuid().ToString(), 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
model = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void FurnitureIdIsNotGuidTest()
{
var model = CreateDataModel("id", Guid.NewGuid().ToString(), 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void ComponentIdIsNullOrEmptyTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), null, 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void ComponentIdIsNotGuidTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), "id", 1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void CountIsLessOrZeroTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -56,7 +57,7 @@ internal class FurnitureComponentDataModelTests
var componentId = Guid.NewGuid().ToString();
var count = 1;
var model = CreateDataModel(furnitureId, componentId, count);
Assert.That(() => model.Validate(), Throws.Nothing);
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(model.FurnitureId, Is.EqualTo(furnitureId));

View File

@@ -1,6 +1,7 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyTests.Infrastructure;
namespace FurnitureAssemblyTests.DataModelsTests;
@@ -11,47 +12,47 @@ internal class FurnitureDataModelTests
public void IdIsNullOrEmptyTest()
{
var model = CreateDataModel(null, "name", 1, CreateSubDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
model = CreateDataModel(string.Empty, "name", 1, CreateSubDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var model = CreateDataModel("id", "name", 1, CreateSubDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void NameIsNullOrEmptyTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), null, 1, CreateSubDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, 1, CreateSubDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void WeightIsLessOrZeroTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), "name", 0, CreateSubDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), "name", -1, CreateSubDataModel());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void ComponentsIsEmptyOrNullTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), "name", 1, []);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), "name", 1, null);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -62,7 +63,7 @@ internal class FurnitureDataModelTests
var weight = 1;
var components = CreateSubDataModel();
var model = CreateDataModel(id, name, weight, components);
Assert.DoesNotThrow(() => model.Validate());
Assert.DoesNotThrow(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()));
Assert.Multiple(() =>
{

View File

@@ -1,5 +1,6 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyTests.Infrastructure;
namespace FurnitureAssemblyTests.DataModelsTests;
@@ -10,60 +11,60 @@ internal class ManifacturingFurnitureDataModelTests
public void IdIsNullOrEmptyTest()
{
var model = CreateDataModel(null, Guid.NewGuid().ToString(), 1, Guid.NewGuid().ToString());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
model = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 1, Guid.NewGuid().ToString());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var model = CreateDataModel("id", Guid.NewGuid().ToString(), 1, Guid.NewGuid().ToString());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void ManifacureIdIsNullOrEmptyTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), null, 1, Guid.NewGuid().ToString());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, 1, Guid.NewGuid().ToString());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void ManifactureIdIsNotGuidTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), "furid", 1, Guid.NewGuid().ToString());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void CountIsLessOrZeroTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0, Guid.NewGuid().ToString());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -1, Guid.NewGuid().ToString());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void WorkerIdIsNullOrEmptyTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, null);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, string.Empty);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void WorkerIdIsNotGuidTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, "id");
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -74,7 +75,7 @@ internal class ManifacturingFurnitureDataModelTests
var count = 1;
var workerId = Guid.NewGuid().ToString();
var model = CreateDataModel(id, manid, count, workerId);
Assert.That(() => model.Validate(), Throws.Nothing);
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(model.Id, Is.EqualTo(id));

View File

@@ -1,7 +1,7 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
using FurnitureAssemblyTests.Infrastructure;
namespace FurnitureAssemblyTests.DataModelsTests;
@@ -11,71 +11,67 @@ internal class PostDataModelTests
[Test]
public void IdIsNullOrEmptyTest()
{
var post = CreateDataModel(null, "name", PostType.Builder, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(string.Empty, "name", PostType.Builder, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
var model = CreateDataModel(null, "name", PostType.Builder, 100);
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
model = CreateDataModel(string.Empty, "name", PostType.Builder, 100);
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var post = CreateDataModel("id", "name", PostType.Builder, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
var model = CreateDataModel("id", "name", PostType.Builder, 100);
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostNameIsEmptyTest()
public void PostNameIsNullOrEmptyTest()
{
var manufacturer = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Builder, new PostConfiguration() { Rate = 10 });
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
manufacturer = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Builder, new PostConfiguration() { Rate = 10 });
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
var model = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Builder, 100);
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Builder, 100);
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostTypeIsNoneTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.None, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
var model = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.None, 100);
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void ConfigurationModelIsNullTest()
public void SalaryIsZeroNegativeTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, null);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void RateIsLessOrZeroTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, new PostConfiguration() { Rate = 0 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, new PostConfiguration() { Rate = -10 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
var model = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 0);
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, -1);
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
public void AllFieldsIsCorrectTest()
{
var postId = Guid.NewGuid().ToString();
var id = Guid.NewGuid().ToString();
var postName = "name";
var postType = PostType.Builder;
var configuration = new PostConfiguration() { Rate = 10 };
var post = CreateDataModel(postId, postName, postType, configuration);
Assert.That(() => post.Validate(), Throws.Nothing);
var salary = 100.50;
var isActual = true;
var changeDate = DateTime.Now;
var model = CreateDataModel(id, postName, postType, salary);
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(post.Id, Is.EqualTo(postId));
Assert.That(post.PostName, Is.EqualTo(postName));
Assert.That(post.PostType, Is.EqualTo(postType));
Assert.That(post.ConfigurationModel, Is.EqualTo(configuration));
Assert.That(post.ConfigurationModel.Rate, Is.EqualTo(configuration.Rate));
Assert.That(model.Id, Is.EqualTo(id));
Assert.That(model.PostName, Is.EqualTo(postName));
Assert.That(model.PostType, Is.EqualTo(postType));
Assert.That(model.Salary, Is.EqualTo(salary));
});
}
private static PostDataModel CreateDataModel(string? id, string? postName, PostType postType, PostConfiguration configuration) =>
new(id, postName, postType, configuration);
private static PostDataModel CreateDataModel(string? id, string? postName, PostType postType, double salary)
=> new(id, postName, postType, salary);
}

View File

@@ -1,5 +1,6 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyTests.Infrastructure;
namespace FurnitureAssemblyTests.DataModelsTests;
@@ -10,26 +11,26 @@ internal class SalaryDataModelTests
public void WorkerIdIsNullOrEmptyTest()
{
var model = CreateDataModel(null, DateTime.Now, 100);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
model = CreateDataModel(string.Empty, DateTime.Now, 100);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void WorkerIdIsNotGuidTest()
{
var model = CreateDataModel("id", DateTime.Now, 100);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void SalaryIsZeroNegativeTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now, -1);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -39,11 +40,11 @@ internal class SalaryDataModelTests
var salaryDate = DateTime.Now;
var salary = 100.50;
var model = CreateDataModel(workerId, salaryDate, salary);
Assert.That(() => model.Validate(), Throws.Nothing);
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(model.WorkerId, Is.EqualTo(workerId));
Assert.That(model.SalaryDate, Is.EqualTo(salaryDate));
Assert.That(model.SalaryDate, Is.EqualTo(salaryDate.ToUniversalTime()));
Assert.That(model.Salary, Is.EqualTo(salary));
});
}

View File

@@ -1,5 +1,8 @@
using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
using FurnitureAssemblyDatebase.Models;
using FurnitureAssemblyTests.Infrastructure;
namespace FurnitureAssemblyTests.DataModelsTests;
@@ -9,68 +12,68 @@ internal class WorkerDataModelTests
[Test]
public void IdIsNullOrEmptyTest()
{
var model = CreateDataModel(null, "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now, false);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
var model = CreateDataModel(null, "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now, false, new PostConfiguration() { Rate = 0 });
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
model = CreateDataModel(string.Empty, "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now, false);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(string.Empty, "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now, false, new PostConfiguration() { Rate = 0 });
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var model = CreateDataModel("not a guid", "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now, false);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
var model = CreateDataModel("not a guid", "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now, false, new PostConfiguration() { Rate = 0 });
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void FioIsNullOrEmptyTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), null, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now, false);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
var model = CreateDataModel(Guid.NewGuid().ToString(), null, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now, false, new PostConfiguration() { Rate = 0 });
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now, false);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now, false, new PostConfiguration() { Rate = 0 });
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void FioIsNotCorrectTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now, false);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
var model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now, false, new PostConfiguration() { Rate = 0 });
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostIdIsNullOrEmptyTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", null, DateTime.Now.AddYears(-20), DateTime.Now, false);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
var model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", null, DateTime.Now.AddYears(-20), DateTime.Now, false, new PostConfiguration() { Rate = 0 });
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", string.Empty, DateTime.Now.AddYears(-20), DateTime.Now, false);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", string.Empty, DateTime.Now.AddYears(-20), DateTime.Now, false, new PostConfiguration() { Rate = 0 });
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostIdIsNotGuidTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", "not a guid", DateTime.Now.AddYears(-20), DateTime.Now, false);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
var model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", "not a guid", DateTime.Now.AddYears(-20), DateTime.Now, false, new PostConfiguration() { Rate = 0 });
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void BirthDateIsFutureTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-14).AddDays(1), DateTime.Now, false);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
var model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-14).AddDays(1), DateTime.Now, false, new PostConfiguration() { Rate = 0 });
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
public void BirthDateAndEmploymentDateIsNotCorrectTest()
{
var model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now.AddYears(-20).AddDays(-1), false);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now.AddYears(-16), false);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
var model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now.AddYears(-20).AddDays(-1), false, new PostConfiguration() { Rate = 0 });
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-20), DateTime.Now.AddYears(-16), false, new PostConfiguration() { Rate = 0 });
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -82,19 +85,23 @@ internal class WorkerDataModelTests
var birthDate = DateTime.Now.AddYears(-20);
var employmentDate = DateTime.Now;
var isDeleted = false;
var model = CreateDataModel(id, fio, postId, birthDate, employmentDate, isDeleted);
Assert.That(() => model.Validate(), Throws.Nothing);
var configuration = new PostConfiguration() { Rate = 10 };
var model = CreateDataModel(id, fio, postId, birthDate, employmentDate, isDeleted, configuration);
Assert.That(() => model.Validate(StringLocalizerMockCreator.GetStringLocalizerMockObject()), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(model.Id, Is.EqualTo(id));
Assert.That(model.FIO, Is.EqualTo(fio));
Assert.That(model.PostId, Is.EqualTo(postId));
Assert.That(model.BirthDate, Is.EqualTo(birthDate));
Assert.That(model.EmploymentDate, Is.EqualTo(employmentDate));
Assert.That(model.BirthDate, Is.EqualTo(birthDate.ToUniversalTime()));
Assert.That(model.EmploymentDate, Is.EqualTo(employmentDate.ToUniversalTime()));
Assert.That(model.IsDeleted, Is.EqualTo(isDeleted));
Assert.That(model.ConfigurationModel, Is.EqualTo(configuration));
Assert.That(model.ConfigurationModel.Rate, Is.EqualTo(configuration.Rate));
Assert.That(model.ConfigurationModel.CultureName, Is.Not.Empty);
});
}
private static WorkerDataModel CreateDataModel(string? id, string? fio, string? postId, DateTime birthDate, DateTime employmentDate, bool isDeleted)
=> new(id, fio, postId, birthDate, employmentDate, isDeleted);
private static WorkerDataModel CreateDataModel(string? id, string? fio, string? postId, DateTime birthDate, DateTime employmentDate, bool isDeleted, PostConfiguration configuration)
=> new(id, fio, postId, birthDate, employmentDate, isDeleted, configuration);
}

View File

@@ -5,5 +5,6 @@ namespace FurnitureAssemblyTests.Infrastructure;
class ConfigurationSalaryTest : IConfigurationSalary
{
public double ExtraMadeSum => 10;
public int MaxConcurrentThreads => 4;
}

View File

@@ -1,29 +1,25 @@

using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
using FurnitureAssemblyDatebase;
using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore;
using System;
namespace FurnitureAssemblyTests.Infrastructure;
internal static class FurnitureAssemblyDbContextExtensions
{
public static Post InsertPostToDatabaseAndReturn(this FurnitureAssemblyDbContext dbContext, string? id = null, string postName = "test", PostType postType = PostType.Builder, PostConfiguration? config = null, bool isActual = true, DateTime? changeDate = null)
public static Post InsertPostToDatabaseAndReturn(this FurnitureAssemblyDbContext dbContext, string? id = null, string postName = "test", PostType postType = PostType.Builder, double salary = 10, bool isActual = true, DateTime? changeDate = null)
{
var post = new Post() { Id = Guid.NewGuid().ToString(), PostId = id ?? Guid.NewGuid().ToString(), PostName = postName, PostType = postType, Configuration= config ?? new PostConfiguration() { Rate = 100 }, IsActual = isActual, ChangeDate = changeDate ?? DateTime.UtcNow };
var post = new Post() { Id = Guid.NewGuid().ToString(), PostId = id ?? Guid.NewGuid().ToString(), PostName = postName, PostType = postType, Salary = salary, IsActual = isActual, ChangeDate = changeDate ?? DateTime.UtcNow };
dbContext.Posts.Add(post);
dbContext.SaveChanges();
return post;
}
public static Worker InsertWorkerToDatabaseAndReturn(this FurnitureAssemblyDbContext dbContext, string? id = null, string fio = "Иванов И.И.", string? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false, DateTime? dateDelete = null)
public static Worker InsertWorkerToDatabaseAndReturn(this FurnitureAssemblyDbContext dbContext, string? id = null, string fio = "Иванов И.И.", string? postId = null, PostConfiguration? config = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false, DateTime? dateDelete = null)
{
var worker = new Worker()
{
Id = id ?? Guid.NewGuid().ToString(), FIO = fio, PostId = postId ?? Guid.NewGuid().ToString(), BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-20), EmploymentDate = employmentDate ?? DateTime.UtcNow, IsDeleted = isDeleted, DateOfDelete = dateDelete
};
var worker = new Worker() { Id = id ?? Guid.NewGuid().ToString(), FIO = fio, PostId = postId ?? Guid.NewGuid().ToString(), Configuration = config ?? new PostConfiguration() { Rate = 100 }, BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-20), EmploymentDate = employmentDate ?? DateTime.UtcNow, IsDeleted = isDeleted, DateOfDelete = dateDelete };
dbContext.Workers.Add(worker);
dbContext.SaveChanges();
return worker;

View File

@@ -0,0 +1,19 @@
using FurnitureAssemblyContracts.Resources;
using Microsoft.Extensions.Localization;
using Moq;
namespace FurnitureAssemblyTests.Infrastructure;
internal class StringLocalizerMockCreator
{
private static Mock<IStringLocalizer<Messages>>? _mockObject = null;
public static IStringLocalizer<Messages> GetStringLocalizerMockObject()
{
if (_mockObject is null)
{
_mockObject = new Mock<IStringLocalizer<Messages>>();
_mockObject.Setup(_ => _[It.IsAny<string>()]).Returns(new LocalizedString("name", "value"));
}
return _mockObject!.Object;
}
}

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