PIbd-22_Ulybin_A.A._PimpMyRide_Task_7 #9

Closed
qkrlnt wants to merge 6 commits from Task_7_Locale into Task_6_Reports
87 changed files with 2287 additions and 781 deletions

View File

@@ -1,22 +1,25 @@
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using PimpMyRideContracts.BusinessLogicsContracts; using PimpMyRideContracts.BusinessLogicsContracts;
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Extensions; using PimpMyRideContracts.Extensions;
using PimpMyRideContracts.Resources;
using PimpMyRideContracts.StoragesContracts; using PimpMyRideContracts.StoragesContracts;
using System.Text.Json; using System.Text.Json;
namespace PimpMyRideBusinessLogic.Implementations; namespace PimpMyRideBusinessLogic.Implementations;
internal class CarBusinessLogicContract(ICarStorageContract carStorageContract, ILogger logger) : ICarBusinessLogicContract internal class CarBusinessLogicContract(ICarStorageContract carStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : ICarBusinessLogicContract
{ {
private readonly ILogger _logger = logger; private readonly ILogger _logger = logger;
private readonly ICarStorageContract _carStorageContract = carStorageContract; private readonly ICarStorageContract _carStorageContract = carStorageContract;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<CarDataModel> GetAllCars() public List<CarDataModel> GetAllCars()
{ {
_logger.LogInformation("GetAllCars"); _logger.LogInformation("GetAllCars");
return _carStorageContract.GetList() ?? throw new NullListException(); return _carStorageContract.GetList();
} }
public List<CarDataModel> GetAllCarsByClient(string clientId) public List<CarDataModel> GetAllCarsByClient(string clientId)
@@ -30,7 +33,7 @@ internal class CarBusinessLogicContract(ICarStorageContract carStorageContract,
{ {
throw new ValidationException("The value in the field clientId is not a unique identifier."); throw new ValidationException("The value in the field clientId is not a unique identifier.");
} }
return _carStorageContract.GetList(clientId) ?? throw new NullListException(); return _carStorageContract.GetList(clientId);
} }
public List<CarDataModel> GetAllCarsByMake(string make, string model) public List<CarDataModel> GetAllCarsByMake(string make, string model)
@@ -44,7 +47,7 @@ internal class CarBusinessLogicContract(ICarStorageContract carStorageContract,
{ {
throw new ArgumentNullException(nameof(model)); throw new ArgumentNullException(nameof(model));
} }
return _carStorageContract.GetList(make: make, model: model) ?? throw new NullListException(); return _carStorageContract.GetList(make: make, model: model);
} }
public CarDataModel GetCarByData(string data) public CarDataModel GetCarByData(string data)
@@ -56,16 +59,16 @@ internal class CarBusinessLogicContract(ICarStorageContract carStorageContract,
} }
if (data.IsGuid()) if (data.IsGuid())
{ {
return _carStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data); return _carStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data, _localizer);
} }
return _carStorageContract.GetElementByStateNumber(data) ?? throw new ElementNotFoundException(data); return _carStorageContract.GetElementByStateNumber(data) ?? throw new ElementNotFoundException(data, _localizer);
} }
public void InsertCar(CarDataModel carDataModel) public void InsertCar(CarDataModel carDataModel)
{ {
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(carDataModel)); _logger.LogInformation("New data: {json}", JsonSerializer.Serialize(carDataModel));
ArgumentNullException.ThrowIfNull(carDataModel); ArgumentNullException.ThrowIfNull(carDataModel);
carDataModel.Validate(); carDataModel.Validate(_localizer);
_carStorageContract.AddElement(carDataModel); _carStorageContract.AddElement(carDataModel);
} }
@@ -73,7 +76,7 @@ internal class CarBusinessLogicContract(ICarStorageContract carStorageContract,
{ {
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(carDataModel)); _logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(carDataModel));
ArgumentNullException.ThrowIfNull(carDataModel); ArgumentNullException.ThrowIfNull(carDataModel);
carDataModel.Validate(); carDataModel.Validate(_localizer);
_carStorageContract.UpdElement(carDataModel); _carStorageContract.UpdElement(carDataModel);
} }

View File

@@ -1,23 +1,26 @@
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using PimpMyRideContracts.BusinessLogicsContracts; using PimpMyRideContracts.BusinessLogicsContracts;
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Extensions; using PimpMyRideContracts.Extensions;
using PimpMyRideContracts.Resources;
using PimpMyRideContracts.StoragesContracts; using PimpMyRideContracts.StoragesContracts;
using System.Text.Json; using System.Text.Json;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
namespace PimpMyRideBusinessLogic.Implementations; namespace PimpMyRideBusinessLogic.Implementations;
internal class ClientBusinessLogicContract(IClientStorageContract clientStorageContract, ILogger logger) : IClientBusinessLogicContract internal class ClientBusinessLogicContract(IClientStorageContract clientStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : IClientBusinessLogicContract
{ {
private readonly ILogger _logger = logger; private readonly ILogger _logger = logger;
private readonly IClientStorageContract _clientStorageContract = clientStorageContract; private readonly IClientStorageContract _clientStorageContract = clientStorageContract;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<ClientDataModel> GetAllClients() public List<ClientDataModel> GetAllClients()
{ {
_logger.LogInformation("GetAllClients"); _logger.LogInformation("GetAllClients");
return _clientStorageContract.GetList() ?? throw new NullListException(); return _clientStorageContract.GetList();
} }
public ClientDataModel GetClientByData(string data) public ClientDataModel GetClientByData(string data)
@@ -29,20 +32,20 @@ internal class ClientBusinessLogicContract(IClientStorageContract clientStorageC
} }
if (data.IsGuid()) if (data.IsGuid())
{ {
return _clientStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data); return _clientStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data, _localizer);
} }
if (Regex.IsMatch(data, @"^((\+7|7|8)+([0-9]){10})$")) if (Regex.IsMatch(data, @"^((\+7|7|8)+([0-9]){10})$"))
{ {
return _clientStorageContract.GetElementByPhoneNumber(data) ?? throw new ElementNotFoundException(data); return _clientStorageContract.GetElementByPhoneNumber(data) ?? throw new ElementNotFoundException(data, _localizer);
} }
return _clientStorageContract.GetElementByFIO(data) ?? throw new ElementNotFoundException(data); return _clientStorageContract.GetElementByFIO(data) ?? throw new ElementNotFoundException(data, _localizer);
} }
public void InsertClient(ClientDataModel clientDataModel) public void InsertClient(ClientDataModel clientDataModel)
{ {
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(clientDataModel)); _logger.LogInformation("New data: {json}", JsonSerializer.Serialize(clientDataModel));
ArgumentNullException.ThrowIfNull(clientDataModel); ArgumentNullException.ThrowIfNull(clientDataModel);
clientDataModel.Validate(); clientDataModel.Validate(_localizer);
_clientStorageContract.AddElement(clientDataModel); _clientStorageContract.AddElement(clientDataModel);
} }
@@ -50,7 +53,7 @@ internal class ClientBusinessLogicContract(IClientStorageContract clientStorageC
{ {
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(clientDataModel)); _logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(clientDataModel));
ArgumentNullException.ThrowIfNull(clientDataModel); ArgumentNullException.ThrowIfNull(clientDataModel);
clientDataModel.Validate(); clientDataModel.Validate(_localizer);
_clientStorageContract.UpdElement(clientDataModel); _clientStorageContract.UpdElement(clientDataModel);
} }

View File

@@ -1,23 +1,26 @@
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using PimpMyRideContracts.BusinessLogicsContracts; using PimpMyRideContracts.BusinessLogicsContracts;
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Enums; using PimpMyRideContracts.Enums;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Extensions; using PimpMyRideContracts.Extensions;
using PimpMyRideContracts.Resources;
using PimpMyRideContracts.StoragesContracts; using PimpMyRideContracts.StoragesContracts;
using System.Text.Json; using System.Text.Json;
namespace PimpMyRideBusinessLogic.Implementations; namespace PimpMyRideBusinessLogic.Implementations;
internal class MaterialBusinessLogicContract(IMaterialStorageContracts materialStorageContract, ILogger logger) : IMaterialBusinessLogicContract internal class MaterialBusinessLogicContract(IMaterialStorageContracts materialStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : IMaterialBusinessLogicContract
{ {
private readonly ILogger _logger = logger; private readonly ILogger _logger = logger;
private readonly IMaterialStorageContracts _materialStorageContract = materialStorageContract; private readonly IMaterialStorageContracts _materialStorageContract = materialStorageContract;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<MaterialDataModel> GetAllMaterials() public List<MaterialDataModel> GetAllMaterials()
{ {
_logger.LogInformation("GetAllMaterials"); _logger.LogInformation("GetAllMaterials");
return _materialStorageContract.GetList() ?? throw new NullListException(); return _materialStorageContract.GetList();
} }
public List<MaterialDataModel> GetAllMaterialsByType(MaterialType materialType) public List<MaterialDataModel> GetAllMaterialsByType(MaterialType materialType)
@@ -27,7 +30,7 @@ internal class MaterialBusinessLogicContract(IMaterialStorageContracts materialS
{ {
throw new ArgumentNullException(nameof(materialType)); throw new ArgumentNullException(nameof(materialType));
} }
return _materialStorageContract.GetList(materialType) ?? throw new NullListException(); return _materialStorageContract.GetList(materialType);
} }
public MaterialDataModel GetMaterialByData(string data) public MaterialDataModel GetMaterialByData(string data)
@@ -39,9 +42,9 @@ internal class MaterialBusinessLogicContract(IMaterialStorageContracts materialS
} }
if (data.IsGuid()) if (data.IsGuid())
{ {
return _materialStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data); return _materialStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data, _localizer);
} }
return _materialStorageContract.GetElementByDescription(data) ?? throw new ElementNotFoundException(data); return _materialStorageContract.GetElementByDescription(data) ?? throw new ElementNotFoundException(data, _localizer);
} }
public List<MaterialHistoryDataModel> GetMaterialHistoryById(string materialId) public List<MaterialHistoryDataModel> GetMaterialHistoryById(string materialId)
@@ -55,14 +58,14 @@ internal class MaterialBusinessLogicContract(IMaterialStorageContracts materialS
{ {
throw new ValidationException("The value in the field materialId is not a unique identifier."); throw new ValidationException("The value in the field materialId is not a unique identifier.");
} }
return _materialStorageContract.GetHistoryByMaterialId(materialId) ?? throw new NullListException(); return _materialStorageContract.GetHistoryByMaterialId(materialId);
} }
public void InsertMaterial(MaterialDataModel materialDataModel) public void InsertMaterial(MaterialDataModel materialDataModel)
{ {
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(materialDataModel)); _logger.LogInformation("New data: {json}", JsonSerializer.Serialize(materialDataModel));
ArgumentNullException.ThrowIfNull(materialDataModel); ArgumentNullException.ThrowIfNull(materialDataModel);
materialDataModel.Validate(); materialDataModel.Validate(_localizer);
_materialStorageContract.AddElement(materialDataModel); _materialStorageContract.AddElement(materialDataModel);
} }
@@ -70,7 +73,7 @@ internal class MaterialBusinessLogicContract(IMaterialStorageContracts materialS
{ {
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(materialDataModel)); _logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(materialDataModel));
ArgumentNullException.ThrowIfNull(materialDataModel); ArgumentNullException.ThrowIfNull(materialDataModel);
materialDataModel.Validate(); materialDataModel.Validate(_localizer);
_materialStorageContract.UpdElement(materialDataModel); _materialStorageContract.UpdElement(materialDataModel);
} }

View File

@@ -1,17 +1,19 @@
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using PimpMyRideContracts.BusinessLogicsContracts; using PimpMyRideContracts.BusinessLogicsContracts;
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Extensions; using PimpMyRideContracts.Extensions;
using PimpMyRideContracts.Infrastructure; using PimpMyRideContracts.Infrastructure;
using PimpMyRideContracts.Resources;
using PimpMyRideContracts.StoragesContracts; using PimpMyRideContracts.StoragesContracts;
using System.Text.Json; using System.Text.Json;
namespace PimpMyRideBusinessLogic.Implementations; namespace PimpMyRideBusinessLogic.Implementations;
internal class OrderBusinessLogicContract(IOrderStorageContract orderStorageContract, IServiceStorageContracts serviceStorageContract, internal class OrderBusinessLogicContract(IOrderStorageContract orderStorageContract, IServiceStorageContracts serviceStorageContract,
IServiceBusinessLogicContract serviceLogic, IConfigurationOrder configuration, ILogger logger) : IOrderBusinessLogicContract IServiceBusinessLogicContract serviceLogic, IConfigurationOrder configuration, IStringLocalizer<Messages> localizer, ILogger logger) : IOrderBusinessLogicContract
{ {
private readonly ILogger _logger = logger; private readonly ILogger _logger = logger;
private readonly IOrderStorageContract _orderStorageContract = orderStorageContract; private readonly IOrderStorageContract _orderStorageContract = orderStorageContract;
@@ -19,6 +21,7 @@ internal class OrderBusinessLogicContract(IOrderStorageContract orderStorageCont
private readonly IServiceBusinessLogicContract _serviceLogic = serviceLogic; private readonly IServiceBusinessLogicContract _serviceLogic = serviceLogic;
private readonly IConfigurationOrder _config = configuration; private readonly IConfigurationOrder _config = configuration;
private readonly object _lockObject = new(); private readonly object _lockObject = new();
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<OrderDataModel> GetAllOrdersByCarByPeriod(string carId, DateTime fromDate, DateTime toDate) public List<OrderDataModel> GetAllOrdersByCarByPeriod(string carId, DateTime fromDate, DateTime toDate)
@@ -26,7 +29,7 @@ internal class OrderBusinessLogicContract(IOrderStorageContract orderStorageCont
_logger.LogInformation("GetAllOrders params: {carId}, {fromDate}, {toDate}", carId, fromDate, toDate); _logger.LogInformation("GetAllOrders params: {carId}, {fromDate}, {toDate}", carId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate)) if (fromDate.IsDateNotOlder(toDate))
{ {
throw new IncorrectDatesException(fromDate, toDate); throw new IncorrectDatesException(fromDate, toDate, _localizer);
} }
if (carId.IsEmpty()) if (carId.IsEmpty())
{ {
@@ -36,7 +39,7 @@ internal class OrderBusinessLogicContract(IOrderStorageContract orderStorageCont
{ {
throw new ValidationException("The value in the field carId is not a unique identifier."); throw new ValidationException("The value in the field carId is not a unique identifier.");
} }
return _orderStorageContract.GetList(fromDate, toDate, carId: carId) ?? throw new NullListException(); return _orderStorageContract.GetList(fromDate, toDate, carId: carId);
} }
public List<OrderDataModel> GetAllOrdersByPeriod(DateTime fromDate, DateTime toDate) public List<OrderDataModel> GetAllOrdersByPeriod(DateTime fromDate, DateTime toDate)
@@ -44,9 +47,9 @@ internal class OrderBusinessLogicContract(IOrderStorageContract orderStorageCont
_logger.LogInformation("GetAllSales params: {fromDate}, {toDate}", fromDate, toDate); _logger.LogInformation("GetAllSales params: {fromDate}, {toDate}", fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate)) if (fromDate.IsDateNotOlder(toDate))
{ {
throw new IncorrectDatesException(fromDate, toDate); throw new IncorrectDatesException(fromDate, toDate, _localizer);
} }
return _orderStorageContract.GetList(fromDate, toDate) ?? throw new NullListException(); return _orderStorageContract.GetList(fromDate, toDate);
} }
public OrderDataModel GetOrderByData(string data) public OrderDataModel GetOrderByData(string data)
@@ -60,14 +63,14 @@ internal class OrderBusinessLogicContract(IOrderStorageContract orderStorageCont
{ {
throw new ValidationException("Id is not a unique identifier"); throw new ValidationException("Id is not a unique identifier");
} }
return _orderStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data); return _orderStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data, _localizer);
} }
public void InsertOrder(OrderDataModel orderDataModel) public void InsertOrder(OrderDataModel orderDataModel)
{ {
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(orderDataModel)); _logger.LogInformation("New data: {json}", JsonSerializer.Serialize(orderDataModel));
ArgumentNullException.ThrowIfNull(orderDataModel); ArgumentNullException.ThrowIfNull(orderDataModel);
orderDataModel.Validate(); orderDataModel.Validate(_localizer);
_orderStorageContract.AddElement(orderDataModel); _orderStorageContract.AddElement(orderDataModel);
} }
@@ -90,7 +93,7 @@ internal class OrderBusinessLogicContract(IOrderStorageContract orderStorageCont
_logger.LogInformation("CalculateOrderCost for order {orderId}", orderId); _logger.LogInformation("CalculateOrderCost for order {orderId}", orderId);
var order = _orderStorageContract.GetElementById(orderId) var order = _orderStorageContract.GetElementById(orderId)
?? throw new ElementNotFoundException(orderId); ?? throw new ElementNotFoundException(orderId, _localizer);
var services = order.Services; var services = order.Services;
if (services.Count == 0) throw new ValidationException("Order must include services"); if (services.Count == 0) throw new ValidationException("Order must include services");
@@ -112,7 +115,7 @@ internal class OrderBusinessLogicContract(IOrderStorageContract orderStorageCont
try try
{ {
var service = _serviceStorage.GetElementById(svcMapping.ServiceId) var service = _serviceStorage.GetElementById(svcMapping.ServiceId)
?? throw new ElementNotFoundException(svcMapping.ServiceId); ?? throw new ElementNotFoundException(svcMapping.ServiceId, _localizer);
double cost = _serviceLogic.CalculateTotalCost(service); double cost = _serviceLogic.CalculateTotalCost(service);

View File

@@ -1,25 +1,43 @@
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using PimpMyRideBusinessLogic.OfficePackage; using PimpMyRideBusinessLogic.OfficePackage;
using PimpMyRideContracts.BusinessLogicsContracts; using PimpMyRideContracts.BusinessLogicsContracts;
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Extensions; using PimpMyRideContracts.Extensions;
using PimpMyRideContracts.Resources;
using PimpMyRideContracts.StoragesContracts; using PimpMyRideContracts.StoragesContracts;
namespace PimpMyRideBusinessLogic.Implementations; namespace PimpMyRideBusinessLogic.Implementations;
internal class ReportContract(ICarStorageContract carStorageContract, IOrderStorageContract orderStorageContract, IServiceStorageContracts serviceStorageContract, BaseWordBuilder baseWordBuilder, BaseExcelBuilder baseExcelBuilder, BasePdfBuilder basePdfBuilder, ILogger logger) : IReportContract internal class ReportContract : IReportContract
{ {
private readonly ICarStorageContract _carStorageContract = carStorageContract; private readonly ICarStorageContract _carStorageContract;
private readonly IOrderStorageContract _orderStorageContract = orderStorageContract; private readonly IOrderStorageContract _orderStorageContract;
private readonly IServiceStorageContracts _serviceStorageContract = serviceStorageContract; private readonly IServiceStorageContracts _serviceStorageContract;
private readonly BaseWordBuilder _baseWordBuilder = baseWordBuilder; private readonly BaseWordBuilder _baseWordBuilder;
private readonly BaseExcelBuilder _baseExcelBuilder = baseExcelBuilder; private readonly BaseExcelBuilder _baseExcelBuilder;
private readonly BasePdfBuilder _basePdfBuilder = basePdfBuilder; private readonly BasePdfBuilder _basePdfBuilder;
private readonly ILogger _logger = logger; private readonly IStringLocalizer<Messages> _localizer;
private readonly ILogger _logger;
internal static readonly string[] documentHeader = ["Клиент", "Авто"]; internal readonly string[] _documentHeader;
internal static readonly string[] tableHeader = ["Дата", "Сумма", "", "Товар", "Кол-во"]; internal readonly string[] _tableHeader;
public ReportContract(ICarStorageContract carStorageContract, IOrderStorageContract orderStorageContract, IServiceStorageContracts serviceStorageContract, BaseWordBuilder baseWordBuilder, BaseExcelBuilder baseExcelBuilder, BasePdfBuilder basePdfBuilder, IStringLocalizer<Messages> localizer, ILogger logger)
{
_carStorageContract = carStorageContract;
_orderStorageContract = orderStorageContract;
_serviceStorageContract = serviceStorageContract;
_baseWordBuilder = baseWordBuilder;
_baseExcelBuilder = baseExcelBuilder;
_basePdfBuilder = basePdfBuilder;
_localizer = localizer;
_logger = logger;
_documentHeader = [_localizer["DocumentDocCaptionClient"], _localizer["DocumentDocCaptionCar"]];
_tableHeader = [_localizer["DocumentExcelCaptionDate"], _localizer["DocumentExcelCaptionSum"], "",
_localizer["DocumentExcelCaptionMaterial"], _localizer["DocumentExcelCaptionCount"]];
}
public async Task<Stream> CreateDocumentCarsByClientAsync(CancellationToken ct) public async Task<Stream> CreateDocumentCarsByClientAsync(CancellationToken ct)
{ {
@@ -31,11 +49,11 @@ internal class ReportContract(ICarStorageContract carStorageContract, IOrderStor
.Union(x.Cars.Select(y => new string[] { "", y })) .Union(x.Cars.Select(y => new string[] { "", y }))
).ToList(); ).ToList();
tableRows.Insert(0, documentHeader); tableRows.Insert(0, _documentHeader);
return _baseWordBuilder return _baseWordBuilder
.AddHeader("Автомобили по клиентам") .AddHeader(_localizer["DocumentDocHeader"])
.AddParagraph($"Сформировано на дату: {DateTime.Now}") .AddParagraph(string.Format(_localizer["DocumentDocSubHeader"], DateTime.Now))
.AddTable([3000, 3000], tableRows) .AddTable([3000, 3000], tableRows)
.Build(); .Build();
} }
@@ -50,11 +68,11 @@ internal class ReportContract(ICarStorageContract carStorageContract, IOrderStor
.Union(x.Services!.Select(y => new string[] { "", "", "", y.ServiceType, y.Count.ToString("N2") })) .Union(x.Services!.Select(y => new string[] { "", "", "", y.ServiceType, y.Count.ToString("N2") }))
).ToList(); ).ToList();
tableRows.Insert(0, tableHeader); tableRows.Insert(0, _tableHeader);
return _baseExcelBuilder return _baseExcelBuilder
.AddHeader("Продажи за период", 0, 5) .AddHeader(_localizer["DocumentExcelHeader"], 0, 5)
.AddParagraph($"c {dateStart.ToShortDateString()} по {dateFinish.ToShortDateString()}", 2) .AddParagraph(string.Format(_localizer["DocumentExcelSubHeader"], dateStart.ToLocalTime().ToShortDateString(), dateFinish.ToLocalTime().ToShortDateString()), 2)
.AddTable([10, 10, 10, 10, 10], tableRows) .AddTable([10, 10, 10, 10, 10], tableRows)
.Build(); .Build();
} }
@@ -64,9 +82,9 @@ internal class ReportContract(ICarStorageContract carStorageContract, IOrderStor
_logger.LogInformation("Create report ServiceByPeriod from {dateStart} to {dateFinish}", dateStart, dateFinish); _logger.LogInformation("Create report ServiceByPeriod from {dateStart} to {dateFinish}", dateStart, dateFinish);
var data = await GetDataByServiceAsync(dateStart, dateFinish, ct) ?? throw new InvalidOperationException("No found data"); var data = await GetDataByServiceAsync(dateStart, dateFinish, ct) ?? throw new InvalidOperationException("No found data");
return _basePdfBuilder return _basePdfBuilder
.AddHeader("Ведомость по заказам") .AddHeader(_localizer["DocumentPdfHeader"])
.AddParagraph($"за период с {dateStart.ToShortDateString()} по {dateFinish.ToShortDateString()}") .AddParagraph(string.Format(_localizer["DocumentPdfSubHeader"], dateStart.ToLocalTime().ToShortDateString(), dateFinish.ToLocalTime().ToShortDateString()))
.AddPieChart("Начисления", [.. data.Select(x => (x.WorkerFIO, x.TotalAmount))]) .AddPieChart(_localizer["DocumentPdfDiagramCaption"], [.. data.Select(x => (x.WorkerFIO, x.TotalAmount))])
.Build(); .Build();
} }
@@ -94,7 +112,7 @@ internal class ReportContract(ICarStorageContract carStorageContract, IOrderStor
{ {
if (dateStart.IsDateNotOlder(dateFinish)) if (dateStart.IsDateNotOlder(dateFinish))
{ {
throw new IncorrectDatesException(dateStart, dateFinish); throw new IncorrectDatesException(dateStart, dateFinish, _localizer);
} }
return [.. (await _orderStorageContract.GetListAsync(dateStart, dateFinish, ct)).OrderBy(x => x.OrderDate)]; return [.. (await _orderStorageContract.GetListAsync(dateStart, dateFinish, ct)).OrderBy(x => x.OrderDate)];
} }
@@ -103,7 +121,7 @@ internal class ReportContract(ICarStorageContract carStorageContract, IOrderStor
{ {
if (dateStart.IsDateNotOlder(dateFinish)) if (dateStart.IsDateNotOlder(dateFinish))
{ {
throw new IncorrectDatesException(dateStart, dateFinish); throw new IncorrectDatesException(dateStart, dateFinish, _localizer);
} }
return [.. (await _serviceStorageContract.GetListAsync(dateStart, dateFinish, ct)).GroupBy(x => new { x.WorkerId, x.WorkerFIO }).Select(x => new WorkerServiceByPeriodDataModel { WorkerFIO = x.Key.WorkerFIO, TotalAmount = x.Sum(y => y.ConfigurationModel.Rate), FromPeriod = x.Min(y => y.ServiceDate), ToPeriod = x.Max(y => y.ServiceDate) }).OrderBy(x => x.WorkerFIO)]; return [.. (await _serviceStorageContract.GetListAsync(dateStart, dateFinish, ct)).GroupBy(x => new { x.WorkerId, x.WorkerFIO }).Select(x => new WorkerServiceByPeriodDataModel { WorkerFIO = x.Key.WorkerFIO, TotalAmount = x.Sum(y => y.ConfigurationModel.Rate), FromPeriod = x.Min(y => y.ServiceDate), ToPeriod = x.Max(y => y.ServiceDate) }).OrderBy(x => x.WorkerFIO)];
} }

View File

@@ -1,24 +1,27 @@
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using PimpMyRideContracts.BusinessLogicsContracts; using PimpMyRideContracts.BusinessLogicsContracts;
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Enums; using PimpMyRideContracts.Enums;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Extensions; using PimpMyRideContracts.Extensions;
using PimpMyRideContracts.Infrastructure.ServiceConfiguration; using PimpMyRideContracts.Infrastructure.ServiceConfiguration;
using PimpMyRideContracts.Resources;
using PimpMyRideContracts.StoragesContracts; using PimpMyRideContracts.StoragesContracts;
using System.Text.Json; using System.Text.Json;
namespace PimpMyRideBusinessLogic.Implementations; namespace PimpMyRideBusinessLogic.Implementations;
internal class ServiceBusinessLogicContract(IServiceStorageContracts serviceStorageContracts, ILogger logger) : IServiceBusinessLogicContract internal class ServiceBusinessLogicContract(IServiceStorageContracts serviceStorageContracts, IStringLocalizer<Messages> localizer, ILogger logger) : IServiceBusinessLogicContract
{ {
private readonly ILogger _logger = logger; private readonly ILogger _logger = logger;
private readonly IServiceStorageContracts _serviceStorageContract = serviceStorageContracts; private readonly IServiceStorageContracts _serviceStorageContract = serviceStorageContracts;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<ServiceDataModel> GetAllServices() public List<ServiceDataModel> GetAllServices()
{ {
_logger.LogInformation("GetAllServices"); _logger.LogInformation("GetAllServices");
return _serviceStorageContract.GetList() ?? throw new NullListException(); return _serviceStorageContract.GetList();
} }
public List<ServiceDataModel> GetAllServicesByWork(string workerId, WorkType workType) public List<ServiceDataModel> GetAllServicesByWork(string workerId, WorkType workType)
@@ -36,7 +39,7 @@ namespace PimpMyRideBusinessLogic.Implementations;
{ {
throw new ValidationException(nameof(workType)); throw new ValidationException(nameof(workType));
} }
return _serviceStorageContract.GetList(workerId, workType) ?? throw new NullListException(); return _serviceStorageContract.GetList(workerId, workType);
} }
public ServiceDataModel GetServiceByData(string data) public ServiceDataModel GetServiceByData(string data)
@@ -48,7 +51,7 @@ namespace PimpMyRideBusinessLogic.Implementations;
} }
if (data.IsGuid()) if (data.IsGuid())
{ {
return _serviceStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data); return _serviceStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data, _localizer);
} }
throw new ValidationException("The value in the field data is not an unique identifier."); throw new ValidationException("The value in the field data is not an unique identifier.");
} }
@@ -57,7 +60,7 @@ namespace PimpMyRideBusinessLogic.Implementations;
{ {
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(serviceDataModel)); _logger.LogInformation("New data: {json}", JsonSerializer.Serialize(serviceDataModel));
ArgumentNullException.ThrowIfNull(serviceDataModel); ArgumentNullException.ThrowIfNull(serviceDataModel);
serviceDataModel.Validate(); serviceDataModel.Validate(_localizer);
_serviceStorageContract.AddElement(serviceDataModel); _serviceStorageContract.AddElement(serviceDataModel);
} }
@@ -82,7 +85,7 @@ namespace PimpMyRideBusinessLogic.Implementations;
if (service is null) if (service is null)
throw new ArgumentNullException(nameof(service)); throw new ArgumentNullException(nameof(service));
service.Validate(); service.Validate(_localizer);
var config = service.ConfigurationModel var config = service.ConfigurationModel
?? throw new ValidationException("Service configuration is missing"); ?? throw new ValidationException("Service configuration is missing");

View File

@@ -1,24 +1,27 @@
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using PimpMyRideContracts.BusinessLogicsContracts; using PimpMyRideContracts.BusinessLogicsContracts;
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Enums; using PimpMyRideContracts.Enums;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Extensions; using PimpMyRideContracts.Extensions;
using PimpMyRideContracts.Resources;
using PimpMyRideContracts.StoragesContracts; using PimpMyRideContracts.StoragesContracts;
using System.Text.Json; using System.Text.Json;
using static System.Runtime.InteropServices.JavaScript.JSType; using static System.Runtime.InteropServices.JavaScript.JSType;
namespace PimpMyRideBusinessLogic.Implementations; namespace PimpMyRideBusinessLogic.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 ILogger _logger = logger;
private readonly IWorkerStorageContract _workerStorageContract = workerStorageContract; private readonly IWorkerStorageContract _workerStorageContract = workerStorageContract;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<WorkerDataModel> GetAllWorkers(bool onlyActive = true) public List<WorkerDataModel> GetAllWorkers(bool onlyActive = true)
{ {
_logger.LogInformation("GetAllWorkers params: {onlyActive}", onlyActive); _logger.LogInformation("GetAllWorkers params: {onlyActive}", onlyActive);
return _workerStorageContract.GetList(onlyActive) ?? throw new NullListException(); return _workerStorageContract.GetList(onlyActive);
} }
public List<WorkerDataModel> GetAllWorkersByBirthDate(DateTime fromDate, DateTime toDate, bool onlyActive = true) public List<WorkerDataModel> GetAllWorkersByBirthDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
@@ -26,9 +29,9 @@ internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageC
_logger.LogInformation("GetAllWorkers params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate); _logger.LogInformation("GetAllWorkers params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(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) public List<WorkerDataModel> GetAllWorkersByEmploymentDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
@@ -36,9 +39,9 @@ internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageC
_logger.LogInformation("GetAllWorkers params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate); _logger.LogInformation("GetAllWorkers params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(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 List<WorkerDataModel> GetAllWorkersBySpeciality(SpecialityType specialityType, bool onlyActive = true) public List<WorkerDataModel> GetAllWorkersBySpeciality(SpecialityType specialityType, bool onlyActive = true)
@@ -48,7 +51,7 @@ internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageC
{ {
throw new ArgumentNullException(nameof(specialityType)); throw new ArgumentNullException(nameof(specialityType));
} }
return _workerStorageContract.GetList(onlyActive, specialityType) ?? throw new NullListException(); return _workerStorageContract.GetList(onlyActive, specialityType);
} }
public WorkerDataModel GetWorkerByData(string data) public WorkerDataModel GetWorkerByData(string data)
@@ -60,16 +63,16 @@ internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageC
} }
if (data.IsGuid()) 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) public void InsertWorker(WorkerDataModel workerDataModel)
{ {
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(workerDataModel)); _logger.LogInformation("New data: {json}", JsonSerializer.Serialize(workerDataModel));
ArgumentNullException.ThrowIfNull(workerDataModel); ArgumentNullException.ThrowIfNull(workerDataModel);
workerDataModel.Validate(); workerDataModel.Validate(_localizer);
_workerStorageContract.AddElement(workerDataModel); _workerStorageContract.AddElement(workerDataModel);
} }
@@ -77,7 +80,7 @@ internal class WorkerBusinessLogicContract(IWorkerStorageContract workerStorageC
{ {
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(workerDataModel)); _logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(workerDataModel));
ArgumentNullException.ThrowIfNull(workerDataModel); ArgumentNullException.ThrowIfNull(workerDataModel);
workerDataModel.Validate(); workerDataModel.Validate(_localizer);
_workerStorageContract.UpdElement(workerDataModel); _workerStorageContract.UpdElement(workerDataModel);
} }

View File

@@ -2,7 +2,7 @@
namespace PimpMyRideContracts.BusinessLogicsContracts; namespace PimpMyRideContracts.BusinessLogicsContracts;
public interface ICarBusinessLogicContract internal interface ICarBusinessLogicContract
{ {
List<CarDataModel> GetAllCars(); List<CarDataModel> GetAllCars();

View File

@@ -1,7 +1,7 @@
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
namespace PimpMyRideContracts.BusinessLogicsContracts; namespace PimpMyRideContracts.BusinessLogicsContracts;
public interface IClientBusinessLogicContract internal interface IClientBusinessLogicContract
{ {
List<ClientDataModel> GetAllClients(); List<ClientDataModel> GetAllClients();

View File

@@ -3,7 +3,7 @@ using PimpMyRideContracts.Enums;
namespace PimpMyRideContracts.BusinessLogicsContracts; namespace PimpMyRideContracts.BusinessLogicsContracts;
public interface IMaterialBusinessLogicContract internal interface IMaterialBusinessLogicContract
{ {
List<MaterialDataModel> GetAllMaterials(); List<MaterialDataModel> GetAllMaterials();

View File

@@ -2,7 +2,7 @@
namespace PimpMyRideContracts.BusinessLogicsContracts; namespace PimpMyRideContracts.BusinessLogicsContracts;
public interface IOrderBusinessLogicContract internal interface IOrderBusinessLogicContract
{ {
List<OrderDataModel> GetAllOrdersByPeriod(DateTime fromDate, DateTime toDate); List<OrderDataModel> GetAllOrdersByPeriod(DateTime fromDate, DateTime toDate);

View File

@@ -2,7 +2,7 @@
namespace PimpMyRideContracts.BusinessLogicsContracts; namespace PimpMyRideContracts.BusinessLogicsContracts;
public interface IReportContract internal interface IReportContract
{ {
Task<List<ClientCarDataModel>> GetDataCarsByClientAsync(CancellationToken ct); Task<List<ClientCarDataModel>> GetDataCarsByClientAsync(CancellationToken ct);

View File

@@ -3,7 +3,7 @@ using PimpMyRideContracts.Enums;
namespace PimpMyRideContracts.BusinessLogicsContracts; namespace PimpMyRideContracts.BusinessLogicsContracts;
public interface IServiceBusinessLogicContract internal interface IServiceBusinessLogicContract
{ {
List<ServiceDataModel> GetAllServices(); List<ServiceDataModel> GetAllServices();

View File

@@ -3,7 +3,7 @@ using PimpMyRideContracts.Enums;
namespace PimpMyRideContracts.BusinessLogicsContracts; namespace PimpMyRideContracts.BusinessLogicsContracts;
public interface IWorkerBusinessLogicContract internal interface IWorkerBusinessLogicContract
{ {
List<WorkerDataModel> GetAllWorkers(bool onlyActive = true); List<WorkerDataModel> GetAllWorkers(bool onlyActive = true);

View File

@@ -1,10 +1,12 @@
using PimpMyRideContracts.Exceptions; using Microsoft.Extensions.Localization;
using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Extensions; using PimpMyRideContracts.Extensions;
using PimpMyRideContracts.Infrastructure; using PimpMyRideContracts.Infrastructure;
using PimpMyRideContracts.Resources;
namespace PimpMyRideContracts.DataModels; namespace PimpMyRideContracts.DataModels;
public class CarDataModel(string id, string clientId, string make, string model, string stateNumber) : IValidation internal class CarDataModel(string id, string clientId, string make, string model, string stateNumber) : IValidation
{ {
private readonly ClientDataModel? _client; private readonly ClientDataModel? _client;
@@ -25,27 +27,27 @@ public class CarDataModel(string id, string clientId, string make, string model,
_client = client; _client = client;
} }
public void Validate() public void Validate(IStringLocalizer<Messages> localizer)
{ {
if (Id.IsEmpty()) if (Id.IsEmpty())
throw new ValidationException("Field Id is empty"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
if (!Id.IsGuid()) if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAnId"], "Id"));
if (ClientId.IsEmpty()) if (ClientId.IsEmpty())
throw new ValidationException("Field CustomerId is empty"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "ClientId"));
if (!ClientId.IsGuid()) if (!ClientId.IsGuid())
throw new ValidationException("The value in the field CustomerId is not a unique identifier"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAnId"], "ClientId"));
if (Make.IsEmpty()) if (Make.IsEmpty())
throw new ValidationException("Field Make is empty"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Make"));
if (Model.IsEmpty()) if (Model.IsEmpty())
throw new ValidationException("Field Model is empty"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Model"));
if (StateNumber.IsEmpty()) if (StateNumber.IsEmpty())
throw new ValidationException("Field StateNumber is empty"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "StateNumber"));
} }
} }

View File

@@ -1,11 +1,13 @@
using PimpMyRideContracts.Exceptions; using Microsoft.Extensions.Localization;
using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Extensions; using PimpMyRideContracts.Extensions;
using PimpMyRideContracts.Infrastructure; using PimpMyRideContracts.Infrastructure;
using PimpMyRideContracts.Resources;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
namespace PimpMyRideContracts.DataModels; namespace PimpMyRideContracts.DataModels;
public class ClientDataModel(string id, string fio, string phoneNumber) : IValidation internal class ClientDataModel(string id, string fio, string phoneNumber) : IValidation
{ {
public string Id { get; private set; } = id; public string Id { get; private set; } = id;
@@ -13,21 +15,21 @@ public class ClientDataModel(string id, string fio, string phoneNumber) : IValid
public string PhoneNumber { get; private set; } = phoneNumber; public string PhoneNumber { get; private set; } = phoneNumber;
public void Validate() public void Validate(IStringLocalizer<Messages> localizer)
{ {
if (Id.IsEmpty()) if (Id.IsEmpty())
throw new ValidationException("Field Id is empty"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
if (!Id.IsGuid()) if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not an unique identifier"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAnId"], "Id"));
if (FIO.IsEmpty()) if (FIO.IsEmpty())
throw new ValidationException("Field FIO is empty"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "FIO"));
if (PhoneNumber.IsEmpty()) if (PhoneNumber.IsEmpty())
throw new ValidationException("Field PhoneNumber is empty"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "PhoneNumber"));
if (!Regex.IsMatch(PhoneNumber, @"^((\+7|7|8)+([0-9]){10})$")) if (!Regex.IsMatch(PhoneNumber, @"^((\+7|7|8)+([0-9]){10})$"))
throw new ValidationException("Field PhoneNumber is not a phone number"); throw new ValidationException(localizer["ValidationExceptionMessageIncorrectPhoneNumber"]);
} }
} }

View File

@@ -1,11 +1,13 @@
using PimpMyRideContracts.Enums; using Microsoft.Extensions.Localization;
using PimpMyRideContracts.Enums;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Extensions; using PimpMyRideContracts.Extensions;
using PimpMyRideContracts.Infrastructure; using PimpMyRideContracts.Infrastructure;
using PimpMyRideContracts.Resources;
namespace PimpMyRideContracts.DataModels; namespace PimpMyRideContracts.DataModels;
public class MaterialDataModel(string id, MaterialType materialType, string description, double unitCost) : IValidation internal class MaterialDataModel(string id, MaterialType materialType, string description, double unitCost) : IValidation
{ {
public string Id { get; private set; } = id; public string Id { get; private set; } = id;
@@ -15,21 +17,21 @@ public class MaterialDataModel(string id, MaterialType materialType, string desc
public double UnitCost { get; private set; } = unitCost; public double UnitCost { get; private set; } = unitCost;
public void Validate() public void Validate(IStringLocalizer<Messages> localizer)
{ {
if (Id.IsEmpty()) if (Id.IsEmpty())
throw new ValidationException("Field Id is empty"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
if (!Id.IsGuid()) if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not an unique identifier"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAnId"], "Id"));
if (MaterialType == MaterialType.None) if (MaterialType == MaterialType.None)
throw new ValidationException("Field MaterialType is empty"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Materialtype"));
if (Description.IsEmpty()) if (Description.IsEmpty())
throw new ValidationException("Field Description is empty"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Description"));
if (UnitCost <= 0) if (UnitCost <= 0)
throw new ValidationException("Cost cannot be zero or less"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "UnitCost"));
} }
} }

View File

@@ -1,10 +1,12 @@
using PimpMyRideContracts.Exceptions; using Microsoft.Extensions.Localization;
using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Extensions; using PimpMyRideContracts.Extensions;
using PimpMyRideContracts.Infrastructure; using PimpMyRideContracts.Infrastructure;
using PimpMyRideContracts.Resources;
namespace PimpMyRideContracts.DataModels; namespace PimpMyRideContracts.DataModels;
public class MaterialHistoryDataModel(string materialId, double oldPrice) : IValidation internal class MaterialHistoryDataModel(string materialId, double oldPrice) : IValidation
{ {
private readonly MaterialDataModel? _material; private readonly MaterialDataModel? _material;
@@ -22,15 +24,15 @@ public class MaterialHistoryDataModel(string materialId, double oldPrice) : IVal
_material = material; _material = material;
} }
public void Validate() public void Validate(IStringLocalizer<Messages> localizer)
{ {
if (MaterialId.IsEmpty()) if (MaterialId.IsEmpty())
throw new ValidationException("Field MaterialId is empty"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "MaterialId"));
if (!MaterialId.IsGuid()) if (!MaterialId.IsGuid())
throw new ValidationException("The value in field MaterialId is not an unique identifier"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAnId"], "MaterialId"));
if (OldPrice <= 0) if (OldPrice <= 0)
throw new ValidationException("OldPrice value cannnot be less or equal to '0'"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "OldPrice"));
} }
} }

View File

@@ -1,10 +1,12 @@
using PimpMyRideContracts.Exceptions; using Microsoft.Extensions.Localization;
using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Extensions; using PimpMyRideContracts.Extensions;
using PimpMyRideContracts.Infrastructure; using PimpMyRideContracts.Infrastructure;
using PimpMyRideContracts.Resources;
namespace PimpMyRideContracts.DataModels; namespace PimpMyRideContracts.DataModels;
public class OrderDataModel : IValidation internal class OrderDataModel : IValidation
{ {
private readonly CarDataModel? _car; private readonly CarDataModel? _car;
@@ -37,29 +39,29 @@ public class OrderDataModel : IValidation
_car = car; _car = car;
} }
public void Validate() public void Validate(IStringLocalizer<Messages> localizer)
{ {
if (Id.IsEmpty()) if (Id.IsEmpty())
throw new ValidationException("Field Id is empty"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
if (!Id.IsGuid()) if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not an unique identifier"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAnId"], "Id"));
if (CarId.IsEmpty()) if (CarId.IsEmpty())
throw new ValidationException("Field CarId is empty"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "CarId"));
if (!CarId.IsGuid()) if (!CarId.IsGuid())
throw new ValidationException("The value in the field CarId is not an unique identifier"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAnId"], "CarId"));
if (TotalCost <= 0) if (TotalCost <= 0)
throw new ValidationException("TotalCost cannot be 0 or less"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "TotalCost"));
if ((Services?.Count ?? 0) == 0) if ((Services?.Count ?? 0) == 0)
throw new ValidationException("The order must include Services"); throw new ValidationException(localizer["ValidationExceptionMessageNoServicesInOrder"]);
foreach (var service in Services) foreach (var service in Services)
{ {
service.Validate(); service.Validate(localizer);
} }
} }
} }

View File

@@ -1,11 +1,13 @@
using PimpMyRideContracts.Enums; using Microsoft.Extensions.Localization;
using PimpMyRideContracts.Enums;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Extensions; using PimpMyRideContracts.Extensions;
using PimpMyRideContracts.Infrastructure; using PimpMyRideContracts.Infrastructure;
using PimpMyRideContracts.Resources;
namespace PimpMyRideContracts.DataModels; namespace PimpMyRideContracts.DataModels;
public class OrderServiceDataModel(string orderId, string serviceId, int count, double price) : IValidation internal class OrderServiceDataModel(string orderId, string serviceId, int count, double price) : IValidation
{ {
private readonly ServiceDataModel? _service; private readonly ServiceDataModel? _service;
@@ -24,24 +26,24 @@ public class OrderServiceDataModel(string orderId, string serviceId, int count,
_service = service; _service = service;
} }
public void Validate() public void Validate(IStringLocalizer<Messages> localizer)
{ {
if (OrderId.IsEmpty()) if (OrderId.IsEmpty())
throw new ValidationException("Field OrderId is empty"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "OrderId"));
if (!OrderId.IsGuid()) if (!OrderId.IsGuid())
throw new ValidationException("The value in the field OrderId is not a unique identifier"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAnId"], "OrderId"));
if (ServiceId.IsEmpty()) if (ServiceId.IsEmpty())
throw new ValidationException("Field ServiceId is empty"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "ServiceId"));
if (!ServiceId.IsGuid()) if (!ServiceId.IsGuid())
throw new ValidationException("The value in the field ServiceId is not a unique identifier"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAnId"], "ServiceId"));
if (Count <= 0) if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Count"));
if (Price <= 0) if (Price <= 0)
throw new ValidationException("Field Price is less than or equal to 0"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Price"));
} }
} }

View File

@@ -5,10 +5,12 @@ using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Extensions; using PimpMyRideContracts.Extensions;
using PimpMyRideContracts.Infrastructure; using PimpMyRideContracts.Infrastructure;
using PimpMyRideContracts.Infrastructure.ServiceConfiguration; using PimpMyRideContracts.Infrastructure.ServiceConfiguration;
using Microsoft.Extensions.Localization;
using PimpMyRideContracts.Resources;
namespace PimpMyRideContracts.DataModels; namespace PimpMyRideContracts.DataModels;
public class ServiceDataModel : IValidation internal class ServiceDataModel : IValidation
{ {
private readonly WorkerDataModel? _worker; private readonly WorkerDataModel? _worker;
@@ -71,30 +73,30 @@ public class ServiceDataModel : IValidation
} }
} }
public void Validate() public void Validate(IStringLocalizer<Messages> localizer)
{ {
if (Id.IsEmpty()) if (Id.IsEmpty())
throw new ValidationException("Field Id is empty"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
if (!Id.IsGuid()) if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not an unique identifier"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAnId"], "Id"));
if (WorkerId.IsEmpty()) if (WorkerId.IsEmpty())
throw new ValidationException("Field WorkerId is empty"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "WorkerId"));
if (!WorkerId.IsGuid()) if (!WorkerId.IsGuid())
throw new ValidationException("The value in the field WorkerId is not an unique identifier"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAnId"], "WorkerId"));
if (WorkType == WorkType.None) if (WorkType == WorkType.None)
throw new ValidationException("Field WorkType is empty"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "WorkType"));
if (ConfigurationModel is null) if (ConfigurationModel is null)
throw new ValidationException("ConfigurationModel is not initialized"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotInitialized"], "ConfigurationModel"));
if (ConfigurationModel!.Rate <= 0) if (ConfigurationModel!.Rate <= 0)
throw new ValidationException("Field Rate is less or equal to zero"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Rate"));
if ((Materials?.Count ?? 0) == 0) if ((Materials?.Count ?? 0) == 0)
throw new ValidationException("The service must include Materials"); throw new ValidationException(localizer["ValidationExceptionMessageNoMaterialsInService"]);
} }
} }

View File

@@ -1,10 +1,12 @@
using PimpMyRideContracts.Exceptions; using Microsoft.Extensions.Localization;
using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Extensions; using PimpMyRideContracts.Extensions;
using PimpMyRideContracts.Infrastructure; using PimpMyRideContracts.Infrastructure;
using PimpMyRideContracts.Resources;
namespace PimpMyRideContracts.DataModels; namespace PimpMyRideContracts.DataModels;
public class ServiceMaterialDataModel(string serviceId, string materialId, int count, double price) : IValidation internal class ServiceMaterialDataModel(string serviceId, string materialId, int count, double price) : IValidation
{ {
private readonly MaterialDataModel? _material; private readonly MaterialDataModel? _material;
@@ -23,24 +25,24 @@ public class ServiceMaterialDataModel(string serviceId, string materialId, int c
_material = material; _material = material;
} }
public void Validate() public void Validate(IStringLocalizer<Messages> localizer)
{ {
if (ServiceId.IsEmpty()) if (ServiceId.IsEmpty())
throw new ValidationException("Field ServiceId is empty"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "ServiceId"));
if (!ServiceId.IsGuid()) if (!ServiceId.IsGuid())
throw new ValidationException("The value in the field ServiceId is not a unique identifier"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAnId"], "ServiceId"));
if (MaterialId.IsEmpty()) if (MaterialId.IsEmpty())
throw new ValidationException("Field MaterialId is empty"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "MaterialId"));
if (!MaterialId.IsGuid()) if (!MaterialId.IsGuid())
throw new ValidationException("The value in the field MaterialId is not a unique identifier"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAnId"], "MaterialId"));
if (Count <= 0) if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Count"));
if (Price <= 0) if (Price <= 0)
throw new ValidationException("Field Price is less than or equal to 0"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Price"));
} }
} }

View File

@@ -1,11 +1,13 @@
using PimpMyRideContracts.Enums; using Microsoft.Extensions.Localization;
using PimpMyRideContracts.Enums;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Extensions; using PimpMyRideContracts.Extensions;
using PimpMyRideContracts.Infrastructure; using PimpMyRideContracts.Infrastructure;
using PimpMyRideContracts.Resources;
namespace PimpMyRideContracts.DataModels; namespace PimpMyRideContracts.DataModels;
public class WorkerDataModel(string id, string fio, SpecialityType specialityType, DateTime birthDate, DateTime employmentDate, bool isDeleted) : IValidation internal class WorkerDataModel(string id, string fio, SpecialityType specialityType, DateTime birthDate, DateTime employmentDate, bool isDeleted) : IValidation
{ {
public string Id { get; private set; } = id; public string Id { get; private set; } = id;
@@ -13,35 +15,37 @@ public class WorkerDataModel(string id, string fio, SpecialityType specialityTyp
public SpecialityType SpecialityType { get; private set; } = specialityType; public SpecialityType SpecialityType { get; private set; } = specialityType;
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 bool IsDeleted { get; private set; } = isDeleted;
public WorkerDataModel(string id, string fio, SpecialityType specialityType, DateTime birthDate, DateTime employmentDate) : this(id, fio, specialityType, birthDate, employmentDate, false) { } public WorkerDataModel(string id, string fio, SpecialityType specialityType, DateTime birthDate, DateTime employmentDate) : this(id, fio, specialityType, birthDate, employmentDate, false) { }
public void Validate() public void Validate(IStringLocalizer<Messages> localizer)
{ {
if (Id.IsEmpty()) if (Id.IsEmpty())
throw new ValidationException("Field Id is empty"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
if (!Id.IsGuid()) if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not an unique identifier"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAnId"], "Id"));
if (FIO.IsEmpty()) if (FIO.IsEmpty())
throw new ValidationException("Field FIO is empty"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "FIO"));
if (SpecialityType == SpecialityType.None) if (SpecialityType == SpecialityType.None)
throw new ValidationException("Field SpecialityType is empty"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "SpecialityType"));
if (BirthDate.Date > DateTime.Now.AddYears(-18).Date) if (BirthDate.Date > DateTime.Now.AddYears(-18).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) if (EmploymentDate.Date < BirthDate.Date)
throw new ValidationException("The date of employment cannot be less than the date of birth"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmploymentDateAndBirthDate"],
EmploymentDate.ToShortDateString(), BirthDate.ToShortDateString()));
if ((EmploymentDate - BirthDate).TotalDays / 365 < 16) if ((EmploymentDate - BirthDate).TotalDays / 365 < 16) // EmploymentDate.Year - BirthDate.Year
throw new ValidationException($"Minors cannot be hired (EmploymentDate - {EmploymentDate.ToShortDateString()}, BirthDate - {BirthDate.ToShortDateString()})"); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageMinorsEmploymentDate"],
EmploymentDate.ToShortDateString(), BirthDate.ToShortDateString()));
} }
} }

View File

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

View File

@@ -1,14 +1,12 @@
namespace PimpMyRideContracts.Exceptions; using Microsoft.Extensions.Localization;
using PimpMyRideContracts.Resources;
public class ElementExistsException : Exception namespace PimpMyRideContracts.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 ParamName { get; private set; } = paramName;
public string ParamValue { get; private set; } public string ParamValue { get; private set; } = paramValue;
public ElementExistsException(string paramName, string paramValue) : base($"There is already an element with value{paramValue} of parameter {paramName}")
{
ParamName = paramName;
ParamValue = paramValue;
}
} }

View File

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

View File

@@ -1,6 +1,8 @@
namespace PimpMyRideContracts.Exceptions; using Microsoft.Extensions.Localization;
using PimpMyRideContracts.Resources;
public class IncorrectDatesException : Exception namespace PimpMyRideContracts.Exceptions;
{
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}") { } 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 PimpMyRideContracts.Exceptions;
public class NullListException : Exception
{
public NullListException() : base("The returned list is null") { }
}

View File

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

View File

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

View File

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

View File

@@ -1,8 +1,12 @@
namespace PimpMyRideContracts.Infrastructure.ServiceConfiguration; using System.Globalization;
namespace PimpMyRideContracts.Infrastructure.ServiceConfiguration;
public class ServiceConfiguration public class ServiceConfiguration
{ {
public virtual string Type => nameof(ServiceConfiguration); public virtual string Type => nameof(ServiceConfiguration);
public double Rate { get; set; } public double Rate { get; set; }
public string CultureName { get; set; } = CultureInfo.CurrentCulture.Name;
} }

View File

@@ -9,6 +9,30 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.3.0" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.3.0" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.3.0" />
<PackageReference Include="Microsoft.Extensions.Localization.Abstractions" Version="9.0.5" />
</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="PimpMyRideBusinessLogic" />
<InternalsVisibleTo Include="PimpMyRideDatabase" />
<InternalsVisibleTo Include="PimpMyRideWebApi" />
<InternalsVisibleTo Include="PimpMyRideTest" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -0,0 +1,387 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace PimpMyRideContracts.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("PimpMyRideContracts.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 AdapterMessageElementDeletedException {
get {
return ResourceManager.GetString("AdapterMessageElementDeletedException", resourceCulture);
}
}
/// <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 DocumentDocCaptionCar {
get {
return ResourceManager.GetString("DocumentDocCaptionCar", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Клиент.
/// </summary>
internal static string DocumentDocCaptionClient {
get {
return ResourceManager.GetString("DocumentDocCaptionClient", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Автомобили по клиентам.
/// </summary>
internal static string DocumentDocHeader {
get {
return ResourceManager.GetString("DocumentDocHeader", 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 DocumentExcelCaptionMaterial {
get {
return ResourceManager.GetString("DocumentExcelCaptionMaterial", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Сумма.
/// </summary>
internal static string DocumentExcelCaptionSum {
get {
return ResourceManager.GetString("DocumentExcelCaptionSum", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Всего.
/// </summary>
internal static string DocumentExcelCaptionTotal {
get {
return ResourceManager.GetString("DocumentExcelCaptionTotal", 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 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 ValidationExceptionMessageIncorrectPhoneNumber {
get {
return ResourceManager.GetString("ValidationExceptionMessageIncorrectPhoneNumber", 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 ValidationExceptionMessageNoMaterialsInService {
get {
return ResourceManager.GetString("ValidationExceptionMessageNoMaterialsInService", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на В заказе должна быть хотя бы одна услуга.
/// </summary>
internal static string ValidationExceptionMessageNoServicesInOrder {
get {
return ResourceManager.GetString("ValidationExceptionMessageNoServicesInOrder", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле {0} не является типом уникального идентификатора.
/// </summary>
internal static string ValidationExceptionMessageNotAnId {
get {
return ResourceManager.GetString("ValidationExceptionMessageNotAnId", 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="AdapterMessageElementDeletedException" xml:space="preserve">
<value>Element von Daten: {0} wurde gelöscht</value>
</data>
<data name="AdapterMessageElementNotFoundException" xml:space="preserve">
<value>Nicht gefundenes Element durch Daten: {0}</value>
</data>
<data name="AdapterMessageEmptyDate" xml:space="preserve">
<value>Die Daten sind leer</value>
</data>
<data name="AdapterMessageIncorrectDatesException" xml:space="preserve">
<value>Falsche Daten: {0}</value>
</data>
<data name="AdapterMessageInvalidOperationException" xml:space="preserve">
<value>Fehler bei der Verarbeitung der Daten: {0}</value>
</data>
<data name="AdapterMessageStorageException" xml:space="preserve">
<value>Fehler beim Arbeiten mit dem Datenspeicher: {0}</value>
</data>
<data name="AdapterMessageValidationException" xml:space="preserve">
<value>Falsche Daten übermittelt: {0}</value>
</data>
<data name="DocumentDocCaptionCar" xml:space="preserve">
<value>Auto</value>
</data>
<data name="DocumentDocCaptionClient" xml:space="preserve">
<value>Kunde</value>
</data>
<data name="DocumentDocHeader" xml:space="preserve">
<value>Autos vom Kunden</value>
</data>
<data name="DocumentDocSubHeader" xml:space="preserve">
<value>Generiert am Datum {0}</value>
</data>
<data name="DocumentExcelCaptionCount" xml:space="preserve">
<value>Zählen</value>
</data>
<data name="DocumentExcelCaptionDate" xml:space="preserve">
<value>Datum</value>
</data>
<data name="DocumentExcelCaptionMaterial" xml:space="preserve">
<value>Material</value>
</data>
<data name="DocumentExcelCaptionSum" xml:space="preserve">
<value>Summe</value>
</data>
<data name="DocumentExcelCaptionTotal" xml:space="preserve">
<value>Gesamt</value>
</data>
<data name="DocumentExcelHeader" xml:space="preserve">
<value>Bestellungen für den Zeitraum</value>
</data>
<data name="DocumentExcelSubHeader" xml:space="preserve">
<value>von {0} bis {1}</value>
</data>
<data name="DocumentPdfDiagramCaption" xml:space="preserve">
<value>Dienstleistungen</value>
</data>
<data name="DocumentPdfHeader" xml:space="preserve">
<value>Leistungserklärung</value>
</data>
<data name="DocumentPdfSubHeader" xml:space="preserve">
<value>für den Zeitraum vom {0} bis {1}</value>
</data>
<data name="ElementDeletedExceptionMessage" xml:space="preserve">
<value>Ein gelöschtes Element (ID: {0}) kann nicht geändert werden.</value>
</data>
<data name="ElementExistsExceptionMessage" xml:space="preserve">
<value>Es gibt bereits ein Element mit dem Wert {0} des Parameters {1}</value>
</data>
<data name="ElementNotFoundExceptionMessage" xml:space="preserve">
<value>Element bei Wert = {0} nicht gefunden</value>
</data>
<data name="IncorrectDatesExceptionMessage" xml:space="preserve">
<value>Das Enddatum muss nach dem Startdatum liegen. Startdatum: {0}. Enddatum: {1}</value>
</data>
<data name="StorageExceptionMessage" xml:space="preserve">
<value>Fehler beim Arbeiten im Speicher: {0}</value>
</data>
<data name="ValidationExceptionMessageEmploymentDateAndBirthDate" xml:space="preserve">
<value>Das Beschäftigungsdatum darf nicht vor dem Geburtsdatum liegen ({0}, {1})</value>
</data>
<data name="ValidationExceptionMessageEmptyField" xml:space="preserve">
<value>Der Wert im Feld {0} ist leer</value>
</data>
<data name="ValidationExceptionMessageIncorrectPhoneNumber" xml:space="preserve">
<value>Der Wert im Feld „Telefonnummer“ ist keine Telefonnummer.</value>
</data>
<data name="ValidationExceptionMessageLessOrEqualZero" xml:space="preserve">
<value>Der Wert im Feld {0} ist kleiner oder gleich 0</value>
</data>
<data name="ValidationExceptionMessageMinorsBirthDate" xml:space="preserve">
<value>Minderjährige können nicht eingestellt werden (Geburtsdatum = {0})</value>
</data>
<data name="ValidationExceptionMessageMinorsEmploymentDate" xml:space="preserve">
<value>Minderjährige können nicht eingestellt werden (Beschäftigungsdatum: {0}, Geburtsdatum: {1})</value>
</data>
<data name="ValidationExceptionMessageNoMaterialsInService" xml:space="preserve">
<value>Es muss mindestens ein Artikel im Service vorhanden sein</value>
</data>
<data name="ValidationExceptionMessageNoServicesInOrder" xml:space="preserve">
<value>Es muss mindestens ein Artikel bestellt werden</value>
</data>
<data name="ValidationExceptionMessageNotAnId" xml:space="preserve">
<value>Der Wert im Feld {0} ist kein eindeutiger Kennungstyp.</value>
</data>
<data name="ValidationExceptionMessageNotInitialized" xml:space="preserve">
<value>Der Wert im Feld {0} ist nicht initialisiert</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="AdapterMessageElementDeletedException" xml:space="preserve">
<value>Element by data: {0} was deleted</value>
</data>
<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="DocumentDocCaptionCar" xml:space="preserve">
<value>Car</value>
</data>
<data name="DocumentDocCaptionClient" xml:space="preserve">
<value>Client</value>
</data>
<data name="DocumentDocHeader" xml:space="preserve">
<value>Cars by Client</value>
</data>
<data name="DocumentDocSubHeader" xml:space="preserve">
<value>Generated on 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="DocumentExcelCaptionMaterial" xml:space="preserve">
<value>Material</value>
</data>
<data name="DocumentExcelCaptionSum" xml:space="preserve">
<value>Sum</value>
</data>
<data name="DocumentExcelCaptionTotal" xml:space="preserve">
<value>Total</value>
</data>
<data name="DocumentExcelHeader" xml:space="preserve">
<value>Orders 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>Services</value>
</data>
<data name="DocumentPdfHeader" xml:space="preserve">
<value>Services statement</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="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="ValidationExceptionMessageIncorrectPhoneNumber" xml:space="preserve">
<value>The value in the Phone Number field is not a phone number.</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="ValidationExceptionMessageNoMaterialsInService" xml:space="preserve">
<value>There must be at least one item on service</value>
</data>
<data name="ValidationExceptionMessageNoServicesInOrder" xml:space="preserve">
<value>There must be at least one item on order</value>
</data>
<data name="ValidationExceptionMessageNotAnId" 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="AdapterMessageElementDeletedException" xml:space="preserve">
<value>Элемент по данным: {0} был удален</value>
</data>
<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="DocumentDocCaptionCar" xml:space="preserve">
<value>Автомобиль</value>
</data>
<data name="DocumentDocCaptionClient" xml:space="preserve">
<value>Клиент</value>
</data>
<data name="DocumentDocHeader" 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="DocumentExcelCaptionMaterial" xml:space="preserve">
<value>Материал</value>
</data>
<data name="DocumentExcelCaptionSum" xml:space="preserve">
<value>Сумма</value>
</data>
<data name="DocumentExcelCaptionTotal" 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="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="ValidationExceptionMessageIncorrectPhoneNumber" 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="ValidationExceptionMessageNoMaterialsInService" xml:space="preserve">
<value>В услуге должен быть хотя бы один товар</value>
</data>
<data name="ValidationExceptionMessageNoServicesInOrder" xml:space="preserve">
<value>В заказе должна быть хотя бы одна услуга</value>
</data>
<data name="ValidationExceptionMessageNotAnId" xml:space="preserve">
<value>Значение в поле {0} не является типом уникального идентификатора</value>
</data>
<data name="ValidationExceptionMessageNotInitialized" xml:space="preserve">
<value>Значение в поле {0} не проиницализировано</value>
</data>
</root>

View File

@@ -2,7 +2,7 @@
namespace PimpMyRideContracts.StoragesContracts; namespace PimpMyRideContracts.StoragesContracts;
public interface ICarStorageContract internal interface ICarStorageContract
{ {
List<CarDataModel> GetList(string? clientId = null, string? make = null, string? model = null); List<CarDataModel> GetList(string? clientId = null, string? make = null, string? model = null);

View File

@@ -2,7 +2,7 @@
namespace PimpMyRideContracts.StoragesContracts; namespace PimpMyRideContracts.StoragesContracts;
public interface IClientStorageContract internal interface IClientStorageContract
{ {
List<ClientDataModel> GetList(); List<ClientDataModel> GetList();

View File

@@ -3,7 +3,7 @@ using PimpMyRideContracts.Enums;
namespace PimpMyRideContracts.StoragesContracts; namespace PimpMyRideContracts.StoragesContracts;
public interface IMaterialStorageContracts internal interface IMaterialStorageContracts
{ {
List<MaterialDataModel> GetList(MaterialType? materialType = MaterialType.None); List<MaterialDataModel> GetList(MaterialType? materialType = MaterialType.None);

View File

@@ -2,7 +2,7 @@
namespace PimpMyRideContracts.StoragesContracts; namespace PimpMyRideContracts.StoragesContracts;
public interface IOrderStorageContract internal interface IOrderStorageContract
{ {
List<OrderDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? carId = null); List<OrderDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? carId = null);

View File

@@ -3,7 +3,7 @@ using PimpMyRideContracts.Enums;
namespace PimpMyRideContracts.StoragesContracts; namespace PimpMyRideContracts.StoragesContracts;
public interface IServiceStorageContracts internal interface IServiceStorageContracts
{ {
List<ServiceDataModel> GetList(string? workerId = null, WorkType? workType = WorkType.None); List<ServiceDataModel> GetList(string? workerId = null, WorkType? workType = WorkType.None);

View File

@@ -3,7 +3,7 @@ using PimpMyRideContracts.Enums;
namespace PimpMyRideContracts.StoragesContracts; namespace PimpMyRideContracts.StoragesContracts;
public interface IWorkerStorageContract internal interface IWorkerStorageContract
{ {
List<WorkerDataModel> GetList(bool onlyActive = true, SpecialityType? specialityType = SpecialityType.None, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null); List<WorkerDataModel> GetList(bool onlyActive = true, SpecialityType? specialityType = SpecialityType.None, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null);

View File

@@ -1,8 +1,10 @@
using AutoMapper; using AutoMapper;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql; using Npgsql;
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Resources;
using PimpMyRideContracts.StoragesContracts; using PimpMyRideContracts.StoragesContracts;
using PimpMyRideDatabase.Models; using PimpMyRideDatabase.Models;
@@ -12,8 +14,9 @@ internal class CarStorageContract : ICarStorageContract
{ {
private readonly PimpMyRideDbContext _dbContext; private readonly PimpMyRideDbContext _dbContext;
private readonly Mapper _mapper; private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public CarStorageContract(PimpMyRideDbContext pimpMyRideDbContext) public CarStorageContract(PimpMyRideDbContext pimpMyRideDbContext, IStringLocalizer<Messages> localizer)
{ {
_dbContext = pimpMyRideDbContext; _dbContext = pimpMyRideDbContext;
var config = new MapperConfiguration(cfg => var config = new MapperConfiguration(cfg =>
@@ -23,6 +26,7 @@ internal class CarStorageContract : ICarStorageContract
cfg.CreateMap<CarDataModel, Car>(); cfg.CreateMap<CarDataModel, Car>();
}); });
_mapper = new Mapper(config); _mapper = new Mapper(config);
_localizer = localizer;
} }
public List<CarDataModel> GetList(string? clientId = null, string? make = null, string? model = null) public List<CarDataModel> GetList(string? clientId = null, string? make = null, string? model = null)
@@ -47,7 +51,7 @@ internal class CarStorageContract : ICarStorageContract
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -60,7 +64,7 @@ internal class CarStorageContract : ICarStorageContract
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -73,7 +77,7 @@ internal class CarStorageContract : ICarStorageContract
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -86,7 +90,7 @@ internal class CarStorageContract : ICarStorageContract
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -100,17 +104,22 @@ internal class CarStorageContract : ICarStorageContract
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict") catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", carDataModel.Id); throw new ElementExistsException("Id", carDataModel.Id, _localizer);
} }
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Cars_StateNumber" }) catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Cars_StateNumber" })
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new ElementExistsException("StateNumber", carDataModel.StateNumber); throw new ElementExistsException("StateNumber", carDataModel.StateNumber, _localizer);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "PK_Cars" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", carDataModel.Id, _localizer);
} }
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -118,7 +127,7 @@ internal class CarStorageContract : ICarStorageContract
{ {
try try
{ {
var element = GetCarById(carDataModel.Id) ?? throw new ElementNotFoundException(carDataModel.Id); var element = GetCarById(carDataModel.Id) ?? throw new ElementNotFoundException(carDataModel.Id, _localizer);
_dbContext.Cars.Update(_mapper.Map(carDataModel, element)); _dbContext.Cars.Update(_mapper.Map(carDataModel, element));
_dbContext.SaveChanges(); _dbContext.SaveChanges();
} }
@@ -130,12 +139,12 @@ internal class CarStorageContract : ICarStorageContract
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Cars_StateNumber" }) catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Cars_StateNumber" })
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new ElementExistsException("StateNumber", carDataModel.StateNumber); throw new ElementExistsException("StateNumber", carDataModel.StateNumber, _localizer);
} }
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -143,7 +152,7 @@ internal class CarStorageContract : ICarStorageContract
{ {
try try
{ {
var element = GetCarById(id) ?? throw new ElementNotFoundException(id); var element = GetCarById(id) ?? throw new ElementNotFoundException(id, _localizer);
_dbContext.Cars.Remove(element); _dbContext.Cars.Remove(element);
_dbContext.SaveChanges(); _dbContext.SaveChanges();
} }
@@ -155,7 +164,7 @@ internal class CarStorageContract : ICarStorageContract
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }

View File

@@ -1,8 +1,10 @@
using AutoMapper; using AutoMapper;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql; using Npgsql;
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Resources;
using PimpMyRideContracts.StoragesContracts; using PimpMyRideContracts.StoragesContracts;
using PimpMyRideDatabase.Models; using PimpMyRideDatabase.Models;
@@ -12,8 +14,9 @@ internal class ClientStorageContract : IClientStorageContract
{ {
private readonly PimpMyRideDbContext _dbContext; private readonly PimpMyRideDbContext _dbContext;
private readonly Mapper _mapper; private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public ClientStorageContract(PimpMyRideDbContext pimpMyRideDbContext) public ClientStorageContract(PimpMyRideDbContext pimpMyRideDbContext, IStringLocalizer<Messages> localizer)
{ {
_dbContext = pimpMyRideDbContext; _dbContext = pimpMyRideDbContext;
var config = new MapperConfiguration(cfg => var config = new MapperConfiguration(cfg =>
@@ -22,6 +25,7 @@ internal class ClientStorageContract : IClientStorageContract
cfg.CreateMap<ClientDataModel, Client>(); cfg.CreateMap<ClientDataModel, Client>();
}); });
_mapper = new Mapper(config); _mapper = new Mapper(config);
_localizer = localizer;
} }
public List<ClientDataModel> GetList() public List<ClientDataModel> GetList()
@@ -33,7 +37,7 @@ internal class ClientStorageContract : IClientStorageContract
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -47,7 +51,7 @@ internal class ClientStorageContract : IClientStorageContract
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -60,7 +64,7 @@ internal class ClientStorageContract : IClientStorageContract
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -74,7 +78,7 @@ internal class ClientStorageContract : IClientStorageContract
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -88,17 +92,22 @@ internal class ClientStorageContract : IClientStorageContract
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict") catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", clientDataModel.Id); throw new ElementExistsException("Id", clientDataModel.Id, _localizer);
} }
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Clients_PhoneNumber" }) catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Clients_PhoneNumber" })
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PhoneNumber", clientDataModel.PhoneNumber); throw new ElementExistsException("PhoneNumber", clientDataModel.PhoneNumber, _localizer);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "PK_Clients" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", clientDataModel.Id, _localizer);
} }
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -107,7 +116,7 @@ internal class ClientStorageContract : IClientStorageContract
{ {
try try
{ {
var element = GetClientById(clientDataModel.Id) ?? throw new ElementNotFoundException(clientDataModel.Id); var element = GetClientById(clientDataModel.Id) ?? throw new ElementNotFoundException(clientDataModel.Id, _localizer);
_dbContext.Clients.Update(_mapper.Map(clientDataModel, element)); _dbContext.Clients.Update(_mapper.Map(clientDataModel, element));
_dbContext.SaveChanges(); _dbContext.SaveChanges();
} }
@@ -119,12 +128,12 @@ internal class ClientStorageContract : IClientStorageContract
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Clients_PhoneNumber" }) catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Clients_PhoneNumber" })
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PhoneNumber", clientDataModel.PhoneNumber); throw new ElementExistsException("PhoneNumber", clientDataModel.PhoneNumber, _localizer);
} }
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -132,7 +141,7 @@ internal class ClientStorageContract : IClientStorageContract
{ {
try try
{ {
var element = GetClientById(id) ?? throw new ElementNotFoundException(id); var element = GetClientById(id) ?? throw new ElementNotFoundException(id, _localizer);
var cars = _dbContext.Cars.Where(c => c.ClientId == id).ToList(); var cars = _dbContext.Cars.Where(c => c.ClientId == id).ToList();
foreach (var car in cars) foreach (var car in cars)
{ {
@@ -149,7 +158,7 @@ internal class ClientStorageContract : IClientStorageContract
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }

View File

@@ -1,9 +1,11 @@
using AutoMapper; using AutoMapper;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql; using Npgsql;
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Enums; using PimpMyRideContracts.Enums;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Resources;
using PimpMyRideContracts.StoragesContracts; using PimpMyRideContracts.StoragesContracts;
using PimpMyRideDatabase.Models; using PimpMyRideDatabase.Models;
@@ -13,8 +15,9 @@ internal class MaterialStorageContracts : IMaterialStorageContracts
{ {
private readonly PimpMyRideDbContext _dbContext; private readonly PimpMyRideDbContext _dbContext;
private readonly Mapper _mapper; private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public MaterialStorageContracts(PimpMyRideDbContext pimpMyRideDbContext) public MaterialStorageContracts(PimpMyRideDbContext pimpMyRideDbContext, IStringLocalizer<Messages> localizer)
{ {
_dbContext = pimpMyRideDbContext; _dbContext = pimpMyRideDbContext;
var config = new MapperConfiguration(cfg => var config = new MapperConfiguration(cfg =>
@@ -24,6 +27,7 @@ internal class MaterialStorageContracts : IMaterialStorageContracts
cfg.CreateMap<MaterialHistory, MaterialHistoryDataModel>(); cfg.CreateMap<MaterialHistory, MaterialHistoryDataModel>();
}); });
_mapper = new Mapper(config); _mapper = new Mapper(config);
_localizer = localizer;
} }
public List<MaterialDataModel> GetList(MaterialType? materialType = MaterialType.None) public List<MaterialDataModel> GetList(MaterialType? materialType = MaterialType.None)
@@ -40,7 +44,7 @@ internal class MaterialStorageContracts : IMaterialStorageContracts
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -53,7 +57,7 @@ internal class MaterialStorageContracts : IMaterialStorageContracts
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -66,7 +70,7 @@ internal class MaterialStorageContracts : IMaterialStorageContracts
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -79,7 +83,7 @@ internal class MaterialStorageContracts : IMaterialStorageContracts
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -93,17 +97,22 @@ internal class MaterialStorageContracts : IMaterialStorageContracts
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict") catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", materialDataModel.Id); throw new ElementExistsException("Id", materialDataModel.Id, _localizer);
} }
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Materials_Description_IsDeleted" }) catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Materials_Description_IsDeleted" })
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Description", materialDataModel.Description); throw new ElementExistsException("Description", materialDataModel.Description, _localizer);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "PK_Materials" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", materialDataModel.Id, _localizer);
} }
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -114,7 +123,7 @@ internal class MaterialStorageContracts : IMaterialStorageContracts
var transaction = _dbContext.Database.BeginTransaction(); var transaction = _dbContext.Database.BeginTransaction();
try try
{ {
var element = GetMaterialById(materialDataModel.Id) ?? throw new ElementNotFoundException(materialDataModel.Id); var element = GetMaterialById(materialDataModel.Id) ?? throw new ElementNotFoundException(materialDataModel.Id, _localizer);
if (element.UnitCost != materialDataModel.UnitCost) if (element.UnitCost != materialDataModel.UnitCost)
{ {
_dbContext.MaterialHistories.Add(new MaterialHistory() { MaterialId = element.Id, OldPrice = element.UnitCost }); _dbContext.MaterialHistories.Add(new MaterialHistory() { MaterialId = element.Id, OldPrice = element.UnitCost });
@@ -138,7 +147,7 @@ internal class MaterialStorageContracts : IMaterialStorageContracts
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -146,7 +155,7 @@ internal class MaterialStorageContracts : IMaterialStorageContracts
{ {
try try
{ {
var element = GetMaterialById(id) ?? throw new ElementNotFoundException(id); var element = GetMaterialById(id) ?? throw new ElementNotFoundException(id, _localizer);
_dbContext.Materials.Remove(element); _dbContext.Materials.Remove(element);
_dbContext.SaveChanges(); _dbContext.SaveChanges();
} }
@@ -158,7 +167,7 @@ internal class MaterialStorageContracts : IMaterialStorageContracts
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }

View File

@@ -1,7 +1,9 @@
using AutoMapper; using AutoMapper;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Resources;
using PimpMyRideContracts.StoragesContracts; using PimpMyRideContracts.StoragesContracts;
using PimpMyRideDatabase.Models; using PimpMyRideDatabase.Models;
@@ -11,8 +13,9 @@ internal class OrderStorageContract : IOrderStorageContract
{ {
private readonly PimpMyRideDbContext _dbContext; private readonly PimpMyRideDbContext _dbContext;
private readonly Mapper _mapper; private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public OrderStorageContract(PimpMyRideDbContext dbContext) public OrderStorageContract(PimpMyRideDbContext dbContext, IStringLocalizer<Messages> localizer)
{ {
_dbContext = dbContext; _dbContext = dbContext;
var config = new MapperConfiguration(cfg => var config = new MapperConfiguration(cfg =>
@@ -28,6 +31,7 @@ internal class OrderStorageContract : IOrderStorageContract
.ForMember(x => x.OrderServices, x => x.MapFrom(src => src.Services)); .ForMember(x => x.OrderServices, x => x.MapFrom(src => src.Services));
}); });
_mapper = new Mapper(config); _mapper = new Mapper(config);
_localizer = localizer;
} }
public List<OrderDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? carId = null) public List<OrderDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? carId = null)
@@ -48,7 +52,7 @@ internal class OrderStorageContract : IOrderStorageContract
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -61,7 +65,7 @@ internal class OrderStorageContract : IOrderStorageContract
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -74,7 +78,7 @@ internal class OrderStorageContract : IOrderStorageContract
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -88,7 +92,7 @@ internal class OrderStorageContract : IOrderStorageContract
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -96,10 +100,10 @@ internal class OrderStorageContract : IOrderStorageContract
{ {
try try
{ {
var element = GetOrderById(id) ?? throw new ElementNotFoundException(id); var element = GetOrderById(id) ?? throw new ElementNotFoundException(id, _localizer);
if (element.IsCancel) if (element.IsCancel)
{ {
throw new ElementDeletedException(id); throw new ElementDeletedException(id, _localizer);
} }
element.IsCancel = true; element.IsCancel = true;
_dbContext.SaveChanges(); _dbContext.SaveChanges();
@@ -112,7 +116,7 @@ internal class OrderStorageContract : IOrderStorageContract
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }

View File

@@ -1,8 +1,10 @@
using AutoMapper; using AutoMapper;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Enums; using PimpMyRideContracts.Enums;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Resources;
using PimpMyRideContracts.StoragesContracts; using PimpMyRideContracts.StoragesContracts;
using PimpMyRideDatabase.Models; using PimpMyRideDatabase.Models;
@@ -12,8 +14,9 @@ internal class ServiceStorageContracts : IServiceStorageContracts
{ {
private readonly PimpMyRideDbContext _dbContext; private readonly PimpMyRideDbContext _dbContext;
private readonly Mapper _mapper; private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public ServiceStorageContracts(PimpMyRideDbContext dbContext) public ServiceStorageContracts(PimpMyRideDbContext dbContext, IStringLocalizer<Messages> localizer)
{ {
_dbContext = dbContext; _dbContext = dbContext;
var config = new MapperConfiguration(cfg => var config = new MapperConfiguration(cfg =>
@@ -42,6 +45,7 @@ internal class ServiceStorageContracts : IServiceStorageContracts
.ForMember(dest => dest.Configuration, opt => opt.MapFrom(src => src.ConfigurationModel)); .ForMember(dest => dest.Configuration, opt => opt.MapFrom(src => src.ConfigurationModel));
}); });
_mapper = new Mapper(config); _mapper = new Mapper(config);
_localizer = localizer;
} }
public List<ServiceDataModel> GetList(string? workerId = null, WorkType? workType = WorkType.None) public List<ServiceDataModel> GetList(string? workerId = null, WorkType? workType = WorkType.None)
@@ -62,7 +66,7 @@ internal class ServiceStorageContracts : IServiceStorageContracts
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -76,7 +80,7 @@ internal class ServiceStorageContracts : IServiceStorageContracts
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -89,7 +93,7 @@ internal class ServiceStorageContracts : IServiceStorageContracts
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -103,7 +107,7 @@ internal class ServiceStorageContracts : IServiceStorageContracts
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -111,7 +115,7 @@ internal class ServiceStorageContracts : IServiceStorageContracts
{ {
try try
{ {
var element = GetServiceById(id) ?? throw new ElementNotFoundException(id); var element = GetServiceById(id) ?? throw new ElementNotFoundException(id, _localizer);
_dbContext.Services.Remove(element); _dbContext.Services.Remove(element);
_dbContext.SaveChanges(); _dbContext.SaveChanges();
} }
@@ -123,7 +127,7 @@ internal class ServiceStorageContracts : IServiceStorageContracts
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }

View File

@@ -1,8 +1,11 @@
using AutoMapper; using AutoMapper;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Enums; using PimpMyRideContracts.Enums;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Resources;
using PimpMyRideContracts.StoragesContracts; using PimpMyRideContracts.StoragesContracts;
using PimpMyRideDatabase.Models; using PimpMyRideDatabase.Models;
@@ -12,8 +15,9 @@ internal class WorkerStorageContract : IWorkerStorageContract
{ {
private readonly PimpMyRideDbContext _dbContext; private readonly PimpMyRideDbContext _dbContext;
private readonly Mapper _mapper; private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public WorkerStorageContract(PimpMyRideDbContext dbContext) public WorkerStorageContract(PimpMyRideDbContext dbContext, IStringLocalizer<Messages> localizer)
{ {
_dbContext = dbContext; _dbContext = dbContext;
var config = new MapperConfiguration(cfg => var config = new MapperConfiguration(cfg =>
@@ -21,6 +25,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
cfg.AddMaps(typeof(Worker)); cfg.AddMaps(typeof(Worker));
}); });
_mapper = new Mapper(config); _mapper = new Mapper(config);
_localizer = localizer;
} }
public List<WorkerDataModel> GetList(bool onlyActive = true, SpecialityType? specialityType = SpecialityType.None, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null) public List<WorkerDataModel> GetList(bool onlyActive = true, SpecialityType? specialityType = SpecialityType.None, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null)
@@ -51,7 +56,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -64,7 +69,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -77,7 +82,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -91,12 +96,17 @@ internal class WorkerStorageContract : IWorkerStorageContract
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict") catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{ {
_dbContext.ChangeTracker.Clear(); _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) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -104,7 +114,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
{ {
try 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.Workers.Update(_mapper.Map(workerDataModel, element));
_dbContext.SaveChanges(); _dbContext.SaveChanges();
} }
@@ -116,7 +126,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }
@@ -124,7 +134,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
{ {
try try
{ {
var element = GetWorkerById(id) ?? throw new ElementNotFoundException(id); var element = GetWorkerById(id) ?? throw new ElementNotFoundException(id, _localizer);
element.IsDeleted = true; element.IsDeleted = true;
_dbContext.SaveChanges(); _dbContext.SaveChanges();
} }
@@ -136,7 +146,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
catch (Exception ex) catch (Exception ex)
{ {
_dbContext.ChangeTracker.Clear(); _dbContext.ChangeTracker.Clear();
throw new StorageException(ex); throw new StorageException(ex, _localizer);
} }
} }

View File

@@ -14,8 +14,6 @@ internal class PimpMyRideDbContext : DbContext
public PimpMyRideDbContext(IConfigurationDatabase configurationDatabase) public PimpMyRideDbContext(IConfigurationDatabase configurationDatabase)
{ {
_configurationDatabase = configurationDatabase; _configurationDatabase = configurationDatabase;
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);
} }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

View File

@@ -5,6 +5,7 @@ using PimpMyRideContracts.BusinessLogicsContracts;
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.StoragesContracts; using PimpMyRideContracts.StoragesContracts;
using PimpMyRideTest.Infrastructure;
namespace PimpMyRideTest.BusinessLogicsContractsTests; namespace PimpMyRideTest.BusinessLogicsContractsTests;
@@ -18,7 +19,7 @@ internal class CarBusinessLogicContractTests
public void OneTimeSetUp() public void OneTimeSetUp()
{ {
_carStorageContract = new Mock<ICarStorageContract>(); _carStorageContract = new Mock<ICarStorageContract>();
_carBusinessLogicContract = new CarBusinessLogicContract(_carStorageContract.Object, new Mock<ILogger>().Object); _carBusinessLogicContract = new CarBusinessLogicContract(_carStorageContract.Object, StringLocalizerMockCreator.GetObject(), new Mock<ILogger>().Object);
} }
[TearDown] [TearDown]
@@ -57,17 +58,10 @@ internal class CarBusinessLogicContractTests
_carStorageContract.Verify(x => x.GetList(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once); _carStorageContract.Verify(x => x.GetList(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
} }
[Test]
public void GetAllCars_ReturnNull_ThrowException_Test()
{
Assert.That(() => _carBusinessLogicContract.GetAllCars(), Throws.TypeOf<NullListException>());
_carStorageContract.Verify(x => x.GetList(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test] [Test]
public void GetAllCars_StorageThrowError_ThrowException_Test() public void GetAllCars_StorageThrowError_ThrowException_Test()
{ {
_carStorageContract.Setup(x => x.GetList(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException())); _carStorageContract.Setup(x => x.GetList(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _carBusinessLogicContract.GetAllCars(), Throws.TypeOf<StorageException>()); Assert.That(() => _carBusinessLogicContract.GetAllCars(), Throws.TypeOf<StorageException>());
_carStorageContract.Verify(x => x.GetList(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once); _carStorageContract.Verify(x => x.GetList(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
@@ -121,17 +115,10 @@ internal class CarBusinessLogicContractTests
_carStorageContract.Verify(x => x.GetList(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never); _carStorageContract.Verify(x => x.GetList(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
} }
[Test]
public void GetAllCarsByClient_ReturnNull_ThrowException_Test()
{
Assert.That(() => _carBusinessLogicContract.GetAllCarsByClient(Guid.NewGuid().ToString()), Throws.TypeOf<NullListException>());
_carStorageContract.Verify(x => x.GetList(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test] [Test]
public void GetAllCarsByClient_StorageThrowError_ThrowException_Test() public void GetAllCarsByClient_StorageThrowError_ThrowException_Test()
{ {
_carStorageContract.Setup(x => x.GetList(It.IsAny<string?>(), It.IsAny<string?>(), It.IsAny<string?>())).Throws(new StorageException(new InvalidOperationException())); _carStorageContract.Setup(x => x.GetList(It.IsAny<string?>(), It.IsAny<string?>(), It.IsAny<string?>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _carBusinessLogicContract.GetAllCarsByClient(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>()); Assert.That(() => _carBusinessLogicContract.GetAllCarsByClient(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_carStorageContract.Verify(x => x.GetList(It.IsAny<string?>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Once); _carStorageContract.Verify(x => x.GetList(It.IsAny<string?>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Once);
@@ -181,17 +168,10 @@ internal class CarBusinessLogicContractTests
_carStorageContract.Verify(x => x.GetList(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never); _carStorageContract.Verify(x => x.GetList(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
} }
[Test]
public void GetAllCarsByMake_ReturnNull_ThrowException_Test()
{
Assert.That(() => _carBusinessLogicContract.GetAllCarsByMake("Porsche", "911"), Throws.TypeOf<NullListException>());
_carStorageContract.Verify(x => x.GetList(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test] [Test]
public void GetAllCarsByMake_StorageThrowError_ThrowException_Test() public void GetAllCarsByMake_StorageThrowError_ThrowException_Test()
{ {
_carStorageContract.Setup(x => x.GetList(It.IsAny<string?>(), It.IsAny<string?>(), It.IsAny<string?>())).Throws(new StorageException(new InvalidOperationException())); _carStorageContract.Setup(x => x.GetList(It.IsAny<string?>(), It.IsAny<string?>(), It.IsAny<string?>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _carBusinessLogicContract.GetAllCarsByMake("Porsche", "911"), Throws.TypeOf<StorageException>()); Assert.That(() => _carBusinessLogicContract.GetAllCarsByMake("Porsche", "911"), Throws.TypeOf<StorageException>());
_carStorageContract.Verify(x => x.GetList(It.IsAny<string?>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Once); _carStorageContract.Verify(x => x.GetList(It.IsAny<string?>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Once);
@@ -253,8 +233,8 @@ internal class CarBusinessLogicContractTests
[Test] [Test]
public void GetCarByData_StorageThrowError_ThrowException_Test() public void GetCarByData_StorageThrowError_ThrowException_Test()
{ {
_carStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException())); _carStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_carStorageContract.Setup(x => x.GetElementByStateNumber(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException())); _carStorageContract.Setup(x => x.GetElementByStateNumber(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _carBusinessLogicContract.GetCarByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>()); Assert.That(() => _carBusinessLogicContract.GetCarByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _carBusinessLogicContract.GetCarByData("A911MP"), Throws.TypeOf<StorageException>()); Assert.That(() => _carBusinessLogicContract.GetCarByData("A911MP"), Throws.TypeOf<StorageException>());
@@ -283,7 +263,7 @@ internal class CarBusinessLogicContractTests
[Test] [Test]
public void InsertCar_RecordWithExistsData_ThrowException_Test() public void InsertCar_RecordWithExistsData_ThrowException_Test()
{ {
_carStorageContract.Setup(x => x.AddElement(It.IsAny<CarDataModel>())).Throws(new ElementExistsException("Data", "Data")); _carStorageContract.Setup(x => x.AddElement(It.IsAny<CarDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
Assert.That(() => _carBusinessLogicContract.InsertCar(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Porsche", "911", "A911MP")), Throws.TypeOf<ElementExistsException>()); Assert.That(() => _carBusinessLogicContract.InsertCar(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Porsche", "911", "A911MP")), Throws.TypeOf<ElementExistsException>());
_carStorageContract.Verify(x => x.AddElement(It.IsAny<CarDataModel>()), Times.Once); _carStorageContract.Verify(x => x.AddElement(It.IsAny<CarDataModel>()), Times.Once);
@@ -306,7 +286,7 @@ internal class CarBusinessLogicContractTests
[Test] [Test]
public void InsertCar_StorageThrowError_ThrowException_Test() public void InsertCar_StorageThrowError_ThrowException_Test()
{ {
_carStorageContract.Setup(x => x.AddElement(It.IsAny<CarDataModel>())).Throws(new StorageException(new InvalidOperationException())); _carStorageContract.Setup(x => x.AddElement(It.IsAny<CarDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _carBusinessLogicContract.InsertCar(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Porsche", "911", "A911MP")), Throws.TypeOf<StorageException>()); Assert.That(() => _carBusinessLogicContract.InsertCar(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Porsche", "911", "A911MP")), Throws.TypeOf<StorageException>());
_carStorageContract.Verify(x => x.AddElement(It.IsAny<CarDataModel>()), Times.Once); _carStorageContract.Verify(x => x.AddElement(It.IsAny<CarDataModel>()), Times.Once);
@@ -333,7 +313,7 @@ internal class CarBusinessLogicContractTests
[Test] [Test]
public void UpdateCar_RecordWithIncorrectData_ThrowException_Test() public void UpdateCar_RecordWithIncorrectData_ThrowException_Test()
{ {
_carStorageContract.Setup(x => x.UpdElement(It.IsAny<CarDataModel>())).Throws(new ElementNotFoundException("")); _carStorageContract.Setup(x => x.UpdElement(It.IsAny<CarDataModel>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetObject()));
Assert.That(() => _carBusinessLogicContract.UpdateCar(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Porsche", "911", "A911MP")), Throws.TypeOf<ElementNotFoundException>()); Assert.That(() => _carBusinessLogicContract.UpdateCar(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Porsche", "911", "A911MP")), Throws.TypeOf<ElementNotFoundException>());
_carStorageContract.Verify(x => x.UpdElement(It.IsAny<CarDataModel>()), Times.Once); _carStorageContract.Verify(x => x.UpdElement(It.IsAny<CarDataModel>()), Times.Once);
@@ -342,7 +322,7 @@ internal class CarBusinessLogicContractTests
[Test] [Test]
public void UpdateCar_RecordWithExistsData_ThrowException_Test() public void UpdateCar_RecordWithExistsData_ThrowException_Test()
{ {
_carStorageContract.Setup(x => x.UpdElement(It.IsAny<CarDataModel>())).Throws(new ElementExistsException("Data", "Data")); _carStorageContract.Setup(x => x.UpdElement(It.IsAny<CarDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
Assert.That(() => _carBusinessLogicContract.UpdateCar(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Porsche", "911", "A911MP")), Throws.TypeOf<ElementExistsException>()); Assert.That(() => _carBusinessLogicContract.UpdateCar(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Porsche", "911", "A911MP")), Throws.TypeOf<ElementExistsException>());
_carStorageContract.Verify(x => x.UpdElement(It.IsAny<CarDataModel>()), Times.Once); _carStorageContract.Verify(x => x.UpdElement(It.IsAny<CarDataModel>()), Times.Once);
@@ -365,7 +345,7 @@ internal class CarBusinessLogicContractTests
[Test] [Test]
public void UpdateCar_StorageThrowError_ThrowException_Test() public void UpdateCar_StorageThrowError_ThrowException_Test()
{ {
_carStorageContract.Setup(x => x.UpdElement(It.IsAny<CarDataModel>())).Throws(new StorageException(new InvalidOperationException())); _carStorageContract.Setup(x => x.UpdElement(It.IsAny<CarDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _carBusinessLogicContract.UpdateCar(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Porsche", "911", "A911MP")), Throws.TypeOf<StorageException>()); Assert.That(() => _carBusinessLogicContract.UpdateCar(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Porsche", "911", "A911MP")), Throws.TypeOf<StorageException>());
_carStorageContract.Verify(x => x.UpdElement(It.IsAny<CarDataModel>()), Times.Once); _carStorageContract.Verify(x => x.UpdElement(It.IsAny<CarDataModel>()), Times.Once);
@@ -387,7 +367,7 @@ internal class CarBusinessLogicContractTests
[Test] [Test]
public void DeleteCar_RecordWithIncorrectId_ThrowException_Test() public void DeleteCar_RecordWithIncorrectId_ThrowException_Test()
{ {
_carStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException("")); _carStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetObject()));
Assert.That(() => _carBusinessLogicContract.DeleteCar(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>()); Assert.That(() => _carBusinessLogicContract.DeleteCar(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_carStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once); _carStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
@@ -411,7 +391,7 @@ internal class CarBusinessLogicContractTests
[Test] [Test]
public void DeleteCar_StorageThrowError_ThrowException_Test() public void DeleteCar_StorageThrowError_ThrowException_Test()
{ {
_carStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException())); _carStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _carBusinessLogicContract.DeleteCar(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>()); Assert.That(() => _carBusinessLogicContract.DeleteCar(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_carStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once); _carStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);

View File

@@ -4,6 +4,7 @@ using PimpMyRideBusinessLogic.Implementations;
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.StoragesContracts; using PimpMyRideContracts.StoragesContracts;
using PimpMyRideTest.Infrastructure;
namespace PimpMyRideTest.BusinessLogicsContractsTests; namespace PimpMyRideTest.BusinessLogicsContractsTests;
@@ -17,7 +18,7 @@ internal class ClientBusinessLogicContractTests
public void OneTimeSetUp() public void OneTimeSetUp()
{ {
_clientStorageContract = new Mock<IClientStorageContract>(); _clientStorageContract = new Mock<IClientStorageContract>();
_clientBusinessLogicContract = new ClientBusinessLogicContract(_clientStorageContract.Object, new Mock<ILogger>().Object); _clientBusinessLogicContract = new ClientBusinessLogicContract(_clientStorageContract.Object, StringLocalizerMockCreator.GetObject(), new Mock<ILogger>().Object);
} }
[TearDown] [TearDown]
@@ -55,17 +56,10 @@ internal class ClientBusinessLogicContractTests
_clientStorageContract.Verify(x => x.GetList(), Times.Once); _clientStorageContract.Verify(x => x.GetList(), Times.Once);
} }
[Test]
public void GetAllClients_ReturnNull_ThrowException_Test()
{
Assert.That(() => _clientBusinessLogicContract.GetAllClients(), Throws.TypeOf<NullListException>());
_clientStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test] [Test]
public void GetAllClients_StorageThrowError_ThrowException_Test() public void GetAllClients_StorageThrowError_ThrowException_Test()
{ {
_clientStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException())); _clientStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _clientBusinessLogicContract.GetAllClients(), Throws.TypeOf<StorageException>()); Assert.That(() => _clientBusinessLogicContract.GetAllClients(), Throws.TypeOf<StorageException>());
_clientStorageContract.Verify(x => x.GetList(), Times.Once); _clientStorageContract.Verify(x => x.GetList(), Times.Once);
@@ -153,9 +147,9 @@ internal class ClientBusinessLogicContractTests
[Test] [Test]
public void GetClientByData_StorageThrowError_ThrowException_Test() public void GetClientByData_StorageThrowError_ThrowException_Test()
{ {
_clientStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException())); _clientStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_clientStorageContract.Setup(x => x.GetElementByFIO(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException())); _clientStorageContract.Setup(x => x.GetElementByFIO(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_clientStorageContract.Setup(x => x.GetElementByPhoneNumber(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException())); _clientStorageContract.Setup(x => x.GetElementByPhoneNumber(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _clientBusinessLogicContract.GetClientByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>()); Assert.That(() => _clientBusinessLogicContract.GetClientByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _clientBusinessLogicContract.GetClientByData("fio"), Throws.TypeOf<StorageException>()); Assert.That(() => _clientBusinessLogicContract.GetClientByData("fio"), Throws.TypeOf<StorageException>());
@@ -186,7 +180,7 @@ internal class ClientBusinessLogicContractTests
[Test] [Test]
public void InsertClient_RecordWithExistsData_ThrowException_Test() public void InsertClient_RecordWithExistsData_ThrowException_Test()
{ {
_clientStorageContract.Setup(x => x.AddElement(It.IsAny<ClientDataModel>())).Throws(new ElementExistsException("Data", "Data")); _clientStorageContract.Setup(x => x.AddElement(It.IsAny<ClientDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
Assert.That(() => _clientBusinessLogicContract.InsertClient(new(Guid.NewGuid().ToString(), "fio", "81111111112")), Throws.TypeOf<ElementExistsException>()); Assert.That(() => _clientBusinessLogicContract.InsertClient(new(Guid.NewGuid().ToString(), "fio", "81111111112")), Throws.TypeOf<ElementExistsException>());
_clientStorageContract.Verify(x => x.AddElement(It.IsAny<ClientDataModel>()), Times.Once); _clientStorageContract.Verify(x => x.AddElement(It.IsAny<ClientDataModel>()), Times.Once);
@@ -209,7 +203,7 @@ internal class ClientBusinessLogicContractTests
[Test] [Test]
public void InsertClient_StorageThrowError_ThrowException_Test() public void InsertClient_StorageThrowError_ThrowException_Test()
{ {
_clientStorageContract.Setup(x => x.AddElement(It.IsAny<ClientDataModel>())).Throws(new StorageException(new InvalidOperationException())); _clientStorageContract.Setup(x => x.AddElement(It.IsAny<ClientDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _clientBusinessLogicContract.InsertClient(new(Guid.NewGuid().ToString(), "fio", "81111111112")), Throws.TypeOf<StorageException>()); Assert.That(() => _clientBusinessLogicContract.InsertClient(new(Guid.NewGuid().ToString(), "fio", "81111111112")), Throws.TypeOf<StorageException>());
_clientStorageContract.Verify(x => x.AddElement(It.IsAny<ClientDataModel>()), Times.Once); _clientStorageContract.Verify(x => x.AddElement(It.IsAny<ClientDataModel>()), Times.Once);
@@ -236,7 +230,7 @@ internal class ClientBusinessLogicContractTests
[Test] [Test]
public void UpdateClient_RecordWithIncorrectData_ThrowException_Test() public void UpdateClient_RecordWithIncorrectData_ThrowException_Test()
{ {
_clientStorageContract.Setup(x => x.UpdElement(It.IsAny<ClientDataModel>())).Throws(new ElementNotFoundException("")); _clientStorageContract.Setup(x => x.UpdElement(It.IsAny<ClientDataModel>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetObject()));
Assert.That(() => _clientBusinessLogicContract.UpdateClient(new(Guid.NewGuid().ToString(), "fio", "81111111112")), Throws.TypeOf<ElementNotFoundException>()); Assert.That(() => _clientBusinessLogicContract.UpdateClient(new(Guid.NewGuid().ToString(), "fio", "81111111112")), Throws.TypeOf<ElementNotFoundException>());
_clientStorageContract.Verify(x => x.UpdElement(It.IsAny<ClientDataModel>()), Times.Once); _clientStorageContract.Verify(x => x.UpdElement(It.IsAny<ClientDataModel>()), Times.Once);
@@ -245,7 +239,7 @@ internal class ClientBusinessLogicContractTests
[Test] [Test]
public void UpdateClient_RecordWithExistsData_ThrowException_Test() public void UpdateClient_RecordWithExistsData_ThrowException_Test()
{ {
_clientStorageContract.Setup(x => x.UpdElement(It.IsAny<ClientDataModel>())).Throws(new ElementExistsException("Data", "Data")); _clientStorageContract.Setup(x => x.UpdElement(It.IsAny<ClientDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
Assert.That(() => _clientBusinessLogicContract.UpdateClient(new(Guid.NewGuid().ToString(), "fio", "81111111112")), Throws.TypeOf<ElementExistsException>()); Assert.That(() => _clientBusinessLogicContract.UpdateClient(new(Guid.NewGuid().ToString(), "fio", "81111111112")), Throws.TypeOf<ElementExistsException>());
_clientStorageContract.Verify(x => x.UpdElement(It.IsAny<ClientDataModel>()), Times.Once); _clientStorageContract.Verify(x => x.UpdElement(It.IsAny<ClientDataModel>()), Times.Once);
@@ -268,7 +262,7 @@ internal class ClientBusinessLogicContractTests
[Test] [Test]
public void UpdateClient_StorageThrowError_ThrowException_Test() public void UpdateClient_StorageThrowError_ThrowException_Test()
{ {
_clientStorageContract.Setup(x => x.UpdElement(It.IsAny<ClientDataModel>())).Throws(new StorageException(new InvalidOperationException())); _clientStorageContract.Setup(x => x.UpdElement(It.IsAny<ClientDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _clientBusinessLogicContract.UpdateClient(new(Guid.NewGuid().ToString(), "fio", "81111111112")), Throws.TypeOf<StorageException>()); Assert.That(() => _clientBusinessLogicContract.UpdateClient(new(Guid.NewGuid().ToString(), "fio", "81111111112")), Throws.TypeOf<StorageException>());
_clientStorageContract.Verify(x => x.UpdElement(It.IsAny<ClientDataModel>()), Times.Once); _clientStorageContract.Verify(x => x.UpdElement(It.IsAny<ClientDataModel>()), Times.Once);
@@ -290,7 +284,7 @@ internal class ClientBusinessLogicContractTests
[Test] [Test]
public void DeleteClient_RecordWithIncorrectId_ThrowException_Test() public void DeleteClient_RecordWithIncorrectId_ThrowException_Test()
{ {
_clientStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException("")); _clientStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetObject()));
Assert.That(() => _clientBusinessLogicContract.DeleteClient(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>()); Assert.That(() => _clientBusinessLogicContract.DeleteClient(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_clientStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once); _clientStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
@@ -314,7 +308,7 @@ internal class ClientBusinessLogicContractTests
[Test] [Test]
public void DeleteClient_StorageThrowError_ThrowException_Test() public void DeleteClient_StorageThrowError_ThrowException_Test()
{ {
_clientStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException())); _clientStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _clientBusinessLogicContract.DeleteClient(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>()); Assert.That(() => _clientBusinessLogicContract.DeleteClient(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_clientStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once); _clientStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);

View File

@@ -6,6 +6,7 @@ using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Enums; using PimpMyRideContracts.Enums;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.StoragesContracts; using PimpMyRideContracts.StoragesContracts;
using PimpMyRideTest.Infrastructure;
namespace PimpMyRideTest.BusinessLogicsContractsTests; namespace PimpMyRideTest.BusinessLogicsContractsTests;
@@ -19,7 +20,7 @@ internal class MaterialBusinessLogicContractTests
public void OneTimeSetUp() public void OneTimeSetUp()
{ {
_materialStorageContract = new Mock<IMaterialStorageContracts>(); _materialStorageContract = new Mock<IMaterialStorageContracts>();
_materialBusinessLogicContract = new MaterialBusinessLogicContract(_materialStorageContract.Object, new Mock<ILogger>().Object); _materialBusinessLogicContract = new MaterialBusinessLogicContract(_materialStorageContract.Object, StringLocalizerMockCreator.GetObject(), new Mock<ILogger>().Object);
} }
[TearDown] [TearDown]
@@ -58,17 +59,10 @@ internal class MaterialBusinessLogicContractTests
_materialStorageContract.Verify(x => x.GetList(It.IsAny<MaterialType>()), Times.Once); _materialStorageContract.Verify(x => x.GetList(It.IsAny<MaterialType>()), Times.Once);
} }
[Test]
public void GetAllMaterials_ReturnNull_ThrowException_Test()
{
Assert.That(() => _materialBusinessLogicContract.GetAllMaterials(), Throws.TypeOf<NullListException>());
_materialStorageContract.Verify(x => x.GetList(It.IsAny<MaterialType>()), Times.Once);
}
[Test] [Test]
public void GetAllMaterials_StorageThrowError_ThrowException_Test() public void GetAllMaterials_StorageThrowError_ThrowException_Test()
{ {
_materialStorageContract.Setup(x => x.GetList(It.IsAny<MaterialType>())).Throws(new StorageException(new InvalidOperationException())); _materialStorageContract.Setup(x => x.GetList(It.IsAny<MaterialType>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _materialBusinessLogicContract.GetAllMaterials(), Throws.TypeOf<StorageException>()); Assert.That(() => _materialBusinessLogicContract.GetAllMaterials(), Throws.TypeOf<StorageException>());
_materialStorageContract.Verify(x => x.GetList(It.IsAny<MaterialType>()), Times.Once); _materialStorageContract.Verify(x => x.GetList(It.IsAny<MaterialType>()), Times.Once);
@@ -114,17 +108,10 @@ internal class MaterialBusinessLogicContractTests
_materialStorageContract.Verify(x => x.GetList(It.IsAny<MaterialType>()), Times.Never); _materialStorageContract.Verify(x => x.GetList(It.IsAny<MaterialType>()), Times.Never);
} }
[Test]
public void GetAllMaterialsByType_ReturnNull_ThrowException_Test()
{
Assert.That(() => _materialBusinessLogicContract.GetAllMaterialsByType(MaterialType.EngineParts), Throws.TypeOf<NullListException>());
_materialStorageContract.Verify(x => x.GetList(It.IsAny<MaterialType>()), Times.Once);
}
[Test] [Test]
public void GetAllMaterialsByType_StorageThrowError_ThrowException_Test() public void GetAllMaterialsByType_StorageThrowError_ThrowException_Test()
{ {
_materialStorageContract.Setup(x => x.GetList(It.IsAny<MaterialType>())).Throws(new StorageException(new InvalidOperationException())); _materialStorageContract.Setup(x => x.GetList(It.IsAny<MaterialType>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _materialBusinessLogicContract.GetAllMaterialsByType(MaterialType.EngineParts), Throws.TypeOf<StorageException>()); Assert.That(() => _materialBusinessLogicContract.GetAllMaterialsByType(MaterialType.EngineParts), Throws.TypeOf<StorageException>());
_materialStorageContract.Verify(x => x.GetList(It.IsAny<MaterialType>()), Times.Once); _materialStorageContract.Verify(x => x.GetList(It.IsAny<MaterialType>()), Times.Once);
@@ -186,8 +173,8 @@ internal class MaterialBusinessLogicContractTests
[Test] [Test]
public void GetMaterialByData_StorageThrowError_ThrowException_Test() public void GetMaterialByData_StorageThrowError_ThrowException_Test()
{ {
_materialStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException())); _materialStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_materialStorageContract.Setup(x => x.GetElementByDescription(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException())); _materialStorageContract.Setup(x => x.GetElementByDescription(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _materialBusinessLogicContract.GetMaterialByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>()); Assert.That(() => _materialBusinessLogicContract.GetMaterialByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _materialBusinessLogicContract.GetMaterialByData("ring"), Throws.TypeOf<StorageException>()); Assert.That(() => _materialBusinessLogicContract.GetMaterialByData("ring"), Throws.TypeOf<StorageException>());
@@ -241,17 +228,10 @@ internal class MaterialBusinessLogicContractTests
_materialStorageContract.Verify(x => x.GetHistoryByMaterialId(It.IsAny<string>()), Times.Never); _materialStorageContract.Verify(x => x.GetHistoryByMaterialId(It.IsAny<string>()), Times.Never);
} }
[Test]
public void GetMaterialHistoryById_ReturnNull_ThrowException_Test()
{
Assert.That(() => _materialBusinessLogicContract.GetMaterialHistoryById(Guid.NewGuid().ToString()), Throws.TypeOf<NullListException>());
_materialStorageContract.Verify(x => x.GetHistoryByMaterialId(It.IsAny<string>()), Times.Once);
}
[Test] [Test]
public void GetMaterialHistoryById_StorageThrowError_ThrowException_Test() public void GetMaterialHistoryById_StorageThrowError_ThrowException_Test()
{ {
_materialStorageContract.Setup(x => x.GetHistoryByMaterialId(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException())); _materialStorageContract.Setup(x => x.GetHistoryByMaterialId(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _materialBusinessLogicContract.GetMaterialHistoryById(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>()); Assert.That(() => _materialBusinessLogicContract.GetMaterialHistoryById(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_materialStorageContract.Verify(x => x.GetHistoryByMaterialId(It.IsAny<string>()), Times.Once); _materialStorageContract.Verify(x => x.GetHistoryByMaterialId(It.IsAny<string>()), Times.Once);
@@ -278,7 +258,7 @@ internal class MaterialBusinessLogicContractTests
[Test] [Test]
public void InsertMaterial_RecordWithExistsData_ThrowException_Test() public void InsertMaterial_RecordWithExistsData_ThrowException_Test()
{ {
_materialStorageContract.Setup(x => x.AddElement(It.IsAny<MaterialDataModel>())).Throws(new ElementExistsException("Data", "Data")); _materialStorageContract.Setup(x => x.AddElement(It.IsAny<MaterialDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
Assert.That(() => _materialBusinessLogicContract.InsertMaterial(new(Guid.NewGuid().ToString(), MaterialType.EngineParts, "ring", 10)), Throws.TypeOf<ElementExistsException>()); Assert.That(() => _materialBusinessLogicContract.InsertMaterial(new(Guid.NewGuid().ToString(), MaterialType.EngineParts, "ring", 10)), Throws.TypeOf<ElementExistsException>());
_materialStorageContract.Verify(x => x.AddElement(It.IsAny<MaterialDataModel>()), Times.Once); _materialStorageContract.Verify(x => x.AddElement(It.IsAny<MaterialDataModel>()), Times.Once);
@@ -301,7 +281,7 @@ internal class MaterialBusinessLogicContractTests
[Test] [Test]
public void InsertMaterial_StorageThrowError_ThrowException_Test() public void InsertMaterial_StorageThrowError_ThrowException_Test()
{ {
_materialStorageContract.Setup(x => x.AddElement(It.IsAny<MaterialDataModel>())).Throws(new StorageException(new InvalidOperationException())); _materialStorageContract.Setup(x => x.AddElement(It.IsAny<MaterialDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _materialBusinessLogicContract.InsertMaterial(new(Guid.NewGuid().ToString(), MaterialType.EngineParts, "ring", 10)), Throws.TypeOf<StorageException>()); Assert.That(() => _materialBusinessLogicContract.InsertMaterial(new(Guid.NewGuid().ToString(), MaterialType.EngineParts, "ring", 10)), Throws.TypeOf<StorageException>());
_materialStorageContract.Verify(x => x.AddElement(It.IsAny<MaterialDataModel>()), Times.Once); _materialStorageContract.Verify(x => x.AddElement(It.IsAny<MaterialDataModel>()), Times.Once);
@@ -328,7 +308,7 @@ internal class MaterialBusinessLogicContractTests
[Test] [Test]
public void UpdateMaterial_RecordWithIncorrectData_ThrowException_Test() public void UpdateMaterial_RecordWithIncorrectData_ThrowException_Test()
{ {
_materialStorageContract.Setup(x => x.UpdElement(It.IsAny<MaterialDataModel>())).Throws(new ElementNotFoundException("")); _materialStorageContract.Setup(x => x.UpdElement(It.IsAny<MaterialDataModel>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetObject()));
Assert.That(() => _materialBusinessLogicContract.UpdateMaterial(new(Guid.NewGuid().ToString(), MaterialType.EngineParts, "ring", 10)), Throws.TypeOf<ElementNotFoundException>()); Assert.That(() => _materialBusinessLogicContract.UpdateMaterial(new(Guid.NewGuid().ToString(), MaterialType.EngineParts, "ring", 10)), Throws.TypeOf<ElementNotFoundException>());
_materialStorageContract.Verify(x => x.UpdElement(It.IsAny<MaterialDataModel>()), Times.Once); _materialStorageContract.Verify(x => x.UpdElement(It.IsAny<MaterialDataModel>()), Times.Once);
@@ -337,7 +317,7 @@ internal class MaterialBusinessLogicContractTests
[Test] [Test]
public void UpdateMaterial_RecordWithExistsData_ThrowException_Test() public void UpdateMaterial_RecordWithExistsData_ThrowException_Test()
{ {
_materialStorageContract.Setup(x => x.UpdElement(It.IsAny<MaterialDataModel>())).Throws(new ElementExistsException("Data", "Data")); _materialStorageContract.Setup(x => x.UpdElement(It.IsAny<MaterialDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
Assert.That(() => _materialBusinessLogicContract.UpdateMaterial(new(Guid.NewGuid().ToString(), MaterialType.EngineParts, "ring", 10)), Throws.TypeOf<ElementExistsException>()); Assert.That(() => _materialBusinessLogicContract.UpdateMaterial(new(Guid.NewGuid().ToString(), MaterialType.EngineParts, "ring", 10)), Throws.TypeOf<ElementExistsException>());
_materialStorageContract.Verify(x => x.UpdElement(It.IsAny<MaterialDataModel>()), Times.Once); _materialStorageContract.Verify(x => x.UpdElement(It.IsAny<MaterialDataModel>()), Times.Once);
@@ -360,7 +340,7 @@ internal class MaterialBusinessLogicContractTests
[Test] [Test]
public void UpdateMaterial_StorageThrowError_ThrowException_Test() public void UpdateMaterial_StorageThrowError_ThrowException_Test()
{ {
_materialStorageContract.Setup(x => x.UpdElement(It.IsAny<MaterialDataModel>())).Throws(new StorageException(new InvalidOperationException())); _materialStorageContract.Setup(x => x.UpdElement(It.IsAny<MaterialDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _materialBusinessLogicContract.UpdateMaterial(new(Guid.NewGuid().ToString(), MaterialType.EngineParts, "ring", 10)), Throws.TypeOf<StorageException>()); Assert.That(() => _materialBusinessLogicContract.UpdateMaterial(new(Guid.NewGuid().ToString(), MaterialType.EngineParts, "ring", 10)), Throws.TypeOf<StorageException>());
_materialStorageContract.Verify(x => x.UpdElement(It.IsAny<MaterialDataModel>()), Times.Once); _materialStorageContract.Verify(x => x.UpdElement(It.IsAny<MaterialDataModel>()), Times.Once);
@@ -382,7 +362,7 @@ internal class MaterialBusinessLogicContractTests
[Test] [Test]
public void DeleteMaterial_RecordWithIncorrectId_ThrowException_Test() public void DeleteMaterial_RecordWithIncorrectId_ThrowException_Test()
{ {
_materialStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException("")); _materialStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetObject()));
Assert.That(() => _materialBusinessLogicContract.DeleteMaterial(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>()); Assert.That(() => _materialBusinessLogicContract.DeleteMaterial(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_materialStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once); _materialStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
@@ -406,7 +386,7 @@ internal class MaterialBusinessLogicContractTests
[Test] [Test]
public void DeleteMaterial_StorageThrowError_ThrowException_Test() public void DeleteMaterial_StorageThrowError_ThrowException_Test()
{ {
_materialStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException())); _materialStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _materialBusinessLogicContract.DeleteMaterial(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>()); Assert.That(() => _materialBusinessLogicContract.DeleteMaterial(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_materialStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once); _materialStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);

View File

@@ -25,7 +25,7 @@ internal class OrderBusinessLogicContractTests
_orderStorageContract = new Mock<IOrderStorageContract>(); _orderStorageContract = new Mock<IOrderStorageContract>();
_serviceStorageContract = new Mock<IServiceStorageContracts>(); _serviceStorageContract = new Mock<IServiceStorageContracts>();
_serviceBusinessLogicContract = new Mock<IServiceBusinessLogicContract>(); _serviceBusinessLogicContract = new Mock<IServiceBusinessLogicContract>();
_orderBusinessLogicContract = new OrderBusinessLogicContract(_orderStorageContract.Object, _serviceStorageContract.Object, _serviceBusinessLogicContract.Object, new ConfigurationOrderTest(), new Mock<ILogger>().Object); _orderBusinessLogicContract = new OrderBusinessLogicContract(_orderStorageContract.Object, _serviceStorageContract.Object, _serviceBusinessLogicContract.Object, new ConfigurationOrderTest(), StringLocalizerMockCreator.GetObject(), new Mock<ILogger>().Object);
} }
[TearDown] [TearDown]
@@ -76,17 +76,10 @@ internal class OrderBusinessLogicContractTests
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Never); _orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Never);
} }
[Test]
public void GetAllOrdersByPeriod_ReturnNull_ThrowException_Test()
{
Assert.That(() => _orderBusinessLogicContract.GetAllOrdersByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Once);
}
[Test] [Test]
public void GetAllOrdersByPeriod_StorageThrowError_ThrowException_Test() public void GetAllOrdersByPeriod_StorageThrowError_ThrowException_Test()
{ {
_orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException())); _orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _orderBusinessLogicContract.GetAllOrdersByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>()); Assert.That(() => _orderBusinessLogicContract.GetAllOrdersByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Once); _orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Once);
@@ -150,17 +143,10 @@ internal class OrderBusinessLogicContractTests
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Never); _orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Never);
} }
[Test]
public void GetAllOrdersByCarByPeriod_ReturnNull_ThrowException_Test()
{
Assert.That(() => _orderBusinessLogicContract.GetAllOrdersByCarByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Once);
}
[Test] [Test]
public void GetAllOrdersByCarByPeriod_StorageThrowError_ThrowException_Test() public void GetAllOrdersByCarByPeriod_StorageThrowError_ThrowException_Test()
{ {
_orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException())); _orderStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _orderBusinessLogicContract.GetAllOrdersByCarByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>()); Assert.That(() => _orderBusinessLogicContract.GetAllOrdersByCarByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Once); _orderStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>()), Times.Once);
@@ -206,7 +192,7 @@ internal class OrderBusinessLogicContractTests
[Test] [Test]
public void GetOrderByData_StorageThrowError_ThrowException_Test() public void GetOrderByData_StorageThrowError_ThrowException_Test()
{ {
_orderStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException())); _orderStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _orderBusinessLogicContract.GetOrderByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>()); Assert.That(() => _orderBusinessLogicContract.GetOrderByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_orderStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once); _orderStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
@@ -236,7 +222,7 @@ internal class OrderBusinessLogicContractTests
[Test] [Test]
public void InsertOrder_RecordWithExistsData_ThrowException_Test() public void InsertOrder_RecordWithExistsData_ThrowException_Test()
{ {
_orderStorageContract.Setup(x => x.AddElement(It.IsAny<OrderDataModel>())).Throws(new ElementExistsException("Data", "Data")); _orderStorageContract.Setup(x => x.AddElement(It.IsAny<OrderDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
Assert.That(() => _orderBusinessLogicContract.InsertOrder(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Assert.That(() => _orderBusinessLogicContract.InsertOrder(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
false, [new OrderServiceDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 10)])), Throws.TypeOf<ElementExistsException>()); false, [new OrderServiceDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 10)])), Throws.TypeOf<ElementExistsException>());
@@ -260,7 +246,7 @@ internal class OrderBusinessLogicContractTests
[Test] [Test]
public void InsertOrder_StorageThrowError_ThrowException_Test() public void InsertOrder_StorageThrowError_ThrowException_Test()
{ {
_orderStorageContract.Setup(x => x.AddElement(It.IsAny<OrderDataModel>())).Throws(new StorageException(new InvalidOperationException())); _orderStorageContract.Setup(x => x.AddElement(It.IsAny<OrderDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _orderBusinessLogicContract.InsertOrder(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Assert.That(() => _orderBusinessLogicContract.InsertOrder(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
false, [new OrderServiceDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 10)])), Throws.TypeOf<StorageException>()); false, [new OrderServiceDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 10)])), Throws.TypeOf<StorageException>());
@@ -284,7 +270,7 @@ internal class OrderBusinessLogicContractTests
public void CancelOrder_RecordWithIncorrectId_ThrowException_Test() public void CancelOrder_RecordWithIncorrectId_ThrowException_Test()
{ {
var id = Guid.NewGuid().ToString(); var id = Guid.NewGuid().ToString();
_orderStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id)); _orderStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetObject()));
Assert.That(() => _orderBusinessLogicContract.CancelOrder(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>()); Assert.That(() => _orderBusinessLogicContract.CancelOrder(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_orderStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once); _orderStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
@@ -308,7 +294,7 @@ internal class OrderBusinessLogicContractTests
[Test] [Test]
public void CancelOrder_StorageThrowError_ThrowException_Test() public void CancelOrder_StorageThrowError_ThrowException_Test()
{ {
_orderStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException())); _orderStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _orderBusinessLogicContract.CancelOrder(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>()); Assert.That(() => _orderBusinessLogicContract.CancelOrder(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_orderStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once); _orderStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);

View File

@@ -7,6 +7,7 @@ using PimpMyRideContracts.Enums;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Infrastructure.ServiceConfiguration; using PimpMyRideContracts.Infrastructure.ServiceConfiguration;
using PimpMyRideContracts.StoragesContracts; using PimpMyRideContracts.StoragesContracts;
using PimpMyRideTest.Infrastructure;
using static NUnit.Framework.Internal.OSPlatform; using static NUnit.Framework.Internal.OSPlatform;
namespace PimpMyRideTest.BusinessLogicsContractsTests; namespace PimpMyRideTest.BusinessLogicsContractsTests;
@@ -31,7 +32,7 @@ internal class ReportContractTests
_baseWordBuilder = new Mock<BaseWordBuilder>(); _baseWordBuilder = new Mock<BaseWordBuilder>();
_baseExcelBuilder = new Mock<BaseExcelBuilder>(); _baseExcelBuilder = new Mock<BaseExcelBuilder>();
_basePdfBuilder = new Mock<BasePdfBuilder>(); _basePdfBuilder = new Mock<BasePdfBuilder>();
_reportContract = new ReportContract(_carStorageContract.Object, _orderStorageContract.Object, _serviceStorageContract.Object, _baseWordBuilder.Object, _baseExcelBuilder.Object, _basePdfBuilder.Object, new Mock<ILogger>().Object); _reportContract = new ReportContract(_carStorageContract.Object, _orderStorageContract.Object, _serviceStorageContract.Object, _baseWordBuilder.Object, _baseExcelBuilder.Object, _basePdfBuilder.Object, StringLocalizerMockCreator.GetObject(), new Mock<ILogger>().Object);
} }
[SetUp] [SetUp]
@@ -86,7 +87,7 @@ internal class ReportContractTests
public void GetDataCarsByClient_WhenStorageThrowError_ShouldFail_Test() public void GetDataCarsByClient_WhenStorageThrowError_ShouldFail_Test()
{ {
//Arrange //Arrange
_carStorageContract.Setup(x => x.GetListAsync(It.IsAny<CancellationToken>())).Throws(new StorageException(new InvalidOperationException())); _carStorageContract.Setup(x => x.GetListAsync(It.IsAny<CancellationToken>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert //Act&Assert
Assert.That(async () => await _reportContract.GetDataCarsByClientAsync(CancellationToken.None), Throws.TypeOf<StorageException>()); Assert.That(async () => await _reportContract.GetDataCarsByClientAsync(CancellationToken.None), Throws.TypeOf<StorageException>());
_carStorageContract.Verify(x => x.GetListAsync(It.IsAny<CancellationToken>()), Times.Once); _carStorageContract.Verify(x => x.GetListAsync(It.IsAny<CancellationToken>()), Times.Once);
@@ -136,7 +137,7 @@ internal class ReportContractTests
public void GetDataByOrdersByPeriod_WhenStorageThrowError_ShouldFail_Test() public void GetDataByOrdersByPeriod_WhenStorageThrowError_ShouldFail_Test()
{ {
//Arrange //Arrange
_orderStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>())).Throws(new StorageException(new InvalidOperationException())); _orderStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert //Act&Assert
Assert.That(async () => await _reportContract.GetDataOrderByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None), Throws.TypeOf<StorageException>()); Assert.That(async () => await _reportContract.GetDataOrderByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None), Throws.TypeOf<StorageException>());
_orderStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once); _orderStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
@@ -204,7 +205,7 @@ internal class ReportContractTests
public void GetDataServiceByPeriod_WhenStorageThrowError_ShouldFail_Test() public void GetDataServiceByPeriod_WhenStorageThrowError_ShouldFail_Test()
{ {
//Arrange //Arrange
_serviceStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>())).Throws(new StorageException(new InvalidOperationException())); _serviceStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert //Act&Assert
Assert.That(async () => await _reportContract.GetDataServiceByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None), Throws.TypeOf<StorageException>()); Assert.That(async () => await _reportContract.GetDataServiceByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None), Throws.TypeOf<StorageException>());
_serviceStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once); _serviceStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);

View File

@@ -9,6 +9,7 @@ using PimpMyRideContracts.Infrastructure.ServiceConfiguration;
using PimpMyRideContracts.StoragesContracts; using PimpMyRideContracts.StoragesContracts;
using PimpMyRideDatabase.Implementations; using PimpMyRideDatabase.Implementations;
using PimpMyRideDatabase.Models; using PimpMyRideDatabase.Models;
using PimpMyRideTest.Infrastructure;
namespace PimpMyRideTest.BusinessLogicsContractsTests; namespace PimpMyRideTest.BusinessLogicsContractsTests;
@@ -22,7 +23,7 @@ internal class ServiceBusinessLogicContractTests
public void OneTimeSetUp() public void OneTimeSetUp()
{ {
_serviceStorageContract = new Mock<IServiceStorageContracts>(); _serviceStorageContract = new Mock<IServiceStorageContracts>();
_serviceBusinessLogicContract = new ServiceBusinessLogicContract(_serviceStorageContract.Object, new Mock<ILogger>().Object); _serviceBusinessLogicContract = new ServiceBusinessLogicContract(_serviceStorageContract.Object, StringLocalizerMockCreator.GetObject(), new Mock<ILogger>().Object);
} }
[TearDown] [TearDown]
@@ -62,17 +63,10 @@ internal class ServiceBusinessLogicContractTests
_serviceStorageContract.Verify(x => x.GetList(It.IsAny<string>(), It.IsAny<WorkType>()), Times.Once); _serviceStorageContract.Verify(x => x.GetList(It.IsAny<string>(), It.IsAny<WorkType>()), Times.Once);
} }
[Test]
public void GetAllServices_ReturnNull_ThrowException_Test()
{
Assert.That(() => _serviceBusinessLogicContract.GetAllServices(), Throws.TypeOf<NullListException>());
_serviceStorageContract.Verify(x => x.GetList(It.IsAny<string>(), It.IsAny<WorkType>()), Times.Once);
}
[Test] [Test]
public void GetAllServices_StorageThrowError_ThrowException_Test() public void GetAllServices_StorageThrowError_ThrowException_Test()
{ {
_serviceStorageContract.Setup(x => x.GetList(It.IsAny<string>(), It.IsAny<WorkType>())).Throws(new StorageException(new InvalidOperationException())); _serviceStorageContract.Setup(x => x.GetList(It.IsAny<string>(), It.IsAny<WorkType>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _serviceBusinessLogicContract.GetAllServices(), Throws.TypeOf<StorageException>()); Assert.That(() => _serviceBusinessLogicContract.GetAllServices(), Throws.TypeOf<StorageException>());
_serviceStorageContract.Verify(x => x.GetList(It.IsAny<string>(), It.IsAny<WorkType>()), Times.Once); _serviceStorageContract.Verify(x => x.GetList(It.IsAny<string>(), It.IsAny<WorkType>()), Times.Once);
@@ -129,17 +123,10 @@ internal class ServiceBusinessLogicContractTests
_serviceStorageContract.Verify(x => x.GetList(It.IsAny<string>(), It.IsAny<WorkType>()), Times.Never); _serviceStorageContract.Verify(x => x.GetList(It.IsAny<string>(), It.IsAny<WorkType>()), Times.Never);
} }
[Test]
public void GetAllServicesByWork_ReturnNull_ThrowException_Test()
{
Assert.That(() => _serviceBusinessLogicContract.GetAllServicesByWork(Guid.NewGuid().ToString(), WorkType.Body), Throws.TypeOf<NullListException>());
_serviceStorageContract.Verify(x => x.GetList(It.IsAny<string>(), It.IsAny<WorkType>()), Times.Once);
}
[Test] [Test]
public void GetAllServicesByWork_StorageThrowError_ThrowException_Test() public void GetAllServicesByWork_StorageThrowError_ThrowException_Test()
{ {
_serviceStorageContract.Setup(x => x.GetList(It.IsAny<string?>(), It.IsAny<WorkType?>())).Throws(new StorageException(new InvalidOperationException())); _serviceStorageContract.Setup(x => x.GetList(It.IsAny<string?>(), It.IsAny<WorkType?>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _serviceBusinessLogicContract.GetAllServicesByWork(Guid.NewGuid().ToString(), WorkType.Body), Throws.TypeOf<StorageException>()); Assert.That(() => _serviceBusinessLogicContract.GetAllServicesByWork(Guid.NewGuid().ToString(), WorkType.Body), Throws.TypeOf<StorageException>());
_serviceStorageContract.Verify(x => x.GetList(It.IsAny<string?>(), It.IsAny<WorkType?>()), Times.Once); _serviceStorageContract.Verify(x => x.GetList(It.IsAny<string?>(), It.IsAny<WorkType?>()), Times.Once);
@@ -185,7 +172,7 @@ internal class ServiceBusinessLogicContractTests
[Test] [Test]
public void GetServiceByData_StorageThrowError_ThrowException_Test() public void GetServiceByData_StorageThrowError_ThrowException_Test()
{ {
_serviceStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException())); _serviceStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _serviceBusinessLogicContract.GetServiceByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>()); Assert.That(() => _serviceBusinessLogicContract.GetServiceByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_serviceStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once); _serviceStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
@@ -216,7 +203,7 @@ internal class ServiceBusinessLogicContractTests
[Test] [Test]
public void InsertService_RecordWithExistsData_ThrowException_Test() public void InsertService_RecordWithExistsData_ThrowException_Test()
{ {
_serviceStorageContract.Setup(x => x.AddElement(It.IsAny<ServiceDataModel>())).Throws(new ElementExistsException("Data", "Data")); _serviceStorageContract.Setup(x => x.AddElement(It.IsAny<ServiceDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
Assert.That(() => _serviceBusinessLogicContract.InsertService(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), WorkType.Body, new ServiceConfiguration() { Rate = 10 }, Assert.That(() => _serviceBusinessLogicContract.InsertService(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), WorkType.Body, new ServiceConfiguration() { Rate = 10 },
[new ServiceMaterialDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 10)])), Throws.TypeOf<ElementExistsException>()); [new ServiceMaterialDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 10)])), Throws.TypeOf<ElementExistsException>());
@@ -240,7 +227,7 @@ internal class ServiceBusinessLogicContractTests
[Test] [Test]
public void InsertService_StorageThrowError_ThrowException_Test() public void InsertService_StorageThrowError_ThrowException_Test()
{ {
_serviceStorageContract.Setup(x => x.AddElement(It.IsAny<ServiceDataModel>())).Throws(new StorageException(new InvalidOperationException())); _serviceStorageContract.Setup(x => x.AddElement(It.IsAny<ServiceDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _serviceBusinessLogicContract.InsertService(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), WorkType.Body, new ServiceConfiguration() { Rate = 10 }, Assert.That(() => _serviceBusinessLogicContract.InsertService(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), WorkType.Body, new ServiceConfiguration() { Rate = 10 },
[new ServiceMaterialDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 10)])), Throws.TypeOf<StorageException>()); [new ServiceMaterialDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 10)])), Throws.TypeOf<StorageException>());
@@ -264,7 +251,7 @@ internal class ServiceBusinessLogicContractTests
public void CancelService_RecordWithIncorrectId_ThrowException_Test() public void CancelService_RecordWithIncorrectId_ThrowException_Test()
{ {
var id = Guid.NewGuid().ToString(); var id = Guid.NewGuid().ToString();
_serviceStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id)); _serviceStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetObject()));
Assert.That(() => _serviceBusinessLogicContract.CancelService(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>()); Assert.That(() => _serviceBusinessLogicContract.CancelService(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_serviceStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once); _serviceStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
@@ -288,7 +275,7 @@ internal class ServiceBusinessLogicContractTests
[Test] [Test]
public void CancelService_StorageThrowError_ThrowException_Test() public void CancelService_StorageThrowError_ThrowException_Test()
{ {
_serviceStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException())); _serviceStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _serviceBusinessLogicContract.CancelService(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>()); Assert.That(() => _serviceBusinessLogicContract.CancelService(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_serviceStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once); _serviceStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
@@ -300,7 +287,7 @@ internal class ServiceBusinessLogicContractTests
// Arrange // Arrange
var loggerMock = new Mock<ILogger>(); var loggerMock = new Mock<ILogger>();
var serviceStorageMock = new Mock<IServiceStorageContracts>(); var serviceStorageMock = new Mock<IServiceStorageContracts>();
var serviceBL = new ServiceBusinessLogicContract(serviceStorageMock.Object, loggerMock.Object); var serviceBL = new ServiceBusinessLogicContract(serviceStorageMock.Object, StringLocalizerMockCreator.GetObject(), loggerMock.Object);
var serviceId = Guid.NewGuid().ToString(); var serviceId = Guid.NewGuid().ToString();
var workerId = Guid.NewGuid().ToString(); var workerId = Guid.NewGuid().ToString();
@@ -339,7 +326,7 @@ internal class ServiceBusinessLogicContractTests
// Arrange // Arrange
var loggerMock = new Mock<ILogger>(); var loggerMock = new Mock<ILogger>();
var serviceStorageMock = new Mock<IServiceStorageContracts>(); var serviceStorageMock = new Mock<IServiceStorageContracts>();
var serviceBL = new ServiceBusinessLogicContract(serviceStorageMock.Object, loggerMock.Object); var serviceBL = new ServiceBusinessLogicContract(serviceStorageMock.Object, StringLocalizerMockCreator.GetObject(), loggerMock.Object);
var serviceId = Guid.NewGuid().ToString(); var serviceId = Guid.NewGuid().ToString();
var workerId = Guid.NewGuid().ToString(); var workerId = Guid.NewGuid().ToString();
@@ -378,7 +365,7 @@ internal class ServiceBusinessLogicContractTests
// Arrange // Arrange
var loggerMock = new Mock<ILogger>(); var loggerMock = new Mock<ILogger>();
var serviceStorageMock = new Mock<IServiceStorageContracts>(); var serviceStorageMock = new Mock<IServiceStorageContracts>();
var serviceBL = new ServiceBusinessLogicContract(serviceStorageMock.Object, loggerMock.Object); var serviceBL = new ServiceBusinessLogicContract(serviceStorageMock.Object, StringLocalizerMockCreator.GetObject(), loggerMock.Object);
var serviceId = Guid.NewGuid().ToString(); var serviceId = Guid.NewGuid().ToString();
var workerId = Guid.NewGuid().ToString(); var workerId = Guid.NewGuid().ToString();

View File

@@ -5,6 +5,7 @@ using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Enums; using PimpMyRideContracts.Enums;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.StoragesContracts; using PimpMyRideContracts.StoragesContracts;
using PimpMyRideTest.Infrastructure;
namespace PimpMyRideTest.BusinessLogicsContractsTests; namespace PimpMyRideTest.BusinessLogicsContractsTests;
@@ -18,7 +19,7 @@ internal class WorkerBusinessLogicContractTests
public void OneTimeSetUp() public void OneTimeSetUp()
{ {
_workerStorageContract = new Mock<IWorkerStorageContract>(); _workerStorageContract = new Mock<IWorkerStorageContract>();
_workerBusinessLogicContract = new WorkerBusinessLogicContract(_workerStorageContract.Object, new Mock<ILogger>().Object); _workerBusinessLogicContract = new WorkerBusinessLogicContract(_workerStorageContract.Object, StringLocalizerMockCreator.GetObject(), new Mock<ILogger>().Object);
} }
[TearDown] [TearDown]
@@ -70,17 +71,10 @@ internal class WorkerBusinessLogicContractTests
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), SpecialityType.None, null, null, null, null), Times.Exactly(2)); _workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), SpecialityType.None, null, null, null, null), Times.Exactly(2));
} }
[Test]
public void GetAllWorkers_ReturnNull_ThrowException_Test()
{
Assert.That(() => _workerBusinessLogicContract.GetAllWorkers(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<SpecialityType?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test] [Test]
public void GetAllWorkers_StorageThrowError_ThrowException_Test() public void GetAllWorkers_StorageThrowError_ThrowException_Test()
{ {
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<SpecialityType?>(), 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<SpecialityType?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _workerBusinessLogicContract.GetAllWorkers(It.IsAny<bool>()), Throws.TypeOf<StorageException>()); Assert.That(() => _workerBusinessLogicContract.GetAllWorkers(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), SpecialityType.None, null, null, null, null), Times.Once); _workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), SpecialityType.None, null, null, null, null), Times.Once);
@@ -141,17 +135,10 @@ internal class WorkerBusinessLogicContractTests
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<SpecialityType?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never); _workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<SpecialityType?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
} }
[Test]
public void GetAllWorkersByBirthDate_ReturnNull_ThrowException_Test()
{
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<SpecialityType?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test] [Test]
public void GetAllWorkersByBirthDate_StorageThrowError_ThrowException_Test() public void GetAllWorkersByBirthDate_StorageThrowError_ThrowException_Test()
{ {
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<SpecialityType?>(), 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<SpecialityType?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByBirthDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<StorageException>()); 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<SpecialityType?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once); _workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<SpecialityType?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
@@ -212,17 +199,10 @@ internal class WorkerBusinessLogicContractTests
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<SpecialityType?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never); _workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<SpecialityType?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
} }
[Test]
public void GetAllWorkersByEmploymentDate_ReturnNull_ThrowException_Test()
{
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<SpecialityType?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test] [Test]
public void GetAllWorkersByEmploymentDate_StorageThrowError_ThrowException_Test() public void GetAllWorkersByEmploymentDate_StorageThrowError_ThrowException_Test()
{ {
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<SpecialityType?>(), 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<SpecialityType?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<StorageException>()); 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<SpecialityType?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once); _workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<SpecialityType?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
@@ -279,17 +259,10 @@ internal class WorkerBusinessLogicContractTests
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<SpecialityType>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never); _workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<SpecialityType>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
} }
[Test]
public void GetAllWorkersBySpeciality_ReturnNull_ThrowException_Test()
{
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersBySpeciality(SpecialityType.Mechanic, It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<SpecialityType>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test] [Test]
public void GetAllWorkersBySpeciality_StorageThrowError_ThrowException_Test() public void GetAllWorkersBySpeciality_StorageThrowError_ThrowException_Test()
{ {
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<SpecialityType?>(), 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<SpecialityType?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _workerBusinessLogicContract.GetAllWorkersBySpeciality(SpecialityType.Mechanic, It.IsAny<bool>()), Throws.TypeOf<StorageException>()); Assert.That(() => _workerBusinessLogicContract.GetAllWorkersBySpeciality(SpecialityType.Mechanic, It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<SpecialityType?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once); _workerStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<SpecialityType?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
@@ -351,8 +324,8 @@ internal class WorkerBusinessLogicContractTests
[Test] [Test]
public void GetWorkerByData_StorageThrowError_ThrowException_Test() public void GetWorkerByData_StorageThrowError_ThrowException_Test()
{ {
_workerStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException())); _workerStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_workerStorageContract.Setup(x => x.GetElementByFIO(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException())); _workerStorageContract.Setup(x => x.GetElementByFIO(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>()); Assert.That(() => _workerBusinessLogicContract.GetWorkerByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _workerBusinessLogicContract.GetWorkerByData("fio"), Throws.TypeOf<StorageException>()); Assert.That(() => _workerBusinessLogicContract.GetWorkerByData("fio"), Throws.TypeOf<StorageException>());
@@ -381,7 +354,7 @@ internal class WorkerBusinessLogicContractTests
[Test] [Test]
public void InsertWorker_RecordWithExistsData_ThrowException_Test() public void InsertWorker_RecordWithExistsData_ThrowException_Test()
{ {
_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.GetObject()));
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new(Guid.NewGuid().ToString(), "fio", SpecialityType.Mechanic, DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementExistsException>()); Assert.That(() => _workerBusinessLogicContract.InsertWorker(new(Guid.NewGuid().ToString(), "fio", SpecialityType.Mechanic, DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementExistsException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Once); _workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Once);
@@ -404,7 +377,7 @@ internal class WorkerBusinessLogicContractTests
[Test] [Test]
public void InsertWorker_StorageThrowError_ThrowException_Test() public void InsertWorker_StorageThrowError_ThrowException_Test()
{ {
_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.GetObject()));
Assert.That(() => _workerBusinessLogicContract.InsertWorker(new(Guid.NewGuid().ToString(), "fio", SpecialityType.Mechanic, DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>()); Assert.That(() => _workerBusinessLogicContract.InsertWorker(new(Guid.NewGuid().ToString(), "fio", SpecialityType.Mechanic, DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Once); _workerStorageContract.Verify(x => x.AddElement(It.IsAny<WorkerDataModel>()), Times.Once);
@@ -431,7 +404,7 @@ internal class WorkerBusinessLogicContractTests
[Test] [Test]
public void UpdateWorker_RecordWithIncorrectData_ThrowException_Test() public void UpdateWorker_RecordWithIncorrectData_ThrowException_Test()
{ {
_workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>())).Throws(new ElementNotFoundException("")); _workerStorageContract.Setup(x => x.UpdElement(It.IsAny<WorkerDataModel>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetObject()));
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new(Guid.NewGuid().ToString(), "fio", SpecialityType.Mechanic, DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementNotFoundException>()); Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new(Guid.NewGuid().ToString(), "fio", SpecialityType.Mechanic, DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Once); _workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Once);
@@ -454,7 +427,7 @@ internal class WorkerBusinessLogicContractTests
[Test] [Test]
public void UpdateWorker_StorageThrowError_ThrowException_Test() public void UpdateWorker_StorageThrowError_ThrowException_Test()
{ {
_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.GetObject()));
Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new(Guid.NewGuid().ToString(), "fio", SpecialityType.Mechanic, DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>()); Assert.That(() => _workerBusinessLogicContract.UpdateWorker(new(Guid.NewGuid().ToString(), "fio", SpecialityType.Mechanic, DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Once); _workerStorageContract.Verify(x => x.UpdElement(It.IsAny<WorkerDataModel>()), Times.Once);
@@ -477,7 +450,7 @@ internal class WorkerBusinessLogicContractTests
public void DeleteWorker_RecordWithIncorrectId_ThrowException_Test() public void DeleteWorker_RecordWithIncorrectId_ThrowException_Test()
{ {
var id = Guid.NewGuid().ToString(); 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.GetObject()));
Assert.That(() => _workerBusinessLogicContract.DeleteWorker(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>()); Assert.That(() => _workerBusinessLogicContract.DeleteWorker(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once); _workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
@@ -502,7 +475,7 @@ internal class WorkerBusinessLogicContractTests
[Test] [Test]
public void DeleteWorker_StorageThrowError_ThrowException_Test() public void DeleteWorker_StorageThrowError_ThrowException_Test()
{ {
_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.GetObject()));
Assert.That(() => _workerBusinessLogicContract.DeleteWorker(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>()); Assert.That(() => _workerBusinessLogicContract.DeleteWorker(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once); _workerStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);

View File

@@ -1,5 +1,6 @@
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideTest.Infrastructure;
namespace PimpMyRideTest.DataModelTests; namespace PimpMyRideTest.DataModelTests;
@@ -10,58 +11,58 @@ internal class CarDataModelTests
public void IdIsNullOrEmptyTest() public void IdIsNullOrEmptyTest()
{ {
var car = CreateDataModel(null, Guid.NewGuid().ToString(), "Porsche", "911", "A991MP"); var car = CreateDataModel(null, Guid.NewGuid().ToString(), "Porsche", "911", "A991MP");
Assert.That(() => car.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => car.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
car = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), "Porsche", "911", "A991MP"); car = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), "Porsche", "911", "A991MP");
Assert.That(() => car.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => car.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void IdIsNotGuidTest() public void IdIsNotGuidTest()
{ {
var car = CreateDataModel("id", Guid.NewGuid().ToString(), "Porsche", "911", "A991MP"); var car = CreateDataModel("id", Guid.NewGuid().ToString(), "Porsche", "911", "A991MP");
Assert.That(() => car.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => car.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void ClientIdIsNullOrEmptyTest() public void ClientIdIsNullOrEmptyTest()
{ {
var car = CreateDataModel(Guid.NewGuid().ToString(), null, "Porsche", "911", "A991MP"); var car = CreateDataModel(Guid.NewGuid().ToString(), null, "Porsche", "911", "A991MP");
Assert.That(() => car.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => car.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
car = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, "Porsche", "911", "A991MP"); car = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, "Porsche", "911", "A991MP");
Assert.That(() => car.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => car.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void ClientIdIsNotGuidTest() public void ClientIdIsNotGuidTest()
{ {
var car = CreateDataModel(Guid.NewGuid().ToString(), "id", "Porsche", "911", "A991MP"); var car = CreateDataModel(Guid.NewGuid().ToString(), "id", "Porsche", "911", "A991MP");
Assert.That(() => car.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => car.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void MakeIsNullOrEmptyTest() public void MakeIsNullOrEmptyTest()
{ {
var car = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, "911", "A911MP"); var car = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, "911", "A911MP");
Assert.That(() => car.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => car.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
car = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), string.Empty, "911", "A911MP"); car = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), string.Empty, "911", "A911MP");
Assert.That(() => car.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => car.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void ModelIsNullOrEmptyTest() public void ModelIsNullOrEmptyTest()
{ {
var car = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Porsche", null, "A911MP"); var car = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Porsche", null, "A911MP");
Assert.That(() => car.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => car.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
car = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Porsche", string.Empty, "A911MP"); car = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Porsche", string.Empty, "A911MP");
Assert.That(() => car.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => car.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void StateNumberIsNullOrEmptyTest() public void StateNumberIsNullOrEmptyTest()
{ {
var car = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Porsche", "911", null); var car = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Porsche", "911", null);
Assert.That(() => car.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => car.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
car = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Porsche", "911", string.Empty); car = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Porsche", "911", string.Empty);
Assert.That(() => car.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => car.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
@@ -73,7 +74,7 @@ internal class CarDataModelTests
var model = "911"; var model = "911";
var stateNumber = "A911MP"; var stateNumber = "A911MP";
var car = CreateDataModel(id, clientId, make, model, stateNumber); var car = CreateDataModel(id, clientId, make, model, stateNumber);
Assert.That(() => car.Validate(), Throws.Nothing); Assert.That(() => car.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.Multiple(() => Assert.Multiple(() =>
{ {
Assert.That(car.Id, Is.EqualTo(id)); Assert.That(car.Id, Is.EqualTo(id));

View File

@@ -1,5 +1,6 @@
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideTest.Infrastructure;
namespace PimpMyRideTest.DataModelTests; namespace PimpMyRideTest.DataModelTests;
@@ -10,41 +11,41 @@ internal class ClientDataModelTests
public void IdIsNullOrEmptyTest() public void IdIsNullOrEmptyTest()
{ {
var client = CreateDataModel(null, "fio", "88005553535"); var client = CreateDataModel(null, "fio", "88005553535");
Assert.That(() => client.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => client.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
client = CreateDataModel(string.Empty, "fio", "88005553535"); client = CreateDataModel(string.Empty, "fio", "88005553535");
Assert.That(() => client.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => client.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void IdIsNotGuidTest() public void IdIsNotGuidTest()
{ {
var client = CreateDataModel("id", "fio", "88005553535"); var client = CreateDataModel("id", "fio", "88005553535");
Assert.That(() => client.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => client.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void FIOIsNullOrEmptyTest() public void FIOIsNullOrEmptyTest()
{ {
var client = CreateDataModel(Guid.NewGuid().ToString(), null, "88005553535"); var client = CreateDataModel(Guid.NewGuid().ToString(), null, "88005553535");
Assert.That(() => client.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => client.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
client = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, "88005553535"); client = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, "88005553535");
Assert.That(() => client.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => client.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void PhoneNumberIsNullOrEmptyTest() public void PhoneNumberIsNullOrEmptyTest()
{ {
var client = CreateDataModel(Guid.NewGuid().ToString(), "fio", null); var client = CreateDataModel(Guid.NewGuid().ToString(), "fio", null);
Assert.That(() => client.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => client.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
client = CreateDataModel(Guid.NewGuid().ToString(), "fio", string.Empty); client = CreateDataModel(Guid.NewGuid().ToString(), "fio", string.Empty);
Assert.That(() => client.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => client.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void PhoneNumberIsIncorrectTest() public void PhoneNumberIsIncorrectTest()
{ {
var client = CreateDataModel(Guid.NewGuid().ToString(), "fio", "777"); var client = CreateDataModel(Guid.NewGuid().ToString(), "fio", "777");
Assert.That(() => client.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => client.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
@@ -54,7 +55,7 @@ internal class ClientDataModelTests
var fio = "Fio"; var fio = "Fio";
var phoneNumber = "88005553535"; var phoneNumber = "88005553535";
var client = CreateDataModel(clientId, fio, phoneNumber); var client = CreateDataModel(clientId, fio, phoneNumber);
Assert.That(() => client.Validate(), Throws.Nothing); Assert.That(() => client.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.Multiple(() => Assert.Multiple(() =>
{ {
Assert.That(client.Id, Is.EqualTo(clientId)); Assert.That(client.Id, Is.EqualTo(clientId));

View File

@@ -1,6 +1,7 @@
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Enums; using PimpMyRideContracts.Enums;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideTest.Infrastructure;
namespace PimpMyRideTest.DataModelTests; namespace PimpMyRideTest.DataModelTests;
@@ -11,39 +12,39 @@ internal class MaterialDataModelTests
public void IdIsNullOrEmptyTest() public void IdIsNullOrEmptyTest()
{ {
var material = CreateDataModel(null, MaterialType.Wheels, "Bridgestone tires", 100.0); var material = CreateDataModel(null, MaterialType.Wheels, "Bridgestone tires", 100.0);
Assert.That(() => material.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => material.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
material = CreateDataModel(string.Empty, MaterialType.Wheels, "Bridgestone tires", 100.0); material = CreateDataModel(string.Empty, MaterialType.Wheels, "Bridgestone tires", 100.0);
Assert.That(() => material.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => material.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void IdIsNotGuidTest() public void IdIsNotGuidTest()
{ {
var material = CreateDataModel("id", MaterialType.Wheels, "Bridgestone tires", 100.0); var material = CreateDataModel("id", MaterialType.Wheels, "Bridgestone tires", 100.0);
Assert.That(() => material.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => material.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void MaterialTypeIsNoneTest() public void MaterialTypeIsNoneTest()
{ {
var material = CreateDataModel(Guid.NewGuid().ToString(), MaterialType.None, "Bridgestone tires", 100.0); var material = CreateDataModel(Guid.NewGuid().ToString(), MaterialType.None, "Bridgestone tires", 100.0);
Assert.That(() => material.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => material.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void DescriptionIsNullOrEmptyTest() public void DescriptionIsNullOrEmptyTest()
{ {
var material = CreateDataModel(Guid.NewGuid().ToString(), MaterialType.Wheels, null, 100.0); var material = CreateDataModel(Guid.NewGuid().ToString(), MaterialType.Wheels, null, 100.0);
Assert.That(() => material.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => material.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
material = CreateDataModel(Guid.NewGuid().ToString(), MaterialType.Wheels, string.Empty, 100.0); material = CreateDataModel(Guid.NewGuid().ToString(), MaterialType.Wheels, string.Empty, 100.0);
Assert.That(() => material.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => material.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void UnitCostIsNegativeTest() public void UnitCostIsNegativeTest()
{ {
var material = CreateDataModel(Guid.NewGuid().ToString(), MaterialType.Wheels, "Bridgestone tires", -1.0); var material = CreateDataModel(Guid.NewGuid().ToString(), MaterialType.Wheels, "Bridgestone tires", -1.0);
Assert.That(() => material.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => material.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
@@ -54,7 +55,7 @@ internal class MaterialDataModelTests
var description = "Bridgestone tires"; var description = "Bridgestone tires";
var unitCost = 100.0; var unitCost = 100.0;
var material = CreateDataModel(id, materialType, description, unitCost); var material = CreateDataModel(id, materialType, description, unitCost);
Assert.That(() => material.Validate(), Throws.Nothing); Assert.That(() => material.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.Multiple(() => Assert.Multiple(() =>
{ {
Assert.That(material.Id, Is.EqualTo(id)); Assert.That(material.Id, Is.EqualTo(id));

View File

@@ -1,6 +1,7 @@
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Enums; using PimpMyRideContracts.Enums;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideTest.Infrastructure;
namespace PimpMyRideTest.DataModelTests; namespace PimpMyRideTest.DataModelTests;
@@ -11,25 +12,25 @@ internal class MaterialHistoryDataModelTests
public void MaterialIdIsNullOrEmptyTest() public void MaterialIdIsNullOrEmptyTest()
{ {
var material = CreateDataModel(null, 100.0); var material = CreateDataModel(null, 100.0);
Assert.That(() => material.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => material.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
material = CreateDataModel(string.Empty, 100.0); material = CreateDataModel(string.Empty, 100.0);
Assert.That(() => material.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => material.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void MaterialIdIsNotGuidTest() public void MaterialIdIsNotGuidTest()
{ {
var material = CreateDataModel("id", 100.0); var material = CreateDataModel("id", 100.0);
Assert.That(() => material.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => material.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void OldPriceIsZeroOrNegative() public void OldPriceIsZeroOrNegative()
{ {
var material = CreateDataModel(Guid.NewGuid().ToString(), 0); var material = CreateDataModel(Guid.NewGuid().ToString(), 0);
Assert.That(() => material.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => material.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
material = CreateDataModel(Guid.NewGuid().ToString(), -1.0); material = CreateDataModel(Guid.NewGuid().ToString(), -1.0);
Assert.That(() => material.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => material.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
@@ -38,7 +39,7 @@ internal class MaterialHistoryDataModelTests
var materialId = Guid.NewGuid().ToString(); var materialId = Guid.NewGuid().ToString();
var oldPrice = 100.0; var oldPrice = 100.0;
var material = CreateDataModel(materialId, oldPrice); var material = CreateDataModel(materialId, oldPrice);
Assert.That(() => material.Validate(), Throws.Nothing); Assert.That(() => material.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.Multiple(() => Assert.Multiple(() =>
{ {
Assert.That(material.MaterialId, Is.EqualTo(materialId)); Assert.That(material.MaterialId, Is.EqualTo(materialId));

View File

@@ -1,5 +1,6 @@
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideTest.Infrastructure;
namespace PimpMyRideTest.DataModelTests; namespace PimpMyRideTest.DataModelTests;
@@ -11,10 +12,10 @@ internal class OrderDataModelTests
{ {
var order = CreateDataModel(null, Guid.NewGuid().ToString(), 500.0, false, var order = CreateDataModel(null, Guid.NewGuid().ToString(), 500.0, false,
[new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 10)]); [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 10)]);
Assert.That(() => order.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => order.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
order = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 500.0, false, order = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 500.0, false,
[new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 10)]); [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 10)]);
Assert.That(() => order.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => order.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
@@ -22,7 +23,7 @@ internal class OrderDataModelTests
{ {
var order = CreateDataModel("id", Guid.NewGuid().ToString(), 500.0, false, var order = CreateDataModel("id", Guid.NewGuid().ToString(), 500.0, false,
[new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 10)]); [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 10)]);
Assert.That(() => order.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => order.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
@@ -30,11 +31,11 @@ internal class OrderDataModelTests
{ {
var order = CreateDataModel(Guid.NewGuid().ToString(), null, 500.0, false, var order = CreateDataModel(Guid.NewGuid().ToString(), null, 500.0, false,
[new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 10)]); [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 10)]);
Assert.That(() => order.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => order.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
order = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, 500.0, false, order = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, 500.0, false,
[new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 10)]); [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 10)]);
Assert.That(() => order.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => order.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
@@ -42,14 +43,14 @@ internal class OrderDataModelTests
{ {
var order = CreateDataModel(Guid.NewGuid().ToString(), "id", 500.0, false, var order = CreateDataModel(Guid.NewGuid().ToString(), "id", 500.0, false,
[new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 10)]); [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 10)]);
Assert.That(() => order.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => order.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void ServicesAreEmptyTest() public void ServicesAreEmptyTest()
{ {
var order = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 500.0, false, []); var order = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 500.0, false, []);
Assert.That(() => order.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => order.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
@@ -63,7 +64,7 @@ internal class OrderDataModelTests
var order = CreateDataModel(id, carId, totalCost, isCancel, services); var order = CreateDataModel(id, carId, totalCost, isCancel, services);
Assert.That(() => order.Validate(), Throws.Nothing); Assert.That(() => order.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.Multiple(() => Assert.Multiple(() =>
{ {
Assert.That(order.Id, Is.EqualTo(id)); Assert.That(order.Id, Is.EqualTo(id));

View File

@@ -1,5 +1,6 @@
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideTest.Infrastructure;
namespace PimpMyRideTest.DataModelTests; namespace PimpMyRideTest.DataModelTests;
@@ -10,41 +11,41 @@ internal class OrderServiceDataModelTests
public void OrderIdIsNullOrEmptyTest() public void OrderIdIsNullOrEmptyTest()
{ {
var orderService = CreateDataModel(null, Guid.NewGuid().ToString(), 1, 1); var orderService = CreateDataModel(null, Guid.NewGuid().ToString(), 1, 1);
Assert.That(() => orderService.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => orderService.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
orderService = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 1, 1); orderService = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 1, 1);
Assert.That(() => orderService.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => orderService.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void OrderIdIsNotGuidTest() public void OrderIdIsNotGuidTest()
{ {
var orderService = CreateDataModel("id", Guid.NewGuid().ToString(), 1, 1); var orderService = CreateDataModel("id", Guid.NewGuid().ToString(), 1, 1);
Assert.That(() => orderService.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => orderService.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void ServiceIdIsNullOrEmptyTest() public void ServiceIdIsNullOrEmptyTest()
{ {
var orderService = CreateDataModel(Guid.NewGuid().ToString(), null, 1, 10); var orderService = CreateDataModel(Guid.NewGuid().ToString(), null, 1, 10);
Assert.That(() => orderService.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => orderService.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
orderService = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, 1, 10); orderService = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, 1, 10);
Assert.That(() => orderService.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => orderService.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void ServiceIdIsNotGuidTest() public void ServiceIdIsNotGuidTest()
{ {
var orderService = CreateDataModel(Guid.NewGuid().ToString(), "id", 1, 10); var orderService = CreateDataModel(Guid.NewGuid().ToString(), "id", 1, 10);
Assert.That(() => orderService.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => orderService.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void CountIsZeroOrNegativeTest() public void CountIsZeroOrNegativeTest()
{ {
var orderService = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0, 10); var orderService = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0, 10);
Assert.That(() => orderService.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => orderService.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
orderService = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -1, 10); orderService = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -1, 10);
Assert.That(() => orderService.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => orderService.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
@@ -55,7 +56,7 @@ internal class OrderServiceDataModelTests
var count = 2; var count = 2;
var price = 10; var price = 10;
var orderService = CreateDataModel(orderId, serviceId, count, price); var orderService = CreateDataModel(orderId, serviceId, count, price);
Assert.That(() => orderService.Validate(), Throws.Nothing); Assert.That(() => orderService.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.Multiple(() => Assert.Multiple(() =>
{ {
Assert.That(orderService.OrderId, Is.EqualTo(orderId)); Assert.That(orderService.OrderId, Is.EqualTo(orderId));

View File

@@ -1,7 +1,9 @@
using PimpMyRideContracts.DataModels; using Microsoft.Extensions.Hosting;
using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Enums; using PimpMyRideContracts.Enums;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Infrastructure.ServiceConfiguration; using PimpMyRideContracts.Infrastructure.ServiceConfiguration;
using PimpMyRideTest.Infrastructure;
namespace PimpMyRideTest.DataModelTests; namespace PimpMyRideTest.DataModelTests;
@@ -13,10 +15,10 @@ internal class ServiceDataModelTests
{ {
var service = CreateDataModel(null, Guid.NewGuid().ToString(), WorkType.Engine, new ServiceConfiguration() { Rate = 10 }, var service = CreateDataModel(null, Guid.NewGuid().ToString(), WorkType.Engine, new ServiceConfiguration() { Rate = 10 },
[new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 10)]); [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 10)]);
Assert.That(() => service.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => service.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
service = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), WorkType.Engine, new ServiceConfiguration() { Rate = 10 }, service = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), WorkType.Engine, new ServiceConfiguration() { Rate = 10 },
[new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 10)]); [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 10)]);
Assert.That(() => service.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => service.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
@@ -24,7 +26,7 @@ internal class ServiceDataModelTests
{ {
var service = CreateDataModel("id", Guid.NewGuid().ToString(), WorkType.Engine, new ServiceConfiguration() { Rate = 10 }, var service = CreateDataModel("id", Guid.NewGuid().ToString(), WorkType.Engine, new ServiceConfiguration() { Rate = 10 },
[new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 10)]); [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 10)]);
Assert.That(() => service.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => service.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
@@ -32,7 +34,7 @@ internal class ServiceDataModelTests
{ {
var service = CreateDataModel(Guid.NewGuid().ToString(), "worker", WorkType.Engine, new ServiceConfiguration() { Rate = 10 }, var service = CreateDataModel(Guid.NewGuid().ToString(), "worker", WorkType.Engine, new ServiceConfiguration() { Rate = 10 },
[new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 10)]); [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 10)]);
Assert.That(() => service.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => service.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
@@ -40,14 +42,14 @@ internal class ServiceDataModelTests
{ {
var service = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), WorkType.None, new ServiceConfiguration() { Rate = 10 }, var service = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), WorkType.None, new ServiceConfiguration() { Rate = 10 },
[new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 10)]); [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 10)]);
Assert.That(() => service.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => service.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void MaterialsAreEmptyTest() public void MaterialsAreEmptyTest()
{ {
var service = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), WorkType.Engine, new ServiceConfiguration() { Rate = 10 }, []); var service = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), WorkType.Engine, new ServiceConfiguration() { Rate = 10 }, []);
Assert.That(() => service.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => service.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
@@ -61,13 +63,16 @@ internal class ServiceDataModelTests
var service = CreateDataModel(id, workerId, workType, configuration, materials); var service = CreateDataModel(id, workerId, workType, configuration, materials);
Assert.That(() => service.Validate(), Throws.Nothing); Assert.That(() => service.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.Multiple(() => Assert.Multiple(() =>
{ {
Assert.That(service.Id, Is.EqualTo(id)); Assert.That(service.Id, Is.EqualTo(id));
Assert.That(service.WorkerId, Is.EqualTo(workerId)); Assert.That(service.WorkerId, Is.EqualTo(workerId));
Assert.That(service.WorkType, Is.EqualTo(workType)); Assert.That(service.WorkType, Is.EqualTo(workType));
Assert.That(service.Materials, Is.EquivalentTo(materials)); Assert.That(service.Materials, Is.EquivalentTo(materials));
Assert.That(service.ConfigurationModel, Is.EqualTo(configuration));
Assert.That(service.ConfigurationModel.Rate, Is.EqualTo(configuration.Rate));
Assert.That(service.ConfigurationModel.CultureName, Is.Not.Empty);
}); });
} }

View File

@@ -1,5 +1,6 @@
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideTest.Infrastructure;
namespace PimpMyRideTest.DataModelTests; namespace PimpMyRideTest.DataModelTests;
@@ -10,41 +11,41 @@ internal class ServiceMaterialDataModelTests
public void ServiceIdIsNullOrEmptyTest() public void ServiceIdIsNullOrEmptyTest()
{ {
var serviceMaterial = new ServiceMaterialDataModel(null, Guid.NewGuid().ToString(), 1, 10); var serviceMaterial = new ServiceMaterialDataModel(null, Guid.NewGuid().ToString(), 1, 10);
Assert.That(() => serviceMaterial.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => serviceMaterial.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
serviceMaterial = new ServiceMaterialDataModel(string.Empty, Guid.NewGuid().ToString(), 1, 10); serviceMaterial = new ServiceMaterialDataModel(string.Empty, Guid.NewGuid().ToString(), 1, 10);
Assert.That(() => serviceMaterial.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => serviceMaterial.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void ServiceIdIsNotGuidTest() public void ServiceIdIsNotGuidTest()
{ {
var serviceMaterial = CreateDataModel("id", Guid.NewGuid().ToString(), 1, 10); var serviceMaterial = CreateDataModel("id", Guid.NewGuid().ToString(), 1, 10);
Assert.That(() => serviceMaterial.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => serviceMaterial.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void MaterialIdIsNullOrEmptyTest() public void MaterialIdIsNullOrEmptyTest()
{ {
var serviceMaterial = new ServiceMaterialDataModel(Guid.NewGuid().ToString(), null, 1, 10); var serviceMaterial = new ServiceMaterialDataModel(Guid.NewGuid().ToString(), null, 1, 10);
Assert.That(() => serviceMaterial.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => serviceMaterial.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
serviceMaterial = new ServiceMaterialDataModel(Guid.NewGuid().ToString(), string.Empty, 1, 10); serviceMaterial = new ServiceMaterialDataModel(Guid.NewGuid().ToString(), string.Empty, 1, 10);
Assert.That(() => serviceMaterial.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => serviceMaterial.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void MaterialIdIsNotGuidTest() public void MaterialIdIsNotGuidTest()
{ {
var serviceMaterial = CreateDataModel(Guid.NewGuid().ToString(), "id", 1, 10); var serviceMaterial = CreateDataModel(Guid.NewGuid().ToString(), "id", 1, 10);
Assert.That(() => serviceMaterial.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => serviceMaterial.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void CountIsZeroOrNegativeTest() public void CountIsZeroOrNegativeTest()
{ {
var serviceMaterial = new ServiceMaterialDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0, 10); var serviceMaterial = new ServiceMaterialDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0, 10);
Assert.That(() => serviceMaterial.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => serviceMaterial.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
serviceMaterial = new ServiceMaterialDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -1, 10); serviceMaterial = new ServiceMaterialDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -1, 10);
Assert.That(() => serviceMaterial.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => serviceMaterial.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
@@ -57,7 +58,7 @@ internal class ServiceMaterialDataModelTests
var serviceMaterial = CreateDataModel(serviceId, materialId, count, price); var serviceMaterial = CreateDataModel(serviceId, materialId, count, price);
Assert.That(() => serviceMaterial.Validate(), Throws.Nothing); Assert.That(() => serviceMaterial.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.Multiple(() => Assert.Multiple(() =>
{ {
Assert.That(serviceMaterial.ServiceId, Is.EqualTo(serviceId)); Assert.That(serviceMaterial.ServiceId, Is.EqualTo(serviceId));

View File

@@ -1,6 +1,7 @@
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Enums; using PimpMyRideContracts.Enums;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideTest.Infrastructure;
namespace PimpMyRideTest.DataModelTests; namespace PimpMyRideTest.DataModelTests;
@@ -12,10 +13,10 @@ internal class WorkerDataModelTests
{ {
var worker = CreateDataModel(null, "John Doe", SpecialityType.Mechanic, DateTime.Now.AddYears(-20), var worker = CreateDataModel(null, "John Doe", SpecialityType.Mechanic, DateTime.Now.AddYears(-20),
DateTime.Now.AddYears(-2), false); DateTime.Now.AddYears(-2), false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
worker = CreateDataModel(string.Empty, "John Doe", SpecialityType.Mechanic, DateTime.Now.AddYears(-20), worker = CreateDataModel(string.Empty, "John Doe", SpecialityType.Mechanic, DateTime.Now.AddYears(-20),
DateTime.Now.AddYears(-2), false); DateTime.Now.AddYears(-2), false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
@@ -23,7 +24,7 @@ internal class WorkerDataModelTests
{ {
var worker = CreateDataModel("id", "John Doe", SpecialityType.Mechanic, DateTime.Now.AddYears(-20), var worker = CreateDataModel("id", "John Doe", SpecialityType.Mechanic, DateTime.Now.AddYears(-20),
DateTime.Now.AddYears(-2), false); DateTime.Now.AddYears(-2), false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
@@ -31,10 +32,10 @@ internal class WorkerDataModelTests
{ {
var worker = CreateDataModel(Guid.NewGuid().ToString(), null, SpecialityType.Mechanic, DateTime.Now.AddYears(-20), var worker = CreateDataModel(Guid.NewGuid().ToString(), null, SpecialityType.Mechanic, DateTime.Now.AddYears(-20),
DateTime.Now.AddYears(-2), false); DateTime.Now.AddYears(-2), false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
worker = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, SpecialityType.Mechanic, DateTime.Now.AddYears(-20), worker = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, SpecialityType.Mechanic, DateTime.Now.AddYears(-20),
DateTime.Now.AddYears(-2), false); DateTime.Now.AddYears(-2), false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
@@ -42,7 +43,7 @@ internal class WorkerDataModelTests
{ {
var worker = CreateDataModel(Guid.NewGuid().ToString(), "John Doe", SpecialityType.None, DateTime.Now.AddYears(-20), var worker = CreateDataModel(Guid.NewGuid().ToString(), "John Doe", SpecialityType.None, DateTime.Now.AddYears(-20),
DateTime.Now.AddYears(-2), false); DateTime.Now.AddYears(-2), false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
@@ -50,7 +51,7 @@ internal class WorkerDataModelTests
{ {
var worker = CreateDataModel(Guid.NewGuid().ToString(), "John Doe", SpecialityType.Mechanic, DateTime.Now.AddYears(-17), var worker = CreateDataModel(Guid.NewGuid().ToString(), "John Doe", SpecialityType.Mechanic, DateTime.Now.AddYears(-17),
DateTime.Now.AddYears(-1), false); DateTime.Now.AddYears(-1), false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
@@ -58,7 +59,7 @@ internal class WorkerDataModelTests
{ {
var worker = CreateDataModel(Guid.NewGuid().ToString(), "John Doe", SpecialityType.Mechanic, DateTime.Now.AddYears(-30), var worker = CreateDataModel(Guid.NewGuid().ToString(), "John Doe", SpecialityType.Mechanic, DateTime.Now.AddYears(-30),
DateTime.Now.AddYears(-31), false); DateTime.Now.AddYears(-31), false);
Assert.That(() => worker.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
@@ -72,14 +73,14 @@ internal class WorkerDataModelTests
var isDeleted = false; var isDeleted = false;
var worker = CreateDataModel(id, fio, specialityType, birthDate, employmentDate, isDeleted); var worker = CreateDataModel(id, fio, specialityType, birthDate, employmentDate, isDeleted);
Assert.That(() => worker.Validate(), Throws.Nothing); Assert.That(() => worker.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.Multiple(() => Assert.Multiple(() =>
{ {
Assert.That(worker.Id, Is.EqualTo(id)); Assert.That(worker.Id, Is.EqualTo(id));
Assert.That(worker.FIO, Is.EqualTo(fio)); Assert.That(worker.FIO, Is.EqualTo(fio));
Assert.That(worker.SpecialityType, Is.EqualTo(specialityType)); Assert.That(worker.SpecialityType, Is.EqualTo(specialityType));
Assert.That(worker.BirthDate, Is.EqualTo(birthDate)); Assert.That(worker.BirthDate, Is.EqualTo(birthDate.ToUniversalTime()));
Assert.That(worker.EmploymentDate, Is.EqualTo(employmentDate)); Assert.That(worker.EmploymentDate, Is.EqualTo(employmentDate.ToUniversalTime()));
Assert.That(worker.IsDeleted, Is.EqualTo(isDeleted)); Assert.That(worker.IsDeleted, Is.EqualTo(isDeleted));
}); });
} }

View File

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

View File

@@ -0,0 +1,353 @@
using Microsoft.AspNetCore.Mvc.Testing;
using PimpMyRideDatabase;
using PimpMyRideTest.Infrastructure;
using System.Text.Json;
using System.Text;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Logging;
using Serilog;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Enums;
using PimpMyRideContracts.Infrastructure.ServiceConfiguration;
using System.Net;
using Newtonsoft.Json.Linq;
using PimpMyRideContracts.BindingModels;
using static NUnit.Framework.Internal.OSPlatform;
using Castle.Core.Configuration;
namespace PimpMyRideTest.LocalizationTests;
internal abstract class BaseLocalizationControllerTest
{
protected abstract string GetLocale();
private WebApplicationFactory<Program> _webApplication;
protected static PimpMyRideDbContext PimpMyRideDbContext { get; private set; }
protected HttpClient HttpClient { get; private set; }
protected static readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNameCaseInsensitive = true };
private static string _clientId;
private static string _carId;
private static string _materialId;
private static string _workerId;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_webApplication = new CustomWebApplicationFactory<Program>();
HttpClient = _webApplication
.WithWebHostBuilder(builder =>
{
builder.ConfigureTestServices(services =>
{
using var loggerFactory = new LoggerFactory();
loggerFactory.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build())
.CreateLogger());
services.AddSingleton(loggerFactory);
});
})
.CreateClient();
var request = HttpClient.GetAsync("/login/user").GetAwaiter().GetResult();
var data = request.Content.ReadAsStringAsync().GetAwaiter().GetResult();
HttpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {data}");
HttpClient.DefaultRequestHeaders.Add("Accept-Language", GetLocale());
PimpMyRideDbContext = _webApplication.Services.GetRequiredService<PimpMyRideDbContext>();
PimpMyRideDbContext.Database.EnsureDeleted();
PimpMyRideDbContext.Database.EnsureCreated();
}
[SetUp]
public void SetUp()
{
_clientId = PimpMyRideDbContext.InsertClientToDatabaseAndReturn(fio: "Client", phoneNumber: "+6-666-666-66-66").Id;
_carId = PimpMyRideDbContext.InsertCarToDatabaseAndReturn(clientId: _clientId, make: "taz", stateNumber: "b555bb").Id;
_materialId = PimpMyRideDbContext.InsertMaterialToDatabaseAndReturn(description: "smth", unitCost: 1).Id;
_workerId = PimpMyRideDbContext.InsertWorkerToDatabaseAndReturn(fio: "Worker").Id;
}
[TearDown]
public void TearDown()
{
PimpMyRideDbContext.RemoveServicesFromDatabase();
PimpMyRideDbContext.RemoveOrdersFromDatabase();
PimpMyRideDbContext.RemoveWorkersFromDatabase();
PimpMyRideDbContext.RemoveClientsFromDatabase();
PimpMyRideDbContext.RemoveCarsFromDatabase();
PimpMyRideDbContext.RemoveMaterialsFromDatabase();
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
PimpMyRideDbContext?.Database.EnsureDeleted();
PimpMyRideDbContext?.Dispose();
HttpClient?.Dispose();
_webApplication?.Dispose();
}
[Test]
public async Task LoadCars_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var Client1 = PimpMyRideDbContext.InsertClientToDatabaseAndReturn(fio: "Клиент 1", phoneNumber: "89991112233");
var Client2 = PimpMyRideDbContext.InsertClientToDatabaseAndReturn(fio: "Клиент 2", phoneNumber: "89991112234");
PimpMyRideDbContext.InsertCarToDatabaseAndReturn(clientId: Client1.Id, make: "ВАЗ", stateNumber: "911");
PimpMyRideDbContext.InsertCarToDatabaseAndReturn(clientId: Client1.Id, make: "ГАЗ", stateNumber: "912");
PimpMyRideDbContext.InsertCarToDatabaseAndReturn(clientId: Client1.Id, make: "УАЗ", stateNumber: "913");
PimpMyRideDbContext.InsertCarToDatabaseAndReturn(clientId: Client2.Id, make: "Toyota", stateNumber: "914");
PimpMyRideDbContext.InsertCarToDatabaseAndReturn(clientId: Client2.Id, make: "Ford", stateNumber: "915");
//Act
var response = await HttpClient.GetAsync("/api/report/LoadProducts");
//Assert
await AssertStreamAsync(response, $"file-{GetLocale()}.docx");
}
[Test]
public async Task LoadOrders_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var client = PimpMyRideDbContext.InsertClientToDatabaseAndReturn();
var car = PimpMyRideDbContext.InsertCarToDatabaseAndReturn(clientId: client.Id);
var material = PimpMyRideDbContext.InsertMaterialToDatabaseAndReturn(unitCost: 1);
var workerId = PimpMyRideDbContext.InsertWorkerToDatabaseAndReturn();
var service1 = PimpMyRideDbContext.InsertServiceToDatabaseAndReturn(workerId.Id, materials: [(material.Id, 1, 1)]);
var service2 = PimpMyRideDbContext.InsertServiceToDatabaseAndReturn(workerId.Id, materials: [(material.Id, 1, 1)]);
PimpMyRideDbContext.InsertOrderToDatabaseAndReturn(car.Id, services: [(service1.Id, 10, 1.1), (service2.Id, 10, 1.1)]);
PimpMyRideDbContext.InsertOrderToDatabaseAndReturn(car.Id, services: [(service1.Id, 10, 1.1)]);
//Act
var response = await HttpClient.GetAsync($"/api/report/loadorders?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
await AssertStreamAsync(response, $"file-{GetLocale()}.xlsx");
}
[Test]
public async Task LoadService_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var worker1 = PimpMyRideDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", specialityType: SpecialityType.TireFitter);
var worker2 = PimpMyRideDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", specialityType: SpecialityType.Mechanic);
var service1 = new ServiceDataModel(Guid.NewGuid().ToString(), worker1.Id, WorkType.Wheels, new ServiceConfiguration() { Rate = 10 }, []);
var service2 = new ServiceDataModel(Guid.NewGuid().ToString(), worker2.Id, WorkType.Body, new ServiceConfiguration() { Rate = 10 }, []);
PimpMyRideDbContext.InsertServiceToDatabaseAndReturn(worker1.Id, WorkType.Wheels, new ServiceConfiguration() { Rate = 100 }, [], serviceDate: DateTime.UtcNow.AddDays(-10));
PimpMyRideDbContext.InsertServiceToDatabaseAndReturn(worker1.Id, WorkType.Wheels, new ServiceConfiguration() { Rate = 1000 }, [], serviceDate: DateTime.UtcNow.AddDays(-5));
PimpMyRideDbContext.InsertServiceToDatabaseAndReturn(worker1.Id, WorkType.Wheels, new ServiceConfiguration() { Rate = 200 }, [], serviceDate: DateTime.UtcNow.AddDays(5));
PimpMyRideDbContext.InsertServiceToDatabaseAndReturn(worker2.Id, WorkType.Body, new ServiceConfiguration() { Rate = 500 }, [], serviceDate: DateTime.UtcNow.AddDays(-5));
PimpMyRideDbContext.InsertServiceToDatabaseAndReturn(worker2.Id, WorkType.Body, new ServiceConfiguration() { Rate = 300 }, [], serviceDate: DateTime.UtcNow.AddDays(-3));
//Act
var response = await HttpClient.GetAsync($"/api/report/loadservice?fromDate={DateTime.UtcNow.AddDays(-7):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
//Assert
await AssertStreamAsync(response, $"file-{GetLocale()}.pdf");
}
private static async Task AssertStreamAsync(HttpResponseMessage response, string fileNameForSave = "")
{
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
using var data = await response.Content.ReadAsStreamAsync();
Assert.That(data, Is.Not.Null);
Assert.That(data.Length, Is.GreaterThan(0));
await SaveStreamAsync(data, fileNameForSave);
}
private static async Task SaveStreamAsync(Stream stream, string fileName)
{
if (string.IsNullOrEmpty(fileName))
{
return;
}
var path = Path.Combine(Directory.GetCurrentDirectory(), fileName);
if (File.Exists(path))
{
File.Delete(path);
}
stream.Position = 0;
using var fileStream = new FileStream(path, FileMode.OpenOrCreate);
await stream.CopyToAsync(fileStream);
}
protected abstract string MessageElementNotFound();
[TestCase("car")]
[TestCase("client")]
[TestCase("material/getrecord")]
[TestCase("order/getrecord")]
[TestCase("service/getrecord")]
[TestCase("workers/getrecord")]
public async Task Api_GetElement_NotFound_Test(string path)
{
//Act
var response = await HttpClient.GetAsync($"/api/{path}/{Guid.NewGuid()}");
//Assert
Assert.That(JToken.Parse(await response.Content.ReadAsStringAsync()).ToString(), Does.StartWith(MessageElementNotFound()));
}
[TestCase("car")]
[TestCase("client")]
[TestCase("material/delete")]
[TestCase("order/cancel")]
[TestCase("service/cancel")]
[TestCase("workers/delete")]
public async Task Api_DeleteElement_NotFound_Test(string path)
{
var currentLocale = GetLocale();
//Act
var response = await HttpClient.DeleteAsync($"/api/{path}/{Guid.NewGuid()}");
//Assert
Assert.That(JToken.Parse(await response.Content.ReadAsStringAsync()).ToString(), Does.StartWith(MessageElementNotFound()));
}
private static IEnumerable<TestCaseData> TestDataElementExists()
{
yield return new TestCaseData(() => {
var model = CreateCarBindingModel(_clientId);
PimpMyRideDbContext.InsertCarToDatabaseAndReturn(model.Id, clientId: _clientId);
return model;
}, "car");
yield return new TestCaseData(() => {
var model = CreateClientModel();
PimpMyRideDbContext.InsertClientToDatabaseAndReturn(model.Id);
return model;
}, "client");
yield return new TestCaseData(() => {
var model = CreateMaterialModel();
PimpMyRideDbContext.InsertMaterialToDatabaseAndReturn(model.Id);
return model;
}, "material/register");
yield return new TestCaseData(() => {
var model = CreateWorkerModel();
PimpMyRideDbContext.InsertWorkerToDatabaseAndReturn(model.Id);
return model;
}, "workers/register");
}
protected abstract string MessageElementExists();
[TestCaseSource(nameof(TestDataElementExists))]
public async Task Api_Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test(Func<object> createModel, string path)
{
//Arrange
var model = createModel();
//Act
var response = await HttpClient.PostAsync($"/api/{path}", MakeContent(model));
//Assert
Assert.That(JToken.Parse(await response.Content.ReadAsStringAsync()).ToString(), Does.StartWith(MessageElementExists()));
}
private static IEnumerable<TestCaseData> TestDataElementWrongIds()
{
yield return new TestCaseData(() => {
var model = CreateCarBindingModel(_clientId);
model.Id = "smth";
return model;
}, "car");
yield return new TestCaseData(() => {
var model = CreateClientModel();
model.Id = "smth";
return model;
}, "client");
yield return new TestCaseData(() => {
var model = CreateMaterialModel();
model.Id = "smth";
return model;
}, "material/changeinfo");
yield return new TestCaseData(() => {
var model = CreateWorkerModel();
model.Id = "smth";
return model;
}, "workers/changeinfo");
}
protected abstract string MessageElementWrongId();
[TestCaseSource(nameof(TestDataElementWrongIds))]
public async Task Api_Put_WhenWrongData_ShouldBadRequest(Func<object> createModel, string path)
{
//Arrange
var model = createModel();
var currentLocale = GetLocale();
//Act
var response = await HttpClient.PutAsync($"/api/{path}", MakeContent(model));
var result = await response.Content.ReadAsStringAsync();
//Assert
Assert.That(JToken.Parse(await response.Content.ReadAsStringAsync()).ToString(), Does.StartWith(MessageElementWrongId()));
}
private static async Task<T?> GetModelFromResponseAsync<T>(HttpResponseMessage response) =>
JsonSerializer.Deserialize<T>(await response.Content.ReadAsStringAsync(), JsonSerializerOptions);
private static StringContent MakeContent(object model) =>
new(JsonSerializer.Serialize(model), Encoding.UTF8, "application/json");
private static CarBindingModel CreateCarBindingModel(string clientId, string? id = null, string make = "bmw", string model = "5", string stateNumber = "a111aa") =>
new()
{
Id = id ?? Guid.NewGuid().ToString(),
ClientId = clientId,
Make = make,
Model = model,
StateNumber = stateNumber
};
private static ClientBindingModel CreateClientModel(string? id = null, string? fio = "name", string? phoneNumber = "88005553535")
=> new()
{
Id = id ?? Guid.NewGuid().ToString(),
FIO = fio,
PhoneNumber = phoneNumber
};
private static MaterialBindingModel CreateMaterialModel(string? id = null, MaterialType materialType = MaterialType.EngineParts, string? description = "smth", double unitCost = 10)
=> new()
{
Id = id ?? Guid.NewGuid().ToString(),
MaterialType = materialType.ToString(),
Description = description,
UnitCost = unitCost
};
//private static OrderBindingModel CreateOrderModel(string carId, string serviceId, string? id = null, int count = 1, int price = 10)
// => new()
// {
// Id = id ?? Guid.NewGuid().ToString(),
// CarId = carId,
// Services = productName
// };
//private static ServiceBindingModel CreateServiceModel(string workerId, string? buyerId, string productId, string? id = null, DiscountType discountType = DiscountType.OnSale, int count = 1, double price = 1.1)
//{
// var saleId = id ?? Guid.NewGuid().ToString();
// return new()
// {
// Id = saleId,
// WorkerId = workerId,
// BuyerId = buyerId,
// DiscountType = (int)discountType,
// Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = productId, Count = count, Price = price }]
// ConfigurationJson = configuration ?? JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 })
// };
//}
private static WorkerBindingModel CreateWorkerModel(string? id = null, string fio = "fio", SpecialityType speciality = SpecialityType.TireFitter, DateTime? birthDate = null, DateTime? employmentDate = null)
{
return new()
{
Id = id ?? Guid.NewGuid().ToString(),
FIO = fio,
SpecialityType = speciality,
BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-22),
EmploymentDate = employmentDate ?? DateTime.UtcNow.AddDays(-5)
};
}
}

View File

@@ -0,0 +1,10 @@
namespace PimpMyRideTest.LocalizationTests;
[TestFixture]
internal class DeDETests : BaseLocalizationControllerTest
{
protected override string GetLocale() => "de-DE";
protected override string MessageElementExists() => "Es gibt bereits ein Element mit dem Wert";
protected override string MessageElementNotFound() => "Nicht gefundenes Element durch Daten";
protected override string MessageElementWrongId() => "Falsche Daten übermittelt";
}

View File

@@ -0,0 +1,10 @@
namespace PimpMyRideTest.LocalizationTests;
[TestFixture]
internal class DefaultTests : BaseLocalizationControllerTest
{
protected override string GetLocale() => "bla-BLA";
protected override string MessageElementExists() => "Уже существует элемент со значением";
protected override string MessageElementNotFound() => "Не найден элемент по данным";
protected override string MessageElementWrongId() => "Переданы неверные данные";
}

View File

@@ -0,0 +1,10 @@
namespace PimpMyRideTest.LocalizationTests;
[TestFixture]
internal class EnUSTests : BaseLocalizationControllerTest
{
protected override string GetLocale() => "en-US";
protected override string MessageElementExists() => "There is already an element with value";
protected override string MessageElementNotFound() => "Not found element by data";
protected override string MessageElementWrongId() => "Incorrect data transmitted";
}

View File

@@ -0,0 +1,10 @@
namespace PimpMyRideTest.LocalizationTests;
[TestFixture]
internal class RuRUTests : BaseLocalizationControllerTest
{
protected override string GetLocale() => "ru-RU";
protected override string MessageElementExists() => "Уже существует элемент со значением";
protected override string MessageElementNotFound() => "Не найден элемент по данным";
protected override string MessageElementWrongId() => "Переданы неверные данные";
}

View File

@@ -16,7 +16,7 @@ internal class CarStorageContractTests : BaseStorageContractTest
[SetUp] [SetUp]
public void SetUp() public void SetUp()
{ {
_carStorageContract = new CarStorageContract(PimpMyRideDbContext); _carStorageContract = new CarStorageContract(PimpMyRideDbContext, StringLocalizerMockCreator.GetObject());
_client = PimpMyRideDbContext.InsertClientToDatabaseAndReturn(); _client = PimpMyRideDbContext.InsertClientToDatabaseAndReturn();
} }

View File

@@ -17,7 +17,7 @@ internal class ClientStorageContractTests : BaseStorageContractTest
[SetUp] [SetUp]
public void SetUp() public void SetUp()
{ {
_clientStorageContract = new ClientStorageContract(PimpMyRideDbContext); _clientStorageContract = new ClientStorageContract(PimpMyRideDbContext, StringLocalizerMockCreator.GetObject());
} }
[TearDown] [TearDown]

View File

@@ -16,7 +16,7 @@ internal class MaterialStorageContractsTests : BaseStorageContractTest
[SetUp] [SetUp]
public void SetUp() public void SetUp()
{ {
_materialStorageContract = new MaterialStorageContracts(PimpMyRideDbContext); _materialStorageContract = new MaterialStorageContracts(PimpMyRideDbContext, StringLocalizerMockCreator.GetObject());
} }
[TearDown] [TearDown]

View File

@@ -23,7 +23,7 @@ internal class OrderStorageContractTests : BaseStorageContractTest
[SetUp] [SetUp]
public void SetUp() public void SetUp()
{ {
_orderStorageContract = new OrderStorageContract(PimpMyRideDbContext); _orderStorageContract = new OrderStorageContract(PimpMyRideDbContext, StringLocalizerMockCreator.GetObject());
_client = InsertClientToDatabaseAndReturn(); _client = InsertClientToDatabaseAndReturn();
_car = InsertCarToDatabaseAndReturn(); _car = InsertCarToDatabaseAndReturn();
_worker = InsertWorkerToDatabaseAndReturn(); _worker = InsertWorkerToDatabaseAndReturn();

View File

@@ -20,7 +20,7 @@ internal class ServiceStorageContractsTests : BaseStorageContractTest
[SetUp] [SetUp]
public void SetUp() public void SetUp()
{ {
_serviceStorageContract = new ServiceStorageContracts(PimpMyRideDbContext); _serviceStorageContract = new ServiceStorageContracts(PimpMyRideDbContext, StringLocalizerMockCreator.GetObject());
_worker = PimpMyRideDbContext.InsertWorkerToDatabaseAndReturn(); _worker = PimpMyRideDbContext.InsertWorkerToDatabaseAndReturn();
_material = PimpMyRideDbContext.InsertMaterialToDatabaseAndReturn(); _material = PimpMyRideDbContext.InsertMaterialToDatabaseAndReturn();
} }

View File

@@ -17,7 +17,7 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
[SetUp] [SetUp]
public void SetUp() public void SetUp()
{ {
_workerStorageContract = new WorkerStorageContract(PimpMyRideDbContext); _workerStorageContract = new WorkerStorageContract(PimpMyRideDbContext, StringLocalizerMockCreator.GetObject());
} }
[TearDown] [TearDown]

View File

@@ -146,7 +146,7 @@ internal class WorkerControllerTests : BaseWebApiControllerTest
PimpMyRideDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", birthDate: DateTime.UtcNow.AddYears(-20), isDeleted: true); PimpMyRideDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", birthDate: DateTime.UtcNow.AddYears(-20), isDeleted: true);
PimpMyRideDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", birthDate: DateTime.UtcNow.AddYears(-19)); PimpMyRideDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", birthDate: DateTime.UtcNow.AddYears(-19));
//Act //Act
var response = await HttpClient.GetAsync($"/api/workers/getbirthdaterecords?fromDate={DateTime.UtcNow.AddYears(-21).AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddYears(-20).AddMinutes(1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true"); var response = await HttpClient.GetAsync($"/api/workers/getbirthdaterecords?fromDate={DateTime.Now.AddYears(-21).AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddYears(-20).AddMinutes(1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true");
//Assert //Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(response); var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(response);
@@ -161,7 +161,7 @@ internal class WorkerControllerTests : BaseWebApiControllerTest
public async Task GetList_ByBirthDate_WhenDateIsIncorrect_ShouldBadRequest_Test() public async Task GetList_ByBirthDate_WhenDateIsIncorrect_ShouldBadRequest_Test()
{ {
//Act //Act
var response = await HttpClient.GetAsync($"/api/workers/getbirthdaterecords?fromDate={DateTime.UtcNow.AddMinutes(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true"); var response = await HttpClient.GetAsync($"/api/workers/getbirthdaterecords?fromDate={DateTime.Now.AddMinutes(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true");
//Assert //Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest)); Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
} }
@@ -175,7 +175,7 @@ internal class WorkerControllerTests : BaseWebApiControllerTest
PimpMyRideDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", employmentDate: DateTime.UtcNow.AddDays(1), isDeleted: true); PimpMyRideDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 3", employmentDate: DateTime.UtcNow.AddDays(1), isDeleted: true);
PimpMyRideDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", employmentDate: DateTime.UtcNow.AddDays(2)); PimpMyRideDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 4", employmentDate: DateTime.UtcNow.AddDays(2));
//Act //Act
var response = await HttpClient.GetAsync($"/api/workers/getemploymentrecords?fromDate={DateTime.UtcNow.AddDays(-1).AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1).AddMinutes(1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true"); var response = await HttpClient.GetAsync($"/api/workers/getemploymentrecords?fromDate={DateTime.Now.AddDays(-1).AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(1).AddMinutes(1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true");
//Assert //Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(response); var data = await GetModelFromResponseAsync<List<WorkerViewModel>>(response);
@@ -190,7 +190,7 @@ internal class WorkerControllerTests : BaseWebApiControllerTest
public async Task GetList_ByEmploymentDate_WhenDateIsIncorrect_ShouldBadRequest_Test() public async Task GetList_ByEmploymentDate_WhenDateIsIncorrect_ShouldBadRequest_Test()
{ {
//Act //Act
var response = await HttpClient.GetAsync($"/api/workers/getemploymentrecords?fromDate={DateTime.UtcNow.AddMinutes(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true"); var response = await HttpClient.GetAsync($"/api/workers/getemploymentrecords?fromDate={DateTime.Now.AddMinutes(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true");
//Assert //Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest)); Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
} }

View File

@@ -1,21 +1,24 @@
using AutoMapper; using AutoMapper;
using Microsoft.Extensions.Localization;
using PimpMyRideContracts.AdapterContracts; using PimpMyRideContracts.AdapterContracts;
using PimpMyRideContracts.AdapterContracts.OperationResponses; using PimpMyRideContracts.AdapterContracts.OperationResponses;
using PimpMyRideContracts.BindingModels; using PimpMyRideContracts.BindingModels;
using PimpMyRideContracts.BusinessLogicsContracts; using PimpMyRideContracts.BusinessLogicsContracts;
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Resources;
using PimpMyRideContracts.ViewModels; using PimpMyRideContracts.ViewModels;
namespace PimpMyRideWebApi.Adapters; namespace PimpMyRideWebApi.Adapters;
public class CarAdapter : ICarAdapter internal class CarAdapter : ICarAdapter
{ {
private readonly ICarBusinessLogicContract _carBusinessLogicContract; private readonly ICarBusinessLogicContract _carBusinessLogicContract;
private readonly IStringLocalizer<Messages> _localizer;
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly Mapper _mapper; private readonly Mapper _mapper;
public CarAdapter(ICarBusinessLogicContract carBusinessLogicContract, ILogger<CarAdapter> logger) public CarAdapter(ICarBusinessLogicContract carBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<CarAdapter> logger)
{ {
_carBusinessLogicContract = carBusinessLogicContract; _carBusinessLogicContract = carBusinessLogicContract;
_logger = logger; _logger = logger;
@@ -24,6 +27,7 @@ public class CarAdapter : ICarAdapter
cfg.CreateMap<CarDataModel, CarViewModel>(); cfg.CreateMap<CarDataModel, CarViewModel>();
}); });
_mapper = new Mapper(config); _mapper = new Mapper(config);
_localizer = localizer;
} }
public CarOperationResponse GetList() public CarOperationResponse GetList()
@@ -32,15 +36,10 @@ public class CarAdapter : ICarAdapter
{ {
return CarOperationResponse.OK([.. _carBusinessLogicContract.GetAllCars().Select(x => _mapper.Map<CarViewModel>(x))]); return CarOperationResponse.OK([.. _carBusinessLogicContract.GetAllCars().Select(x => _mapper.Map<CarViewModel>(x))]);
} }
catch (NullListException)
{
_logger.LogError("NullListException");
return CarOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return CarOperationResponse.InternalServerError($"Error while working with data storage: { ex.InnerException!.Message}"); return CarOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -58,17 +57,12 @@ public class CarAdapter : ICarAdapter
catch (ValidationException ex) catch (ValidationException ex)
{ {
_logger.LogError(ex, "ValidationException"); _logger.LogError(ex, "ValidationException");
return CarOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}"); return CarOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (NullListException)
{
_logger.LogError("NullListException");
return CarOperationResponse.NotFound("The list is not initialized");
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return CarOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return CarOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -86,17 +80,12 @@ public class CarAdapter : ICarAdapter
catch (ValidationException ex) catch (ValidationException ex)
{ {
_logger.LogError(ex, "ValidationException"); _logger.LogError(ex, "ValidationException");
return CarOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}"); return CarOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (NullListException)
{
_logger.LogError("NullListException");
return CarOperationResponse.NotFound("The list is not initialized");
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return CarOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return CarOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -115,17 +104,17 @@ public class CarAdapter : ICarAdapter
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
_logger.LogError(ex, "ArgumentNullException"); _logger.LogError(ex, "ArgumentNullException");
return CarOperationResponse.BadRequest("Data is empty"); return CarOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
} }
catch (ElementNotFoundException ex) catch (ElementNotFoundException ex)
{ {
_logger.LogError(ex, "ElementNotFoundException"); _logger.LogError(ex, "ElementNotFoundException");
return CarOperationResponse.NotFound($"Not found element by data {data}"); return CarOperationResponse.NotFound(string.Format(_localizer["AdapterMessageElementNotFoundException"], data));
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return CarOperationResponse.InternalServerError($"Error while working with data storage: { ex.InnerException!.Message}"); return CarOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -144,12 +133,12 @@ public class CarAdapter : ICarAdapter
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
_logger.LogError(ex, "ArgumentNullException"); _logger.LogError(ex, "ArgumentNullException");
return CarOperationResponse.BadRequest("Data is empty"); return CarOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
} }
catch (ValidationException ex) catch (ValidationException ex)
{ {
_logger.LogError(ex, "ValidationException"); _logger.LogError(ex, "ValidationException");
return CarOperationResponse.BadRequest($"Incorrect data transmitted: { ex.Message}"); return CarOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
} }
catch (ElementExistsException ex) catch (ElementExistsException ex)
{ {
@@ -159,7 +148,7 @@ public class CarAdapter : ICarAdapter
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return CarOperationResponse.BadRequest($"Error while working with data storage: { ex.InnerException!.Message}"); return CarOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -178,17 +167,17 @@ public class CarAdapter : ICarAdapter
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
_logger.LogError(ex, "ArgumentNullException"); _logger.LogError(ex, "ArgumentNullException");
return CarOperationResponse.BadRequest("Data is empty"); return CarOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
} }
catch (ValidationException ex) catch (ValidationException ex)
{ {
_logger.LogError(ex, "ValidationException"); _logger.LogError(ex, "ValidationException");
return CarOperationResponse.BadRequest($"Incorrect data transmitted: { ex.Message}"); return CarOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
} }
catch (ElementNotFoundException ex) catch (ElementNotFoundException ex)
{ {
_logger.LogError(ex, "ElementNotFoundException"); _logger.LogError(ex, "ElementNotFoundException");
return CarOperationResponse.BadRequest($"Not found element by Id { carModel.Id}"); return CarOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], carModel.Id));
} }
catch (ElementExistsException ex) catch (ElementExistsException ex)
{ {
@@ -198,7 +187,7 @@ public class CarAdapter : ICarAdapter
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return CarOperationResponse.BadRequest($"Error while working with data storage: { ex.InnerException!.Message}"); return CarOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -217,22 +206,22 @@ public class CarAdapter : ICarAdapter
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
_logger.LogError(ex, "ArgumentNullException"); _logger.LogError(ex, "ArgumentNullException");
return CarOperationResponse.BadRequest("Id is empty"); return CarOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
} }
catch (ValidationException ex) catch (ValidationException ex)
{ {
_logger.LogError(ex, "ValidationException"); _logger.LogError(ex, "ValidationException");
return CarOperationResponse.BadRequest($"Incorrect data transmitted: { ex.Message}"); return CarOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
} }
catch (ElementNotFoundException ex) catch (ElementNotFoundException ex)
{ {
_logger.LogError(ex, "ElementNotFoundException"); _logger.LogError(ex, "ElementNotFoundException");
return CarOperationResponse.BadRequest($"Not found element by id: { id}"); return CarOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], id));
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return CarOperationResponse.BadRequest($"Error while working with data storage: { ex.InnerException!.Message}"); return CarOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@@ -1,21 +1,24 @@
using AutoMapper; using AutoMapper;
using Microsoft.Extensions.Localization;
using PimpMyRideContracts.AdapterContracts; using PimpMyRideContracts.AdapterContracts;
using PimpMyRideContracts.AdapterContracts.OperationResponses; using PimpMyRideContracts.AdapterContracts.OperationResponses;
using PimpMyRideContracts.BindingModels; using PimpMyRideContracts.BindingModels;
using PimpMyRideContracts.BusinessLogicsContracts; using PimpMyRideContracts.BusinessLogicsContracts;
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Resources;
using PimpMyRideContracts.ViewModels; using PimpMyRideContracts.ViewModels;
namespace PimpMyRideWebApi.Adapters; namespace PimpMyRideWebApi.Adapters;
public class ClientAdapter : IClientAdapter internal class ClientAdapter : IClientAdapter
{ {
private readonly IClientBusinessLogicContract _clientBusinessLogicContract; private readonly IClientBusinessLogicContract _clientBusinessLogicContract;
private readonly IStringLocalizer<Messages> _localizer;
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly Mapper _mapper; private readonly Mapper _mapper;
public ClientAdapter(IClientBusinessLogicContract clientBusinessLogicContract, ILogger<ClientAdapter> logger) public ClientAdapter(IClientBusinessLogicContract clientBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<ClientAdapter> logger)
{ {
_clientBusinessLogicContract = clientBusinessLogicContract; _clientBusinessLogicContract = clientBusinessLogicContract;
_logger = logger; _logger = logger;
@@ -24,6 +27,7 @@ public class ClientAdapter : IClientAdapter
cfg.CreateMap<ClientDataModel, ClientViewModel>(); cfg.CreateMap<ClientDataModel, ClientViewModel>();
}); });
_mapper = new Mapper(config); _mapper = new Mapper(config);
_localizer = localizer;
} }
public ClientOperationResponse GetList() public ClientOperationResponse GetList()
@@ -32,15 +36,10 @@ public class ClientAdapter : IClientAdapter
{ {
return ClientOperationResponse.OK([.. _clientBusinessLogicContract.GetAllClients().Select(x => _mapper.Map<ClientViewModel>(x))]); return ClientOperationResponse.OK([.. _clientBusinessLogicContract.GetAllClients().Select(x => _mapper.Map<ClientViewModel>(x))]);
} }
catch (NullListException)
{
_logger.LogError("NullListException");
return ClientOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return ClientOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return ClientOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -59,17 +58,17 @@ public class ClientAdapter : IClientAdapter
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
_logger.LogError(ex, "ArgumentNullException"); _logger.LogError(ex, "ArgumentNullException");
return ClientOperationResponse.BadRequest("Data is empty"); return ClientOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
} }
catch (ElementNotFoundException ex) catch (ElementNotFoundException ex)
{ {
_logger.LogError(ex, "ElementNotFoundException"); _logger.LogError(ex, "ElementNotFoundException");
return ClientOperationResponse.NotFound($"Not found element by data {data}"); return ClientOperationResponse.NotFound(string.Format(_localizer["AdapterMessageElementNotFoundException"], data));
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return ClientOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return ClientOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -88,12 +87,12 @@ public class ClientAdapter : IClientAdapter
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
_logger.LogError(ex, "ArgumentNullException"); _logger.LogError(ex, "ArgumentNullException");
return ClientOperationResponse.BadRequest("Data is empty"); return ClientOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
} }
catch (ValidationException ex) catch (ValidationException ex)
{ {
_logger.LogError(ex, "ValidationException"); _logger.LogError(ex, "ValidationException");
return ClientOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}"); return ClientOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
} }
catch (ElementExistsException ex) catch (ElementExistsException ex)
{ {
@@ -103,7 +102,7 @@ public class ClientAdapter : IClientAdapter
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return ClientOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}"); return ClientOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -122,17 +121,17 @@ public class ClientAdapter : IClientAdapter
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
_logger.LogError(ex, "ArgumentNullException"); _logger.LogError(ex, "ArgumentNullException");
return ClientOperationResponse.BadRequest("Data is empty"); return ClientOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
} }
catch (ValidationException ex) catch (ValidationException ex)
{ {
_logger.LogError(ex, "ValidationException"); _logger.LogError(ex, "ValidationException");
return ClientOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}"); return ClientOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
} }
catch (ElementNotFoundException ex) catch (ElementNotFoundException ex)
{ {
_logger.LogError(ex, "ElementNotFoundException"); _logger.LogError(ex, "ElementNotFoundException");
return ClientOperationResponse.BadRequest($"Not found element by Id {clientModel.Id}"); return ClientOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], clientModel.Id));
} }
catch (ElementExistsException ex) catch (ElementExistsException ex)
{ {
@@ -142,7 +141,7 @@ public class ClientAdapter : IClientAdapter
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return ClientOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}"); return ClientOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -161,22 +160,22 @@ public class ClientAdapter : IClientAdapter
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
_logger.LogError(ex, "ArgumentNullException"); _logger.LogError(ex, "ArgumentNullException");
return ClientOperationResponse.BadRequest("Id is empty"); return ClientOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
} }
catch (ValidationException ex) catch (ValidationException ex)
{ {
_logger.LogError(ex, "ValidationException"); _logger.LogError(ex, "ValidationException");
return ClientOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}"); return ClientOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
} }
catch (ElementNotFoundException ex) catch (ElementNotFoundException ex)
{ {
_logger.LogError(ex, "ElementNotFoundException"); _logger.LogError(ex, "ElementNotFoundException");
return ClientOperationResponse.BadRequest($"Not found element by id: {id}"); return ClientOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], id));
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return ClientOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}"); return ClientOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@@ -1,4 +1,6 @@
using AutoMapper; using AutoMapper;
using DocumentFormat.OpenXml.Office2010.Excel;
using Microsoft.Extensions.Localization;
using PimpMyRideContracts.AdapterContracts; using PimpMyRideContracts.AdapterContracts;
using PimpMyRideContracts.AdapterContracts.OperationResponses; using PimpMyRideContracts.AdapterContracts.OperationResponses;
using PimpMyRideContracts.BindingModels; using PimpMyRideContracts.BindingModels;
@@ -6,19 +8,22 @@ using PimpMyRideContracts.BusinessLogicsContracts;
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Enums; using PimpMyRideContracts.Enums;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Resources;
using PimpMyRideContracts.ViewModels; using PimpMyRideContracts.ViewModels;
namespace PimpMyRideWebApi.Adapters; namespace PimpMyRideWebApi.Adapters;
public class MaterialAdapter : IMaterialAdapter internal class MaterialAdapter : IMaterialAdapter
{ {
private readonly IMaterialBusinessLogicContract _materialBusinessLogicContract; private readonly IMaterialBusinessLogicContract _materialBusinessLogicContract;
private readonly IStringLocalizer<Messages> _localizer;
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly Mapper _mapper; private readonly Mapper _mapper;
public MaterialAdapter(IMaterialBusinessLogicContract materialBusinessLogicContract, ILogger<MaterialAdapter> logger) public MaterialAdapter(IMaterialBusinessLogicContract materialBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<MaterialAdapter> logger)
{ {
_materialBusinessLogicContract = materialBusinessLogicContract; _materialBusinessLogicContract = materialBusinessLogicContract;
_logger = logger; _logger = logger;
@@ -29,6 +34,7 @@ public class MaterialAdapter : IMaterialAdapter
cfg.CreateMap<MaterialHistoryDataModel, MaterialHistoryViewModel>(); cfg.CreateMap<MaterialHistoryDataModel, MaterialHistoryViewModel>();
}); });
_mapper = new Mapper(config); _mapper = new Mapper(config);
_localizer = localizer;
} }
public MaterialOperationResponse GetList() public MaterialOperationResponse GetList()
@@ -37,15 +43,10 @@ public class MaterialAdapter : IMaterialAdapter
{ {
return MaterialOperationResponse.OK([.. _materialBusinessLogicContract.GetAllMaterials().Select(x => _mapper.Map<MaterialViewModel>(x))]); return MaterialOperationResponse.OK([.. _materialBusinessLogicContract.GetAllMaterials().Select(x => _mapper.Map<MaterialViewModel>(x))]);
} }
catch (NullListException)
{
_logger.LogError("NullListException");
return MaterialOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return MaterialOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return MaterialOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -63,22 +64,17 @@ public class MaterialAdapter : IMaterialAdapter
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
_logger.LogError(ex, "ArgumentNullException"); _logger.LogError(ex, "ArgumentNullException");
return MaterialOperationResponse.BadRequest("Data is empty"); return MaterialOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
} }
catch (ValidationException ex) catch (ValidationException ex)
{ {
_logger.LogError(ex, "ValidationException"); _logger.LogError(ex, "ValidationException");
return MaterialOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}"); return MaterialOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (NullListException)
{
_logger.LogError("NullListException");
return MaterialOperationResponse.NotFound("The list is not initialized");
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return MaterialOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return MaterialOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -96,17 +92,12 @@ public class MaterialAdapter : IMaterialAdapter
catch (ValidationException ex) catch (ValidationException ex)
{ {
_logger.LogError(ex, "ValidationException"); _logger.LogError(ex, "ValidationException");
return MaterialOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}"); return MaterialOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (NullListException)
{
_logger.LogError("NullListException");
return MaterialOperationResponse.NotFound("The list is not initialized");
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return MaterialOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return MaterialOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -124,22 +115,22 @@ public class MaterialAdapter : IMaterialAdapter
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
_logger.LogError(ex, "ArgumentNullException"); _logger.LogError(ex, "ArgumentNullException");
return MaterialOperationResponse.BadRequest("Data is empty"); return MaterialOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
} }
catch (ElementNotFoundException ex) catch (ElementNotFoundException ex)
{ {
_logger.LogError(ex, "ElementNotFoundException"); _logger.LogError(ex, "ElementNotFoundException");
return MaterialOperationResponse.NotFound($"Not found element by data {data}"); return MaterialOperationResponse.NotFound(string.Format(_localizer["AdapterMessageElementNotFoundException"], data));
} }
catch (ElementDeletedException ex) catch (ElementDeletedException ex)
{ {
_logger.LogError(ex, "ElementDeletedException"); _logger.LogError(ex, "ElementDeletedException");
return MaterialOperationResponse.BadRequest($"Element by data: {data} was deleted"); return MaterialOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], data));
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return MaterialOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return MaterialOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -158,12 +149,12 @@ public class MaterialAdapter : IMaterialAdapter
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
_logger.LogError(ex, "ArgumentNullException"); _logger.LogError(ex, "ArgumentNullException");
return MaterialOperationResponse.BadRequest("Data is empty"); return MaterialOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
} }
catch (ValidationException ex) catch (ValidationException ex)
{ {
_logger.LogError(ex, "ValidationException"); _logger.LogError(ex, "ValidationException");
return MaterialOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}"); return MaterialOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
} }
catch (ElementExistsException ex) catch (ElementExistsException ex)
{ {
@@ -173,7 +164,7 @@ public class MaterialAdapter : IMaterialAdapter
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return MaterialOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}"); return MaterialOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -192,17 +183,17 @@ public class MaterialAdapter : IMaterialAdapter
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
_logger.LogError(ex, "ArgumentNullException"); _logger.LogError(ex, "ArgumentNullException");
return MaterialOperationResponse.BadRequest("Data is empty"); return MaterialOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
} }
catch (ValidationException ex) catch (ValidationException ex)
{ {
_logger.LogError(ex, "ValidationException"); _logger.LogError(ex, "ValidationException");
return MaterialOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}"); return MaterialOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
} }
catch (ElementNotFoundException ex) catch (ElementNotFoundException ex)
{ {
_logger.LogError(ex, "ElementNotFoundException"); _logger.LogError(ex, "ElementNotFoundException");
return MaterialOperationResponse.BadRequest($"Not found element by Id {materialModel.Id}"); return MaterialOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], materialModel.Id));
} }
catch (ElementExistsException ex) catch (ElementExistsException ex)
{ {
@@ -212,7 +203,7 @@ public class MaterialAdapter : IMaterialAdapter
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return MaterialOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}"); return MaterialOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -231,22 +222,22 @@ public class MaterialAdapter : IMaterialAdapter
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
_logger.LogError(ex, "ArgumentNullException"); _logger.LogError(ex, "ArgumentNullException");
return MaterialOperationResponse.BadRequest("Id is empty"); return MaterialOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
} }
catch (ValidationException ex) catch (ValidationException ex)
{ {
_logger.LogError(ex, "ValidationException"); _logger.LogError(ex, "ValidationException");
return MaterialOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}"); return MaterialOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
} }
catch (ElementNotFoundException ex) catch (ElementNotFoundException ex)
{ {
_logger.LogError(ex, "ElementNotFoundException"); _logger.LogError(ex, "ElementNotFoundException");
return MaterialOperationResponse.BadRequest($"Not found element by id: {id}"); return MaterialOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], id));
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return MaterialOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}"); return MaterialOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@@ -1,23 +1,27 @@
using AutoMapper; using AutoMapper;
using Microsoft.Extensions.Localization;
using PimpMyRideContracts.AdapterContracts; using PimpMyRideContracts.AdapterContracts;
using PimpMyRideContracts.AdapterContracts.OperationResponses; using PimpMyRideContracts.AdapterContracts.OperationResponses;
using PimpMyRideContracts.BindingModels; using PimpMyRideContracts.BindingModels;
using PimpMyRideContracts.BusinessLogicsContracts; using PimpMyRideContracts.BusinessLogicsContracts;
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Resources;
using PimpMyRideContracts.ViewModels; using PimpMyRideContracts.ViewModels;
namespace PimpMyRideWebApi.Adapters; namespace PimpMyRideWebApi.Adapters;
public class OrderAdapter : IOrderAdapter internal class OrderAdapter : IOrderAdapter
{ {
private readonly IOrderBusinessLogicContract _orderBusinessLogicContract; private readonly IOrderBusinessLogicContract _orderBusinessLogicContract;
private readonly IStringLocalizer<Messages> _localizer;
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly Mapper _mapper; private readonly Mapper _mapper;
public OrderAdapter(IOrderBusinessLogicContract orderBusinessLogicContract, ILogger<OrderAdapter> logger) public OrderAdapter(IOrderBusinessLogicContract orderBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<OrderAdapter> logger)
{ {
_orderBusinessLogicContract = orderBusinessLogicContract; _orderBusinessLogicContract = orderBusinessLogicContract;
_logger = logger; _logger = logger;
@@ -33,28 +37,24 @@ public class OrderAdapter : IOrderAdapter
.ForCtorParam("orderServices", opt => opt.MapFrom(src => src.Services)); .ForCtorParam("orderServices", opt => opt.MapFrom(src => src.Services));
}); });
_mapper = new Mapper(config); _mapper = new Mapper(config);
_localizer = localizer;
} }
public OrderOperationResponse GetList(DateTime fromDate, DateTime toDate) public OrderOperationResponse GetList(DateTime fromDate, DateTime toDate)
{ {
try try
{ {
return OrderOperationResponse.OK([.. _orderBusinessLogicContract.GetAllOrdersByPeriod(fromDate, toDate).Select(x => _mapper.Map<OrderViewModel>(x))]); return OrderOperationResponse.OK([.. _orderBusinessLogicContract.GetAllOrdersByPeriod(fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => _mapper.Map<OrderViewModel>(x))]);
} }
catch (IncorrectDatesException ex) catch (IncorrectDatesException ex)
{ {
_logger.LogError(ex, "IncorrectDatesException"); _logger.LogError(ex, "IncorrectDatesException");
return OrderOperationResponse.BadRequest($"Incorrect dates: {ex.Message}"); return OrderOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageIncorrectDatesException"], ex.Message));
}
catch (NullListException)
{
_logger.LogError("NullListException");
return OrderOperationResponse.NotFound("The list is not initialized");
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return OrderOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return OrderOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -67,27 +67,22 @@ public class OrderAdapter : IOrderAdapter
{ {
try try
{ {
return OrderOperationResponse.OK([.. _orderBusinessLogicContract.GetAllOrdersByCarByPeriod(id, fromDate, toDate).Select(x => _mapper.Map<OrderViewModel>(x))]); return OrderOperationResponse.OK([.. _orderBusinessLogicContract.GetAllOrdersByCarByPeriod(id, fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => _mapper.Map<OrderViewModel>(x))]);
} }
catch (IncorrectDatesException ex) catch (IncorrectDatesException ex)
{ {
_logger.LogError(ex, "IncorrectDatesException"); _logger.LogError(ex, "IncorrectDatesException");
return OrderOperationResponse.BadRequest($"Incorrect dates: {ex.Message}"); return OrderOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageIncorrectDatesException"], ex.Message));
} }
catch (ValidationException ex) catch (ValidationException ex)
{ {
_logger.LogError(ex, "ValidationException"); _logger.LogError(ex, "ValidationException");
return OrderOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}"); return OrderOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (NullListException)
{
_logger.LogError("NullListException");
return OrderOperationResponse.NotFound("The list is not initialized");
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return OrderOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return OrderOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -105,22 +100,22 @@ public class OrderAdapter : IOrderAdapter
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
_logger.LogError(ex, "ArgumentNullException"); _logger.LogError(ex, "ArgumentNullException");
return OrderOperationResponse.BadRequest("Data is empty"); return OrderOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
} }
catch (ValidationException ex) catch (ValidationException ex)
{ {
_logger.LogError(ex, "ValidationException"); _logger.LogError(ex, "ValidationException");
return OrderOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}"); return OrderOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
} }
catch (ElementNotFoundException ex) catch (ElementNotFoundException ex)
{ {
_logger.LogError(ex, "ElementNotFoundException"); _logger.LogError(ex, "ElementNotFoundException");
return OrderOperationResponse.NotFound($"Not found element by data {id}"); return OrderOperationResponse.NotFound(string.Format(_localizer["AdapterMessageElementNotFoundException"], id));
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return OrderOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return OrderOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -140,17 +135,17 @@ public class OrderAdapter : IOrderAdapter
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
_logger.LogError(ex, "ArgumentNullException"); _logger.LogError(ex, "ArgumentNullException");
return OrderOperationResponse.BadRequest("Data is empty"); return OrderOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
} }
catch (ValidationException ex) catch (ValidationException ex)
{ {
_logger.LogError(ex, "ValidationException"); _logger.LogError(ex, "ValidationException");
return OrderOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}"); return OrderOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return OrderOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}"); return OrderOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -169,27 +164,27 @@ public class OrderAdapter : IOrderAdapter
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
_logger.LogError(ex, "ArgumentNullException"); _logger.LogError(ex, "ArgumentNullException");
return OrderOperationResponse.BadRequest("Id is empty"); return OrderOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
} }
catch (ValidationException ex) catch (ValidationException ex)
{ {
_logger.LogError(ex, "ValidationException"); _logger.LogError(ex, "ValidationException");
return OrderOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}"); return OrderOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
} }
catch (ElementNotFoundException ex) catch (ElementNotFoundException ex)
{ {
_logger.LogError(ex, "ElementNotFoundException"); _logger.LogError(ex, "ElementNotFoundException");
return OrderOperationResponse.BadRequest($"Not found element by id: {id}"); return OrderOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], id));
} }
catch (ElementDeletedException ex) catch (ElementDeletedException ex)
{ {
_logger.LogError(ex, "ElementDeletedException"); _logger.LogError(ex, "ElementDeletedException");
return OrderOperationResponse.BadRequest($"Element by id: {id} was deleted"); return OrderOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], id));
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return OrderOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}"); return OrderOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@@ -1,4 +1,5 @@
using AutoMapper; using AutoMapper;
using Microsoft.Extensions.Localization;
using PimpMyRideBusinessLogic.Implementations; using PimpMyRideBusinessLogic.Implementations;
using PimpMyRideContracts.AdapterContracts; using PimpMyRideContracts.AdapterContracts;
using PimpMyRideContracts.AdapterContracts.OperationResponses; using PimpMyRideContracts.AdapterContracts.OperationResponses;
@@ -6,19 +7,22 @@ using PimpMyRideContracts.BindingModels;
using PimpMyRideContracts.BusinessLogicsContracts; using PimpMyRideContracts.BusinessLogicsContracts;
using PimpMyRideContracts.DataModels; using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Resources;
using PimpMyRideContracts.ViewModels; using PimpMyRideContracts.ViewModels;
namespace PimpMyRideWebApi.Adapters; namespace PimpMyRideWebApi.Adapters;
public class ReportAdapter : IReportAdapter internal class ReportAdapter : IReportAdapter
{ {
private readonly IReportContract _reportContract; private readonly IReportContract _reportContract;
private readonly IStringLocalizer<Messages> _localizer;
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly Mapper _mapper; private readonly Mapper _mapper;
public ReportAdapter(IReportContract reportContract, ILogger<CarAdapter> logger) public ReportAdapter(IReportContract reportContract, IStringLocalizer<Messages> localizer, ILogger<CarAdapter> logger)
{ {
_reportContract = reportContract; _reportContract = reportContract;
_logger = logger; _logger = logger;
@@ -29,6 +33,7 @@ public class ReportAdapter : IReportAdapter
cfg.CreateMap<WorkerServiceByPeriodDataModel, WorkerServiceByPeriodViewModel>(); cfg.CreateMap<WorkerServiceByPeriodDataModel, WorkerServiceByPeriodViewModel>();
}); });
_mapper = new Mapper(config); _mapper = new Mapper(config);
_localizer = localizer;
} }
public async Task<ReportOperationResponse> GetDataCarsByClientAsync(CancellationToken ct) public async Task<ReportOperationResponse> GetDataCarsByClientAsync(CancellationToken ct)
@@ -40,12 +45,12 @@ public class ReportAdapter : IReportAdapter
catch (InvalidOperationException ex) catch (InvalidOperationException ex)
{ {
_logger.LogError(ex, "InvalidOperationException"); _logger.LogError(ex, "InvalidOperationException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageInvalidOperationException"], ex.InnerException!.Message));
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -58,23 +63,23 @@ public class ReportAdapter : IReportAdapter
{ {
try try
{ {
return ReportOperationResponse.OK((await _reportContract.GetDataOrderByPeriodAsync(dateStart, dateFinish, ct)) return ReportOperationResponse.OK((await _reportContract.GetDataOrderByPeriodAsync(dateStart.ToUniversalTime(), dateFinish.ToUniversalTime(), ct))
.Select(x => _mapper.Map<OrderViewModel>(x)).ToList()); .Select(x => _mapper.Map<OrderViewModel>(x)).ToList());
} }
catch (IncorrectDatesException ex) catch (IncorrectDatesException ex)
{ {
_logger.LogError(ex, "IncorrectDatesException"); _logger.LogError(ex, "IncorrectDatesException");
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}"); return ReportOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageIncorrectDatesException"], ex.Message));
} }
catch (InvalidOperationException ex) catch (InvalidOperationException ex)
{ {
_logger.LogError(ex, "InvalidOperationException"); _logger.LogError(ex, "InvalidOperationException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageInvalidOperationException"], ex.InnerException!.Message));
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -88,22 +93,22 @@ public class ReportAdapter : IReportAdapter
{ {
try try
{ {
return ReportOperationResponse.OK((await _reportContract.GetDataServiceByPeriodAsync(dateStart, dateFinish, ct)).Select(x => _mapper.Map<WorkerServiceByPeriodViewModel>(x)).ToList()); return ReportOperationResponse.OK((await _reportContract.GetDataServiceByPeriodAsync(dateStart.ToUniversalTime(), dateFinish.ToUniversalTime(), ct)).Select(x => _mapper.Map<WorkerServiceByPeriodViewModel>(x)).ToList());
} }
catch (IncorrectDatesException ex) catch (IncorrectDatesException ex)
{ {
_logger.LogError(ex, "IncorrectDatesException"); _logger.LogError(ex, "IncorrectDatesException");
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}"); return ReportOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageIncorrectDatesException"], ex.Message));
} }
catch (InvalidOperationException ex) catch (InvalidOperationException ex)
{ {
_logger.LogError(ex, "InvalidOperationException"); _logger.LogError(ex, "InvalidOperationException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageInvalidOperationException"], ex.InnerException!.Message));
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -121,12 +126,12 @@ public class ReportAdapter : IReportAdapter
catch (InvalidOperationException ex) catch (InvalidOperationException ex)
{ {
_logger.LogError(ex, "InvalidOperationException"); _logger.LogError(ex, "InvalidOperationException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageInvalidOperationException"], ex.InnerException!.Message));
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -139,22 +144,22 @@ public class ReportAdapter : IReportAdapter
{ {
try try
{ {
return SendStream(await _reportContract.CreateDocumentOrdersByPeriodAsync(dateStart, dateFinish, ct), "orders.xslx"); return SendStream(await _reportContract.CreateDocumentOrdersByPeriodAsync(dateStart.ToUniversalTime(), dateFinish.ToUniversalTime(), ct), "orders.xslx");
} }
catch (IncorrectDatesException ex) catch (IncorrectDatesException ex)
{ {
_logger.LogError(ex, "IncorrectDatesException"); _logger.LogError(ex, "IncorrectDatesException");
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}"); return ReportOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageIncorrectDatesException"], ex.Message));
} }
catch (InvalidOperationException ex) catch (InvalidOperationException ex)
{ {
_logger.LogError(ex, "InvalidOperationException"); _logger.LogError(ex, "InvalidOperationException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageInvalidOperationException"], ex.InnerException!.Message));
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -167,22 +172,22 @@ public class ReportAdapter : IReportAdapter
{ {
try try
{ {
return SendStream(await _reportContract.CreateDocumentServiceByPeriodAsync(dateStart, dateFinish, ct), "service.pdf"); return SendStream(await _reportContract.CreateDocumentServiceByPeriodAsync(dateStart.ToUniversalTime(), dateFinish.ToUniversalTime(), ct), "service.pdf");
} }
catch (IncorrectDatesException ex) catch (IncorrectDatesException ex)
{ {
_logger.LogError(ex, "IncorrectDatesException"); _logger.LogError(ex, "IncorrectDatesException");
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}"); return ReportOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageIncorrectDatesException"], ex.Message));
} }
catch (InvalidOperationException ex) catch (InvalidOperationException ex)
{ {
_logger.LogError(ex, "InvalidOperationException"); _logger.LogError(ex, "InvalidOperationException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageInvalidOperationException"], ex.InnerException!.Message));
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return ReportOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@@ -1,5 +1,6 @@
using System.Text.Json; using System.Text.Json;
using AutoMapper; using AutoMapper;
using Microsoft.Extensions.Localization;
using Newtonsoft.Json; using Newtonsoft.Json;
using PimpMyRideContracts.AdapterContracts; using PimpMyRideContracts.AdapterContracts;
using PimpMyRideContracts.AdapterContracts.OperationResponses; using PimpMyRideContracts.AdapterContracts.OperationResponses;
@@ -9,21 +10,24 @@ using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Enums; using PimpMyRideContracts.Enums;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.Infrastructure.ServiceConfiguration; using PimpMyRideContracts.Infrastructure.ServiceConfiguration;
using PimpMyRideContracts.Resources;
using PimpMyRideContracts.ViewModels; using PimpMyRideContracts.ViewModels;
namespace PimpMyRideWebApi.Adapters; namespace PimpMyRideWebApi.Adapters;
public class ServiceAdapter : IServiceAdapter internal class ServiceAdapter : IServiceAdapter
{ {
private readonly IServiceBusinessLogicContract _serviceBusinessLogicContract; private readonly IServiceBusinessLogicContract _serviceBusinessLogicContract;
private readonly IStringLocalizer<Messages> _localizer;
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly Mapper _mapper; private readonly Mapper _mapper;
private readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNameCaseInsensitive = true }; private readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNameCaseInsensitive = true };
public ServiceAdapter(IServiceBusinessLogicContract serviceBusinessLogicContract, ILogger<ServiceAdapter> logger) public ServiceAdapter(IServiceBusinessLogicContract serviceBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<ServiceAdapter> logger)
{ {
_serviceBusinessLogicContract = serviceBusinessLogicContract; _serviceBusinessLogicContract = serviceBusinessLogicContract;
_logger = logger; _logger = logger;
@@ -34,7 +38,7 @@ public class ServiceAdapter : IServiceAdapter
src.Id!, src.Id!,
src.WorkerId, src.WorkerId,
src.WorkType, src.WorkType,
src.ConfigurationJson!, // pass JSON string directly src.ConfigurationJson!,
src.Materials.Select(m => _mapper.Map<ServiceMaterialDataModel>(m)).ToList() src.Materials.Select(m => _mapper.Map<ServiceMaterialDataModel>(m)).ToList()
)); ));
cfg.CreateMap<ServiceDataModel, ServiceViewModel>() cfg.CreateMap<ServiceDataModel, ServiceViewModel>()
@@ -44,6 +48,7 @@ public class ServiceAdapter : IServiceAdapter
cfg.CreateMap<ServiceMaterialDataModel, ServiceMaterialViewModel>(); cfg.CreateMap<ServiceMaterialDataModel, ServiceMaterialViewModel>();
}); });
_mapper = new Mapper(config); _mapper = new Mapper(config);
_localizer = localizer;
} }
public ServiceOperationResponse GetList() public ServiceOperationResponse GetList()
@@ -55,17 +60,12 @@ public class ServiceAdapter : IServiceAdapter
catch (IncorrectDatesException ex) catch (IncorrectDatesException ex)
{ {
_logger.LogError(ex, "IncorrectDatesException"); _logger.LogError(ex, "IncorrectDatesException");
return ServiceOperationResponse.BadRequest($"Incorrect dates: {ex.Message}"); return ServiceOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageIncorrectDatesException"], ex.Message));
}
catch (NullListException)
{
_logger.LogError("NullListException");
return ServiceOperationResponse.NotFound("The list is not initialized");
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return ServiceOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return ServiceOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -83,22 +83,17 @@ public class ServiceAdapter : IServiceAdapter
catch (IncorrectDatesException ex) catch (IncorrectDatesException ex)
{ {
_logger.LogError(ex, "IncorrectDatesException"); _logger.LogError(ex, "IncorrectDatesException");
return ServiceOperationResponse.BadRequest($"Incorrect dates: {ex.Message}"); return ServiceOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageIncorrectDatesException"], ex.Message));
} }
catch (ValidationException ex) catch (ValidationException ex)
{ {
_logger.LogError(ex, "ValidationException"); _logger.LogError(ex, "ValidationException");
return ServiceOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}"); return ServiceOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (NullListException)
{
_logger.LogError("NullListException");
return ServiceOperationResponse.NotFound("The list is not initialized");
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return ServiceOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return ServiceOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -116,22 +111,22 @@ public class ServiceAdapter : IServiceAdapter
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
_logger.LogError(ex, "ArgumentNullException"); _logger.LogError(ex, "ArgumentNullException");
return ServiceOperationResponse.BadRequest("Data is empty"); return ServiceOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
} }
catch (ValidationException ex) catch (ValidationException ex)
{ {
_logger.LogError(ex, "ValidationException"); _logger.LogError(ex, "ValidationException");
return ServiceOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}"); return ServiceOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
} }
catch (ElementNotFoundException ex) catch (ElementNotFoundException ex)
{ {
_logger.LogError(ex, "ElementNotFoundException"); _logger.LogError(ex, "ElementNotFoundException");
return ServiceOperationResponse.NotFound($"Not found element by data {data}"); return ServiceOperationResponse.NotFound(string.Format(_localizer["AdapterMessageElementNotFoundException"], data));
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return ServiceOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return ServiceOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -151,17 +146,17 @@ public class ServiceAdapter : IServiceAdapter
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
_logger.LogError(ex, "ArgumentNullException"); _logger.LogError(ex, "ArgumentNullException");
return ServiceOperationResponse.BadRequest("Data is empty"); return ServiceOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
} }
catch (ValidationException ex) catch (ValidationException ex)
{ {
_logger.LogError(ex, "ValidationException"); _logger.LogError(ex, "ValidationException");
return ServiceOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}"); return ServiceOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return ServiceOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}"); return ServiceOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -180,22 +175,22 @@ public class ServiceAdapter : IServiceAdapter
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
_logger.LogError(ex, "ArgumentNullException"); _logger.LogError(ex, "ArgumentNullException");
return ServiceOperationResponse.BadRequest("Id is empty"); return ServiceOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
} }
catch (ValidationException ex) catch (ValidationException ex)
{ {
_logger.LogError(ex, "ValidationException"); _logger.LogError(ex, "ValidationException");
return ServiceOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}"); return ServiceOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
} }
catch (ElementNotFoundException ex) catch (ElementNotFoundException ex)
{ {
_logger.LogError(ex, "ElementNotFoundException"); _logger.LogError(ex, "ElementNotFoundException");
return ServiceOperationResponse.BadRequest($"Not found element by id: {id}"); return ServiceOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], id));
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return ServiceOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}"); return ServiceOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@@ -7,18 +7,22 @@ using PimpMyRideContracts.DataModels;
using PimpMyRideContracts.Exceptions; using PimpMyRideContracts.Exceptions;
using PimpMyRideContracts.ViewModels; using PimpMyRideContracts.ViewModels;
using PimpMyRideContracts.Enums; using PimpMyRideContracts.Enums;
using Microsoft.Extensions.Localization;
using PimpMyRideContracts.Resources;
namespace PimpMyRideWebApi.Adapters; namespace PimpMyRideWebApi.Adapters;
public class WorkerAdapter : IWorkerAdapter internal class WorkerAdapter : IWorkerAdapter
{ {
private readonly IWorkerBusinessLogicContract _buyerBusinessLogicContract; private readonly IWorkerBusinessLogicContract _buyerBusinessLogicContract;
private readonly IStringLocalizer<Messages> _localizer;
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly Mapper _mapper; private readonly Mapper _mapper;
public WorkerAdapter(IWorkerBusinessLogicContract workerBusinessLogicContract, ILogger<WorkerAdapter> logger) public WorkerAdapter(IWorkerBusinessLogicContract workerBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<WorkerAdapter> logger)
{ {
_buyerBusinessLogicContract = workerBusinessLogicContract; _buyerBusinessLogicContract = workerBusinessLogicContract;
_logger = logger; _logger = logger;
@@ -28,6 +32,7 @@ public class WorkerAdapter : IWorkerAdapter
cfg.CreateMap<WorkerDataModel, WorkerViewModel>(); cfg.CreateMap<WorkerDataModel, WorkerViewModel>();
}); });
_mapper = new Mapper(config); _mapper = new Mapper(config);
_localizer = localizer;
} }
public WorkerOperationResponse GetList(bool includeDeleted) public WorkerOperationResponse GetList(bool includeDeleted)
@@ -36,15 +41,10 @@ public class WorkerAdapter : IWorkerAdapter
{ {
return WorkerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllWorkers(!includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]); return WorkerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllWorkers(!includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
} }
catch (NullListException)
{
_logger.LogError("NullListException");
return WorkerOperationResponse.NotFound("The list is not initialized");
}
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return WorkerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return WorkerOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -62,17 +62,12 @@ public class WorkerAdapter : IWorkerAdapter
catch (ValidationException ex) catch (ValidationException ex)
{ {
_logger.LogError(ex, "ValidationException"); _logger.LogError(ex, "ValidationException");
return WorkerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}"); return WorkerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (NullListException)
{
_logger.LogError("NullListException");
return WorkerOperationResponse.NotFound("The list is not initialized");
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return WorkerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return WorkerOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -85,22 +80,17 @@ public class WorkerAdapter : IWorkerAdapter
{ {
try try
{ {
return WorkerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllWorkersByBirthDate(fromDate, toDate, !includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]); return WorkerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllWorkersByBirthDate(fromDate.ToUniversalTime(), toDate.ToUniversalTime(), !includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
} }
catch (IncorrectDatesException ex) catch (IncorrectDatesException ex)
{ {
_logger.LogError(ex, "IncorrectDatesException"); _logger.LogError(ex, "IncorrectDatesException");
return WorkerOperationResponse.BadRequest($"Incorrect dates: {ex.Message}"); return WorkerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageIncorrectDatesException"], ex.Message));
}
catch (NullListException)
{
_logger.LogError("NullListException");
return WorkerOperationResponse.NotFound("The list is not initialized");
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return WorkerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return WorkerOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -113,22 +103,17 @@ public class WorkerAdapter : IWorkerAdapter
{ {
try try
{ {
return WorkerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllWorkersByEmploymentDate(fromDate, toDate, !includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]); return WorkerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllWorkersByEmploymentDate(fromDate.ToUniversalTime(), toDate.ToUniversalTime(), !includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
} }
catch (IncorrectDatesException ex) catch (IncorrectDatesException ex)
{ {
_logger.LogError(ex, "IncorrectDatesException"); _logger.LogError(ex, "IncorrectDatesException");
return WorkerOperationResponse.BadRequest($"Incorrect dates: {ex.Message}"); return WorkerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageIncorrectDatesException"], ex.Message));
}
catch (NullListException)
{
_logger.LogError("NullListException");
return WorkerOperationResponse.NotFound("The list is not initialized");
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return WorkerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return WorkerOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -146,22 +131,22 @@ public class WorkerAdapter : IWorkerAdapter
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
_logger.LogError(ex, "ArgumentNullException"); _logger.LogError(ex, "ArgumentNullException");
return WorkerOperationResponse.BadRequest("Data is empty"); return WorkerOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
} }
catch (ValidationException ex) catch (ValidationException ex)
{ {
_logger.LogError(ex, "ValidationException"); _logger.LogError(ex, "ValidationException");
return WorkerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}"); return WorkerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
} }
catch (ElementNotFoundException ex) catch (ElementNotFoundException ex)
{ {
_logger.LogError(ex, "ElementNotFoundException"); _logger.LogError(ex, "ElementNotFoundException");
return WorkerOperationResponse.NotFound($"Not found element by data {data}"); return WorkerOperationResponse.NotFound(string.Format(_localizer["AdapterMessageElementNotFoundException"], data));
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return WorkerOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}"); return WorkerOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -180,12 +165,12 @@ public class WorkerAdapter : IWorkerAdapter
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
_logger.LogError(ex, "ArgumentNullException"); _logger.LogError(ex, "ArgumentNullException");
return WorkerOperationResponse.BadRequest("Data is empty"); return WorkerOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
} }
catch (ValidationException ex) catch (ValidationException ex)
{ {
_logger.LogError(ex, "ValidationException"); _logger.LogError(ex, "ValidationException");
return WorkerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}"); return WorkerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
} }
catch (ElementExistsException ex) catch (ElementExistsException ex)
{ {
@@ -195,7 +180,7 @@ public class WorkerAdapter : IWorkerAdapter
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return WorkerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}"); return WorkerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -214,17 +199,17 @@ public class WorkerAdapter : IWorkerAdapter
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
_logger.LogError(ex, "ArgumentNullException"); _logger.LogError(ex, "ArgumentNullException");
return WorkerOperationResponse.BadRequest("Data is empty"); return WorkerOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
} }
catch (ValidationException ex) catch (ValidationException ex)
{ {
_logger.LogError(ex, "ValidationException"); _logger.LogError(ex, "ValidationException");
return WorkerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}"); return WorkerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
} }
catch (ElementNotFoundException ex) catch (ElementNotFoundException ex)
{ {
_logger.LogError(ex, "ElementNotFoundException"); _logger.LogError(ex, "ElementNotFoundException");
return WorkerOperationResponse.BadRequest($"Not found element by Id {workerModel.Id}"); return WorkerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], workerModel.Id));
} }
catch (ElementExistsException ex) catch (ElementExistsException ex)
{ {
@@ -234,7 +219,7 @@ public class WorkerAdapter : IWorkerAdapter
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return WorkerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}"); return WorkerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -253,22 +238,22 @@ public class WorkerAdapter : IWorkerAdapter
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
_logger.LogError(ex, "ArgumentNullException"); _logger.LogError(ex, "ArgumentNullException");
return WorkerOperationResponse.BadRequest("Id is empty"); return WorkerOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
} }
catch (ValidationException ex) catch (ValidationException ex)
{ {
_logger.LogError(ex, "ValidationException"); _logger.LogError(ex, "ValidationException");
return WorkerOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}"); return WorkerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
} }
catch (ElementNotFoundException ex) catch (ElementNotFoundException ex)
{ {
_logger.LogError(ex, "ElementNotFoundException"); _logger.LogError(ex, "ElementNotFoundException");
return WorkerOperationResponse.BadRequest($"Not found element by id: {id}"); return WorkerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], id));
} }
catch (StorageException ex) catch (StorageException ex)
{ {
_logger.LogError(ex, "StorageException"); _logger.LogError(ex, "StorageException");
return WorkerOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}"); return WorkerOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@@ -1,5 +1,7 @@
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Localization;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using PimpMyRideBusinessLogic.Implementations; using PimpMyRideBusinessLogic.Implementations;
using PimpMyRideBusinessLogic.OfficePackage; using PimpMyRideBusinessLogic.OfficePackage;
@@ -13,6 +15,7 @@ using PimpMyRideWebApi;
using PimpMyRideWebApi.Adapters; using PimpMyRideWebApi.Adapters;
using PimpMyRideWebApi.Infrastructure; using PimpMyRideWebApi.Infrastructure;
using Serilog; using Serilog;
using System.Globalization;
using System.IdentityModel.Tokens.Jwt; using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims; using System.Security.Claims;
@@ -49,6 +52,22 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
}; };
}); });
builder.Services.AddLocalization();
builder.Services.Configure<RequestLocalizationOptions>(
options =>
{
var supportedCultures = new List<CultureInfo>
{
new("de-DE"),
new("en-US"),
new("ru-RU")
};
options.DefaultRequestCulture = new RequestCulture(culture: "ru-RU", uiCulture: "ru-RU");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});
builder.Services.AddSingleton<IConfigurationDatabase, ConfigurationDatabase>(); builder.Services.AddSingleton<IConfigurationDatabase, ConfigurationDatabase>();
builder.Services.AddSingleton<IConfigurationOrder, ConfigurationOrder>(); builder.Services.AddSingleton<IConfigurationOrder, ConfigurationOrder>();
@@ -121,4 +140,10 @@ app.Map("/login/{username}", (string username) =>
app.MapControllers(); app.MapControllers();
var localizeOptions = app.Services.GetService<IOptions<RequestLocalizationOptions>>();
if (localizeOptions is not null)
{
app.UseRequestLocalization(localizeOptions.Value);
}
app.Run(); app.Run();