1 Commits

Author SHA1 Message Date
b2cf602602 сданный вариант 2025-04-19 10:23:03 +04:00
119 changed files with 1154 additions and 4857 deletions

View File

@@ -6,21 +6,18 @@ using SquirrelContract.Extensions;
using System.Text.Json;
using System.Text.RegularExpressions;
using SquirrelContract.DataModels;
using Microsoft.Extensions.Localization;
using SquirrelContract.Resources;
namespace SquirrelBusinessLogic.Implementations;
internal class ClientBusinessLogicContract(IClientStorageContract clientStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : IClientBusinessLogicContract
public class ClientBusinessLogicContract(IClientStorageContract clientStorageContract, ILogger logger) : IClientBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IClientStorageContract _clientStorageContract = clientStorageContract;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<ClientDataModel> GetAllClients()
{
_logger.LogInformation("GetAllClients");
return _clientStorageContract.GetList();
return _clientStorageContract.GetList() ?? throw new NullListException();
}
public ClientDataModel GetClientByData(string data)
@@ -32,20 +29,20 @@ internal class ClientBusinessLogicContract(IClientStorageContract clientStorageC
}
if (data.IsGuid())
{
return _clientStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data, _localizer);
return _clientStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
if (Regex.IsMatch(data, @"^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7,10}$"))
{
return _clientStorageContract.GetElementByPhoneNumber(data) ?? throw new ElementNotFoundException(data, _localizer);
return _clientStorageContract.GetElementByPhoneNumber(data) ?? throw new ElementNotFoundException(data);
}
return _clientStorageContract.GetElementByFIO(data) ?? throw new ElementNotFoundException(data, _localizer);
return _clientStorageContract.GetElementByFIO(data) ?? throw new ElementNotFoundException(data);
}
public void InsertClient(ClientDataModel clientDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(clientDataModel));
ArgumentNullException.ThrowIfNull(clientDataModel);
clientDataModel.Validate(_localizer);
clientDataModel.Validate();
_clientStorageContract.AddElement(clientDataModel);
}
@@ -53,7 +50,7 @@ internal class ClientBusinessLogicContract(IClientStorageContract clientStorageC
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(clientDataModel));
ArgumentNullException.ThrowIfNull(clientDataModel);
clientDataModel.Validate(_localizer);
clientDataModel.Validate();
_clientStorageContract.UpdElement(clientDataModel);
}
@@ -66,7 +63,7 @@ internal class ClientBusinessLogicContract(IClientStorageContract clientStorageC
}
if (!id.IsGuid())
{
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
throw new ValidationException("Id is not a unique identifier");
}
_clientStorageContract.DelElement(id);
}

View File

@@ -1,25 +1,22 @@
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging;
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Resources;
using SquirrelContract.StoragesContracts;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace SquirrelBusinessLogic.Implementations;
internal class CocktailBusinessLogicContract(ICocktailStorageContract cocktailStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : ICocktailBusinessLogicContract
public class CocktailBusinessLogicContract(ICocktailStorageContract cocktailStorageContract, ILogger logger) : ICocktailBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ICocktailStorageContract _cocktailStorageContract = cocktailStorageContract;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<CocktailDataModel> GetAllCocktails()
{
_logger.LogInformation("GetAllCocktails");
return _cocktailStorageContract.GetList();
return _cocktailStorageContract.GetList() ?? throw new NullListException();
}
public List<CocktailHistoryDataModel> GetCocktailHistoryByCocktail(string cocktailId)
@@ -31,9 +28,9 @@ internal class CocktailBusinessLogicContract(ICocktailStorageContract cocktailSt
}
if (!cocktailId.IsGuid())
{
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "CocktailId"));
throw new ValidationException("The value in the field cocktailId is not a unique identifier.");
}
return _cocktailStorageContract.GetHistoryByCocktailId(cocktailId);
return _cocktailStorageContract.GetHistoryByCocktailId(cocktailId) ?? throw new NullListException();
}
public CocktailDataModel GetCocktailByData(string data)
@@ -45,16 +42,16 @@ internal class CocktailBusinessLogicContract(ICocktailStorageContract cocktailSt
}
if (data.IsGuid())
{
return _cocktailStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data, _localizer);
return _cocktailStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
return _cocktailStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data, _localizer);
return _cocktailStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data);
}
public void InsertCocktail(CocktailDataModel cocktailDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(cocktailDataModel));
ArgumentNullException.ThrowIfNull(cocktailDataModel);
cocktailDataModel.Validate(_localizer);
cocktailDataModel.Validate();
_cocktailStorageContract.AddElement(cocktailDataModel);
}
@@ -62,7 +59,7 @@ internal class CocktailBusinessLogicContract(ICocktailStorageContract cocktailSt
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(cocktailDataModel));
ArgumentNullException.ThrowIfNull(cocktailDataModel);
cocktailDataModel.Validate(_localizer);
cocktailDataModel.Validate();
_cocktailStorageContract.UpdElement(cocktailDataModel);
}
@@ -75,7 +72,7 @@ internal class CocktailBusinessLogicContract(ICocktailStorageContract cocktailSt
}
if (!id.IsGuid())
{
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
throw new ValidationException("Id is not a unique identifier");
}
_cocktailStorageContract.DelElement(id);
}

View File

@@ -1,26 +1,23 @@
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging;
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Resources;
using SquirrelContract.StoragesContracts;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace SquirrelBusinessLogic.Implementations;
internal class EmployeeBusinessLogicContract(IEmployeeStorageContract employeeStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : IEmployeeBusinessLogicContract
public class EmployeeBusinessLogicContract(IEmployeeStorageContract employeeStorageContract, ILogger logger) : IEmployeeBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IEmployeeStorageContract _employeeStorageContract = employeeStorageContract;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<EmployeeDataModel> GetAllEmployees(bool onlyActive = true)
{
_logger.LogInformation("GetAllEmployees params: {onlyActive}", onlyActive);
return _employeeStorageContract.GetList(onlyActive);
return _employeeStorageContract.GetList(onlyActive) ?? throw new NullListException();
}
public List<EmployeeDataModel> GetAllEmployeesByPost(string postId, bool onlyActive = true)
@@ -32,9 +29,9 @@ internal class EmployeeBusinessLogicContract(IEmployeeStorageContract employeeSt
}
if (!postId.IsGuid())
{
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "PostId"));
throw new ValidationException("The value in the field postId is not a unique identifier.");
}
return _employeeStorageContract.GetList(onlyActive, postId);
return _employeeStorageContract.GetList(onlyActive, postId) ?? throw new NullListException();
}
public List<EmployeeDataModel> GetAllEmployeesByBirthDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
@@ -42,9 +39,9 @@ internal class EmployeeBusinessLogicContract(IEmployeeStorageContract employeeSt
_logger.LogInformation("GetAllEmployees params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate, _localizer);
throw new IncorrectDatesException(fromDate, toDate);
}
return _employeeStorageContract.GetList(onlyActive, fromBirthDate: fromDate, toBirthDate: toDate);
return _employeeStorageContract.GetList(onlyActive, fromBirthDate: fromDate, toBirthDate: toDate) ?? throw new NullListException();
}
public List<EmployeeDataModel> GetAllEmployeesByEmploymentDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
@@ -52,9 +49,9 @@ internal class EmployeeBusinessLogicContract(IEmployeeStorageContract employeeSt
_logger.LogInformation("GetAllEmployees params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate, _localizer);
throw new IncorrectDatesException(fromDate, toDate);
}
return _employeeStorageContract.GetList(onlyActive, fromEmploymentDate: fromDate, toEmploymentDate: toDate);
return _employeeStorageContract.GetList(onlyActive, fromEmploymentDate: fromDate, toEmploymentDate: toDate) ?? throw new NullListException();
}
public EmployeeDataModel GetEmployeeByData(string data)
@@ -66,20 +63,20 @@ internal class EmployeeBusinessLogicContract(IEmployeeStorageContract employeeSt
}
if (data.IsGuid())
{
return _employeeStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data, _localizer);
return _employeeStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
if (Regex.IsMatch(data, @"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"))
{
return _employeeStorageContract.GetElementByEmail(data) ?? throw new ElementNotFoundException(data, _localizer);
return _employeeStorageContract.GetElementByEmail(data) ?? throw new ElementNotFoundException(data);
}
return _employeeStorageContract.GetElementByFIO(data) ?? throw new ElementNotFoundException(data, _localizer);
return _employeeStorageContract.GetElementByFIO(data) ?? throw new ElementNotFoundException(data);
}
public void InsertEmployee(EmployeeDataModel employeeDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(employeeDataModel));
ArgumentNullException.ThrowIfNull(employeeDataModel);
employeeDataModel.Validate(_localizer);
employeeDataModel.Validate();
_employeeStorageContract.AddElement(employeeDataModel);
}
@@ -87,7 +84,7 @@ internal class EmployeeBusinessLogicContract(IEmployeeStorageContract employeeSt
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(employeeDataModel));
ArgumentNullException.ThrowIfNull(employeeDataModel);
employeeDataModel.Validate(_localizer);
employeeDataModel.Validate();
_employeeStorageContract.UpdElement(employeeDataModel);
}
@@ -100,7 +97,7 @@ internal class EmployeeBusinessLogicContract(IEmployeeStorageContract employeeSt
}
if (!id.IsGuid())
{
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
throw new ValidationException("Id is not a unique identifier");
}
_employeeStorageContract.DelElement(id);
}

View File

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

View File

@@ -1,173 +0,0 @@
using SquirrelBusinessLogic.OfficePackage;
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.StoragesContracts;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Localization;
using SquirrelContract.Resources;
namespace SquirrelBusinessLogic.Implementations;
internal class ReportContract : IReportContract
{
private readonly ICocktailStorageContract _cocktailStorageContract;
private readonly ISalaryStorageContract _salaryStorageContract;
private readonly ISaleStorageContract _saleStorageContract;
private readonly BaseWordBuilder _baseWordBuilder;
private readonly BaseExcelBuilder _baseExcelBuilder;
private readonly BasePdfBuilder _basePdfBuilder;
private readonly ILogger _logger;
private readonly IStringLocalizer<Messages> _localizer;
internal readonly string[] _documentHeader;
internal readonly string[] _tableHeader;
public ReportContract(ICocktailStorageContract cocktailStorageContract, ISaleStorageContract saleStorageContract, ISalaryStorageContract salaryStorageContract, BaseWordBuilder baseWordBuilder, BaseExcelBuilder baseExcelBuilder, BasePdfBuilder basePdfBuilder, ILogger logger, IStringLocalizer<Messages> localizer)
{
_cocktailStorageContract = cocktailStorageContract;
_saleStorageContract = saleStorageContract;
_salaryStorageContract = salaryStorageContract;
_baseWordBuilder = baseWordBuilder;
_baseExcelBuilder = baseExcelBuilder;
_basePdfBuilder = basePdfBuilder;
_logger = logger;
_localizer = localizer;
_documentHeader = [_localizer["DocumentDocCaptionCocktail"], _localizer["DocumentDocCaptionPreviousNames"], _localizer["DocumentDocCaptionData"]];
_tableHeader = [_localizer["DocumentExcelCaptionDate"], _localizer["DocumentExcelCaptionSum"], _localizer["DocumentExcelCaptionDiscount"], _localizer["DocumentExcelCaptionCocktail"], _localizer["DocumentExcelCaptionCount"]];
}
public Task<List<CocktailAndCocktailHistoryDataModel>> GetDataCocktailsHistoryAsync(CancellationToken ct)
{
_logger.LogInformation("Get data PostHistory");
return GetCocktailsHistoriesAsync(ct);
}
public async Task<Stream> CreateDocumentCocktailsHistoryAsync(CancellationToken ct)
{
_logger.LogInformation("Create report CocktailHistory");
var data = await GetCocktailsHistoriesAsync(ct) ?? throw new InvalidOperationException(_localizer["NotFoundDataMessage"]);
return _baseWordBuilder
.AddHeader(_localizer["DocumentDocHeader"])
.AddParagraph(string.Format(_localizer["DocumentDocSubHeader"], DateTime.Now))
.AddTable(
new[] { 3000, 3000, 3000 },
new List<string[]> { _documentHeader }
.Concat(data.SelectMany(x =>
new[] { new[] { x.CocktailName, "", "" } }
.Concat(x.Histories.Zip(x.Data, (price, date) => new[] { "", price, date }))
))
.ToList()
)
.Build();
}
private async Task<List<CocktailAndCocktailHistoryDataModel>> GetCocktailsHistoriesAsync(CancellationToken ct) =>
[.. (await _cocktailStorageContract.GetHistoriesListAsync(ct)).GroupBy(x => x.CocktailName).Select(x => new CocktailAndCocktailHistoryDataModel {
CocktailName = x.Key, Histories = [.. x.Select(y => y.OldPrice.ToString())], Data = [.. x.Select(y => y.ChangeDate.ToString())] })];
public async Task<Stream> CreateDocumentSalesByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
var tableHeader1 = new string[]
{
_localizer["DocumentExcelHeaderEmployee"],
_localizer["DocumentExcelCaptionDate"],
_localizer["DocumentExcelCaptionSum"],
_localizer["DocumentExcelCaptionDiscount"],
_localizer["DocumentExcelCaptionCocktail"],
_localizer["DocumentExcelCaptionCount"]
};
_logger.LogInformation("Create report SalesByPeriod from {dateStart} to {dateFinish}", dateStart, dateFinish);
var data = await GetDataBySalesAsync(dateStart, dateFinish, ct) ?? throw new InvalidOperationException(_localizer["NotFoundDataMessage"]); ;
var tableRows = new List<string[]>
{
tableHeader1
};
foreach (var sale in data)
{
tableRows.Add(new string[]
{
sale.EmployeeFIO ?? "",
sale.SaleDate.ToShortDateString(),
sale.Sum.ToString("N2"),
sale.Discount.ToString("N2"),
"", ""
});
foreach (var cocktail in sale.Cocktails ?? Enumerable.Empty<SaleCocktailDataModel>())
{
tableRows.Add(new string[]
{
"", "", "", "", cocktail.CocktailName, cocktail.Count.ToString("N2")
});
}
}
tableRows.Add(new string[]
{
_localizer["DocumentExcelCaptionTotal"], "", data.Sum(x => x.Sum).ToString("N2"), data.Sum(x => x.Discount).ToString("N2"), "", ""
});
return _baseExcelBuilder
.AddHeader(_localizer["DocumentExcelHeader"], 0, 6)
.AddParagraph(string.Format(_localizer["DocumentExcelSubHeader"], dateStart.ToLocalTime().ToShortDateString(), dateFinish.ToLocalTime().ToShortDateString()), 2)
.AddTable([15, 15, 10, 10, 25, 10], tableRows)
.Build();
}
public async Task<List<SaleDataModel>> GetDataBySalesAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
if (dateStart.IsDateNotOlder(dateFinish))
{
throw new IncorrectDatesException(dateStart, dateFinish, _localizer);
}
return [.. (await _saleStorageContract.GetListAsync(dateStart,
dateFinish, ct)).OrderBy(x => x.SaleDate)];
}
public Task<List<SaleDataModel>> GetDataSaleByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
_logger.LogInformation("Get data SalesByPeriod from {dateStart} to {dateFinish}", dateStart, dateFinish);
return GetDataBySalesAsync(dateStart, dateFinish, ct);
}
public Task<List<EmployeeSalaryByPeriodDataModel>> GetDataSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
_logger.LogInformation("Get data SalaryByPeriod from {dateStart} to { dateFinish}", dateStart, dateFinish);
return GetDataBySalaryAsync(dateStart, dateFinish, ct);
}
private async Task<List<EmployeeSalaryByPeriodDataModel>> GetDataBySalaryAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
if (dateStart.IsDateNotOlder(dateFinish))
{
throw new IncorrectDatesException(dateStart, dateFinish, _localizer);
}
return [.. (await _salaryStorageContract.GetListAsync(dateStart, dateFinish, ct))
.GroupBy(x => x.EmployeeId)
.Select(x => new EmployeeSalaryByPeriodDataModel {
EmployeeFIO = x.First().EmployeeFIO,
TotalSalary = x.Sum(y => y.Salary),
FromPeriod = x.Min(y => y.SalaryDate),
ToPeriod = x.Max(y => y.SalaryDate)
})
.OrderBy(x => x.EmployeeFIO)];
}
public async Task<Stream> CreateDocumentSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
_logger.LogInformation("Create report SalaryByPeriod from {dateStart} to {dateFinish}", dateStart, dateFinish);
var data = await GetDataBySalaryAsync(dateStart, dateFinish, ct) ?? throw new InvalidOperationException(_localizer["NotFoundDataMessage"]);
return _basePdfBuilder
.AddHeader(_localizer["DocumentPdfHeader"])
.AddParagraph(string.Format(_localizer["DocumentPdfSubHeader"], dateStart.ToLocalTime().ToShortDateString(), dateFinish.ToLocalTime().ToShortDateString()))
.AddPieChart(_localizer["DocumentPdfDiagramCaption"], [.. data.Select(x => (x.EmployeeFIO, x.TotalSalary))])
.Build();
}
}

View File

@@ -1,5 +1,4 @@
using BarBelochkaContract.DataModels;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.DataModels;
@@ -7,13 +6,12 @@ using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
using SquirrelContract.Infastructure.PostConfigurations;
using SquirrelContract.Resources;
using SquirrelContract.StoragesContracts;
namespace SquirrelBusinessLogic.Implementations;
internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract,
ISaleStorageContract saleStorageContract, IPostStorageContract postStorageContract, IEmployeeStorageContract employeeStorageContract, IStringLocalizer<Messages> localizer, ILogger logger, IConfigurationSalary сonfiguration) : ISalaryBusinessLogicContract
public class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract,
ISaleStorageContract saleStorageContract, IPostStorageContract postStorageContract, IEmployeeStorageContract employeeStorageContract, ILogger logger, IConfigurationSalary сonfiguration) : ISalaryBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISalaryStorageContract _salaryStorageContract = salaryStorageContract;
@@ -21,7 +19,6 @@ internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageC
private readonly IPostStorageContract _postStorageContract = postStorageContract;
private readonly IEmployeeStorageContract _employeeStorageContract = employeeStorageContract;
private readonly IConfigurationSalary _salaryConfiguration = сonfiguration;
private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly Lock _lockObject = new();
public List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate)
@@ -29,16 +26,16 @@ internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageC
_logger.LogInformation("GetAllSalaries params: {fromDate}, {toDate}", fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate, _localizer);
throw new IncorrectDatesException(fromDate, toDate);
}
return _salaryStorageContract.GetList(fromDate, toDate);
return _salaryStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
}
public List<SalaryDataModel> GetAllSalariesByPeriodByEmployee(DateTime fromDate, DateTime toDate, string employeeId)
{
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate, _localizer);
throw new IncorrectDatesException(fromDate, toDate);
}
if (employeeId.IsEmpty())
{
@@ -46,10 +43,10 @@ internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageC
}
if (!employeeId.IsGuid())
{
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "EmployeeId"));
throw new ValidationException("The value in the field employeeId is not a unique identifier.");
}
_logger.LogInformation("GetAllSalaries params: {fromDate}, {toDate}, {employeeId}", fromDate, toDate, employeeId);
return _salaryStorageContract.GetList(fromDate, toDate, employeeId);
return _salaryStorageContract.GetList(fromDate, toDate, employeeId) ?? throw new NullListException();
}
public void CalculateSalaryByMounth(DateTime date)
@@ -57,11 +54,11 @@ internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageC
_logger.LogInformation("CalculateSalaryByMounth: {date}", date);
var startDate = new DateTime(date.Year, date.Month, 1);
var finishDate = new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month));
var employees = _employeeStorageContract.GetList();
var employees = _employeeStorageContract.GetList() ?? throw new NullListException();
foreach (var employee in employees)
{
var sales = _saleStorageContract.GetList(startDate, finishDate, employeeId: employee.Id);
var post = _postStorageContract.GetElementById(employee.PostId) ?? throw new ElementNotFoundException(employee.PostId, _localizer);
var sales = _saleStorageContract.GetList(startDate, finishDate, employeeId: employee.Id) ?? throw new NullListException();
var post = _postStorageContract.GetElementById(employee.PostId) ?? throw new NullListException();
var salary = post.ConfigurationModel switch
{
null => 0,
@@ -76,40 +73,43 @@ internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageC
private double CalculateSalaryForBartender(List<SaleDataModel> sales, DateTime startDate, DateTime finishDate, BartenderPostConfiguration config)
{
var tasks = new List<Task>();
var calcPercent = 0.0;
for (var date = startDate; date < finishDate; date = date.AddDays(1))
var days = (finishDate - startDate).Days;
var dates = Enumerable.Range(0, days)
.Select(offset => startDate.AddDays(offset))
.ToList();
var parallelOptions = new ParallelOptions
{
tasks.Add(Task.Factory.StartNew((object? obj) =>
MaxDegreeOfParallelism = _salaryConfiguration.MaxConcurrentThreads
};
Parallel.ForEach(dates, parallelOptions, date =>
{
var salesInDay = sales.Where(x => x.SaleDate.Date == date.Date).ToArray();
if (salesInDay.Length == 0) return;
double dailySum = salesInDay.Sum(x => x.Sum);
double averageSale = dailySum / salesInDay.Length;
lock (_lockObject)
{
var dateInTask = (DateTime)obj!;
var salesInDay = sales.Where(x => x.SaleDate >= dateInTask && x.SaleDate <= dateInTask.AddDays(1)).ToArray();
if (salesInDay.Length > 0)
{
lock (_lockObject)
{
calcPercent += (salesInDay.Sum(x => x.Sum) / salesInDay.Length) * config.SalePercent;
}
}
}, date));
}
var calcBonusTask = Task.Run(() =>
{
return sales.Where(x => x.Sum > _salaryConfiguration.ExtraSaleSum).Sum(x => x.Sum) * config.BonusForExtraSales;
calcPercent += averageSale * config.SalePercent;
}
});
double bonus = 0;
try
{
Task.WaitAll([Task.WhenAll(tasks), calcBonusTask]);
bonus = sales.Where(x => x.Sum > _salaryConfiguration.ExtraSaleSum)
.Sum(x => x.Sum) * config.BonusForExtraSales;
}
catch (AggregateException agEx)
catch (Exception ex)
{
foreach (var ex in agEx.InnerExceptions)
{
_logger.LogError(ex, "Error in the cashier payroll process");
}
return 0;
_logger.LogError(ex, "Error in bonus calculation");
}
return config.Rate + calcPercent + calcBonusTask.Result;
return config.Rate + calcPercent + bonus;
}
private double CalculateSalaryForManager(DateTime startDate, DateTime finishDate, ManagerPostConfiguration config)
{

View File

@@ -1,31 +1,27 @@
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging;
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Resources;
using SquirrelContract.StoragesContracts;
using System.Text.Json;
namespace SquirrelBusinessLogic.Implementations;
internal class SaleBusinessLogicContract(ISaleStorageContract
saleStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : ISaleBusinessLogicContract
public class SaleBusinessLogicContract(ISaleStorageContract
saleStorageContract, ILogger logger) : ISaleBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<SaleDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {fromDate}, {toDate}", fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate, _localizer);
throw new IncorrectDatesException(fromDate, toDate);
}
return _saleStorageContract.GetList(fromDate, toDate);
return _saleStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
}
public List<SaleDataModel> GetAllSalesByEmployeeByPeriod(string employeeId, DateTime fromDate, DateTime toDate)
@@ -33,7 +29,7 @@ saleStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : ISa
_logger.LogInformation("GetAllSales params: {employeeId}, {fromDate}, {toDate}", employeeId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate, _localizer);
throw new IncorrectDatesException(fromDate, toDate);
}
if (employeeId.IsEmpty())
{
@@ -41,9 +37,9 @@ saleStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : ISa
}
if (!employeeId.IsGuid())
{
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "EmployeeId"));
throw new ValidationException("The value in the field employeeId is not a unique identifier.");
}
return _saleStorageContract.GetList(fromDate, toDate, employeeId: employeeId);
return _saleStorageContract.GetList(fromDate, toDate, employeeId: employeeId) ?? throw new NullListException();
}
public List<SaleDataModel> GetAllSalesByClientByPeriod(string clientId, DateTime fromDate, DateTime toDate)
@@ -51,7 +47,7 @@ saleStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : ISa
_logger.LogInformation("GetAllSales params: {buyerId}, {fromDate}, {toDate}", clientId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate, _localizer);
throw new IncorrectDatesException(fromDate, toDate);
}
if (clientId.IsEmpty())
{
@@ -59,9 +55,9 @@ saleStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : ISa
}
if (!clientId.IsGuid())
{
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "ClientId"));
throw new ValidationException("The value in the field clientId is not a unique identifier.");
}
return _saleStorageContract.GetList(fromDate, toDate, clientId: clientId);
return _saleStorageContract.GetList(fromDate, toDate, clientId: clientId) ?? throw new NullListException();
}
public List<SaleDataModel> GetAllSalesByCocktailByPeriod(string cocktailId, DateTime fromDate, DateTime toDate)
@@ -69,7 +65,7 @@ saleStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : ISa
_logger.LogInformation("GetAllSales params: {cocktailId}, {fromDate}, {toDate}", cocktailId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate, _localizer);
throw new IncorrectDatesException(fromDate, toDate);
}
if (cocktailId.IsEmpty())
{
@@ -77,9 +73,9 @@ saleStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : ISa
}
if (!cocktailId.IsGuid())
{
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "cocktailId"));
throw new ValidationException("The value in the field cocktailId is not a unique identifier.");
}
return _saleStorageContract.GetList(fromDate, toDate, cocktailId: cocktailId);
return _saleStorageContract.GetList(fromDate, toDate, cocktailId: cocktailId) ?? throw new NullListException();
}
public SaleDataModel GetSaleByData(string data)
@@ -91,16 +87,16 @@ saleStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : ISa
}
if (!data.IsGuid())
{
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
throw new ValidationException("Id is not a unique identifier");
}
return _saleStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data, _localizer);
return _saleStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
public void InsertSale(SaleDataModel saleDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(saleDataModel));
ArgumentNullException.ThrowIfNull(saleDataModel);
saleDataModel.Validate(_localizer);
saleDataModel.Validate();
_saleStorageContract.AddElement(saleDataModel);
}
@@ -113,7 +109,7 @@ saleStorageContract, IStringLocalizer<Messages> localizer, ILogger logger) : ISa
}
if (!id.IsGuid())
{
throw new ValidationException(string.Format(_localizer["ValidationExceptionMessageNotAId"], "Id"));
throw new ValidationException("Id is not a unique identifier");
}
_saleStorageContract.DelElement(id);
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -8,14 +8,11 @@
<ItemGroup>
<InternalsVisibleTo Include="SquirrelTests" />
<InternalsVisibleTo Include="SquirrelWebApi" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="3.3.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.4" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.3" />
</ItemGroup>
<ItemGroup>

View File

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

View File

@@ -1,19 +0,0 @@
using SquirrelContract.Infrastructure;
using SquirrelContract.ViewModels;
namespace SquirrelContract.AdapterContracts.OperationResponses;
public class ReportOperationResponse : OperationResponse
{
public static ReportOperationResponse OK(List<CocktailAndCocktailHistoryViewModel> data) => OK<ReportOperationResponse, List<CocktailAndCocktailHistoryViewModel>>(data);
public static ReportOperationResponse OK(List<SaleViewModel> data) => OK<ReportOperationResponse, List<SaleViewModel>>(data);
public static ReportOperationResponse OK(List<EmployeeSalaryByPeriodViewModel> data) => OK<ReportOperationResponse, List<EmployeeSalaryByPeriodViewModel>>(data);
public static ReportOperationResponse OK(Stream data, string fileName) => OK<ReportOperationResponse, Stream>(data, fileName);
public static ReportOperationResponse BadRequest(string message) => BadRequest<ReportOperationResponse>(message);
public static ReportOperationResponse InternalServerError(string message) => InternalServerError<ReportOperationResponse>(message);
}

View File

@@ -1,10 +1,4 @@
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using SquirrelContract.Infastructure.PostConfigurations;
using SquirrelContract.Mapper;
using System.Text.Json;
namespace SquirrelContract.BindingModels;
namespace SquirrelContract.BindingModels;
public class PostBindingModel
{
@@ -16,27 +10,5 @@ public class PostBindingModel
public string? PostType { get; set; }
[PostProcessing(MappingCallMethodName = "ParseConfiguration")]
public string? ConfigurationJson { get; set; }
private string ParseConfiguration(PostConfiguration model) =>
System.Text.Json.JsonSerializer.Serialize(model, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
private PostConfiguration? ParseJson(string json)
{
if (ConfigurationJson is null)
return null;
var obj = JToken.Parse(json);
if (obj is not null)
{
return obj.Value<string>("Type") switch
{
nameof(BartenderPostConfiguration) => JsonConvert.DeserializeObject<BartenderPostConfiguration>(json)!,
nameof(ManagerPostConfiguration) => JsonConvert.DeserializeObject<ManagerPostConfiguration>(json)!,
_ => JsonConvert.DeserializeObject<PostConfiguration>(json)!,
};
}
return null;
}
}

View File

@@ -2,7 +2,7 @@
namespace SquirrelContract.BusinessLogicContracts;
internal interface IClientBusinessLogicContract
public interface IClientBusinessLogicContract
{
List<ClientDataModel> GetAllClients();

View File

@@ -2,7 +2,7 @@
namespace SquirrelContract.BusinessLogicContracts;
internal interface ICocktailBusinessLogicContract
public interface ICocktailBusinessLogicContract
{
List<CocktailDataModel> GetAllCocktails();

View File

@@ -2,7 +2,7 @@
namespace SquirrelContract.BusinessLogicContracts;
internal interface IEmployeeBusinessLogicContract
public interface IEmployeeBusinessLogicContract
{
List<EmployeeDataModel> GetAllEmployees(bool onlyActive = true);

View File

@@ -2,7 +2,7 @@
namespace SquirrelContract.BusinessLogicContracts;
internal interface IPostBusinessLogicContract
public interface IPostBusinessLogicContract
{
List<PostDataModel> GetAllPosts();

View File

@@ -1,13 +0,0 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.BusinessLogicContracts;
internal interface IReportContract
{
Task<List<CocktailAndCocktailHistoryDataModel>> GetDataCocktailsHistoryAsync(CancellationToken ct);
Task<Stream> CreateDocumentCocktailsHistoryAsync(CancellationToken ct);
Task<List<SaleDataModel>> GetDataBySalesAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<Stream> CreateDocumentSalesByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<List<EmployeeSalaryByPeriodDataModel>> GetDataSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<Stream> CreateDocumentSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
}

View File

@@ -2,7 +2,7 @@
namespace SquirrelContract.BusinessLogicContracts;
internal interface ISalaryBusinessLogicContract
public interface ISalaryBusinessLogicContract
{
List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate);

View File

@@ -2,7 +2,7 @@
namespace SquirrelContract.BusinessLogicContracts;
internal interface ISaleBusinessLogicContract
public interface ISaleBusinessLogicContract
{
List<SaleDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate);

View File

@@ -1,35 +1,32 @@
using Microsoft.Extensions.Localization;
using SquirrelContract.Exceptions;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
using SquirrelContract.Resources;
using System.Text.RegularExpressions;
namespace SquirrelContract.DataModels;
internal class ClientDataModel(string id, string fio, string phoneNumber, double discountSize) : IValidation
public class ClientDataModel(string id, string fio, string phoneNumber, double discountSize) : IValidation
{
public string Id { get; private set; } = id;
public string FIO { get; private set;} = fio;
public string PhoneNumber { get; private set;} = phoneNumber;
public double DiscountSize { get; private set; } = discountSize;
public ClientDataModel() : this(string.Empty, string.Empty, string.Empty, 0) { }
public void Validate(IStringLocalizer<Messages> localizer)
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
throw new ValidationException("The value in the field Id is not a unique identifier");
if (FIO.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "FIO"));
throw new ValidationException("Field FIO is empty");
if (PhoneNumber.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "PhoneNumber"));
throw new ValidationException("Field PhoneNumber is empty");
if (!Regex.IsMatch(PhoneNumber, @"^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7,10}$"))
throw new ValidationException(localizer["ValidationExceptionMessageIncorrectPhoneNumber"]);
throw new ValidationException("Field PhoneNumber is not a phone number");
}
}

View File

@@ -1,8 +0,0 @@
namespace SquirrelContract.DataModels;
public class CocktailAndCocktailHistoryDataModel
{
public required string CocktailName { get; set; }
public required List<string> Histories { get; set; }
public required List<string> Data { get; set; }
}

View File

@@ -1,35 +1,32 @@
using Microsoft.Extensions.Localization;
using SquirrelContract.Enums;
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
using SquirrelContract.Resources;
namespace SquirrelContract.DataModels;
internal class CocktailDataModel(string id, string cocktailName, double price, AlcoholType baseAlcohol) : IValidation
public class CocktailDataModel(string id, string cocktailName, double price, AlcoholType baseAlcohol) : IValidation
{
public string Id { get; private set; } = id;
public string CocktailName { get; private set; } = cocktailName;
public double Price { get; private set; } = price;
public AlcoholType BaseAlcohol { get; private set; } = baseAlcohol;
public CocktailDataModel() : this(string.Empty, string.Empty, 0, AlcoholType.None) { }
public void Validate(IStringLocalizer<Messages> localizer)
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
throw new ValidationException("The value in the field Id is not a unique identifier");
if (CocktailName.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "CocktailName"));
throw new ValidationException("Field CocktailName is empty");
if (Price <= 0)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Price"));
throw new ValidationException("Field Price is less than or equal to 0");
if (BaseAlcohol == AlcoholType.None)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "BaseAlcohol"));
throw new ValidationException("Field BaseAlcohol is empty");
}
}

View File

@@ -1,12 +1,10 @@
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
using Microsoft.Extensions.Localization;
using SquirrelContract.Resources;
namespace SquirrelContract.DataModels;
internal class CocktailHistoryDataModel(string cocktailId, double oldPrice) : IValidation
public class CocktailHistoryDataModel(string cocktailId, double oldPrice) : IValidation
{
private readonly CocktailDataModel? _cocktail;
@@ -23,17 +21,16 @@ internal class CocktailHistoryDataModel(string cocktailId, double oldPrice) : IV
ChangeDate = changeDate;
_cocktail = cocktail;
}
public CocktailHistoryDataModel() : this(string.Empty, 0) { }
public void Validate(IStringLocalizer<Messages> localizer)
public void Validate()
{
if (CocktailId.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "CocktailId"));
throw new ValidationException("Field CocktailId is empty");
if (!CocktailId.IsGuid())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "CocktailId"));
throw new ValidationException("The value in the field CocktailId is not a unique identifier");
if (OldPrice <= 0)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "OldPrice"));
throw new ValidationException("Field OldPrice is less than or equal to 0");
}
}

View File

@@ -1,13 +1,11 @@
using Microsoft.Extensions.Localization;
using SquirrelContract.Exceptions;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
using SquirrelContract.Resources;
using System.Text.RegularExpressions;
namespace SquirrelContract.DataModels;
internal class EmployeeDataModel(string id, string fio, string email, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted) : IValidation
public class EmployeeDataModel(string id, string fio, string email, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted) : IValidation
{
private readonly PostDataModel? _post;
@@ -19,9 +17,9 @@ internal class EmployeeDataModel(string id, string fio, string email, string pos
public string PostId { get; private set; } = postId;
public DateTime BirthDate { get; private set; } = birthDate.ToUniversalTime();
public DateTime BirthDate { get; private set; } = birthDate;
public DateTime EmploymentDate { get; private set; } = employmentDate.ToUniversalTime();
public DateTime EmploymentDate { get; private set; } = employmentDate;
public bool IsDeleted { get; private set; } = isDeleted;
@@ -33,41 +31,37 @@ internal class EmployeeDataModel(string id, string fio, string email, string pos
}
public EmployeeDataModel(string id, string fio, string email, string postId, DateTime birthDate, DateTime employmentDate) : this(id, fio, email, postId, birthDate, employmentDate, false) { }
public EmployeeDataModel() : this(string.Empty, string.Empty, string.Empty, string.Empty, DateTime.MinValue, DateTime.MinValue, false) { }
public void Validate(IStringLocalizer<Messages> localizer)
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
throw new ValidationException("The value in the field Id is not a unique identifier");
if (FIO.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "FIO"));
throw new ValidationException("Field FIO is empty");
if (Email.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Email"));
throw new ValidationException("Field Email is empty");
if (!Regex.IsMatch(Email, @"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"))
throw new ValidationException(localizer["ValidationExceptionMessageIncorrectEmail"]);
throw new ValidationException("Field Email is not a valid email address");
if (PostId.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "PostId"));
throw new ValidationException("Field PostId is empty");
if (!PostId.IsGuid())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "PostId"));
throw new ValidationException("The value in the field PostId is not a unique identifier");
if (BirthDate.Date > DateTime.Now.AddYears(-18).Date)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageMinorsBirthDate"], BirthDate.ToShortDateString()));
throw new ValidationException($"Only adults can be hired (BirthDate = {BirthDate.ToShortDateString()})");
if (EmploymentDate.Date < BirthDate.Date)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmploymentDateAndBirthDate"],
EmploymentDate.ToShortDateString(), BirthDate.ToShortDateString()));
throw new ValidationException("The date of employment cannot be less than the date of birth");
if ((EmploymentDate - BirthDate).TotalDays / 365 < 18) // EmploymentDate.Year - BirthDate.Year
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageMinorsEmploymentDate"],
EmploymentDate.ToShortDateString(), BirthDate.ToShortDateString()));
throw new ValidationException($"Only adults can be hired (EmploymentDate - {EmploymentDate.ToShortDateString()}, BirthDate - {BirthDate.ToShortDateString()})");
}
}

View File

@@ -1,12 +0,0 @@
namespace SquirrelContract.DataModels;
public class EmployeeSalaryByPeriodDataModel
{
public required string EmployeeFIO { get; set; }
public double TotalSalary { get; set; }
public DateTime FromPeriod { get; set; }
public DateTime ToPeriod { get; set; }
}

View File

@@ -5,76 +5,50 @@ using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
using SquirrelContract.Infastructure.PostConfigurations;
using Microsoft.Extensions.Localization;
using SquirrelContract.Resources;
using SquirrelContract.Mapper;
namespace SquirrelContract.DataModels;
internal class PostDataModel(string postId, string postName, PostType postType, PostConfiguration configuration) : IValidation
public class PostDataModel(string postId, string postName, PostType postType, PostConfiguration configuration) : IValidation
{
[AlternativeName("PostId")]
public string Id { get; private set; } = postId;
public string PostName { get; private set; } = postName;
public PostType PostType { get; private set; } = postType;
[AlternativeName("Configuration")]
[AlternativeName("ConfigurationJson")]
[PostProcessing(MappingCallMethodName = "ParseJson")]
public PostConfiguration ConfigurationModel { get; private set; } = configuration;
public PostDataModel() : this(string.Empty, string.Empty, PostType.None, null) { }
public PostDataModel(string postId, string postName) : this(postId, postName, PostType.None, new PostConfiguration() { Rate = 10 }) { }
public PostDataModel(string postId, string postName, PostType postType, string configurationJson) : this(postId, postName, postType, (PostConfiguration)null)
{
var obj = JToken.Parse(configurationJson);
if (obj is not null)
{
ConfigurationModel = obj.Value<string>("Type") switch
{
nameof(BartenderPostConfiguration) => JsonConvert.DeserializeObject<BartenderPostConfiguration>(configurationJson)!,
nameof(ManagerPostConfiguration) => JsonConvert.DeserializeObject<ManagerPostConfiguration>(configurationJson)!,
_ => JsonConvert.DeserializeObject<PostConfiguration>(configurationJson)!,
};
}
}
public void Validate(IStringLocalizer<Messages> localizer)
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
throw new ValidationException("The value in the field Id is not a unique identifier");
if (PostName.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "PostName"));
throw new ValidationException("Field PostName is empty");
if (PostType == PostType.None)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "PostType"));
throw new ValidationException("Field PostType is empty");
if (ConfigurationModel is null)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotInitialized"], "ConfigurationModel"));
throw new ValidationException("Field ConfigurationModel is not initialized");
if (ConfigurationModel!.Rate <= 0)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Rate"));
}
private PostConfiguration? ParseJson(object json)
{
if (json is PostConfiguration config)
{
return config;
}
if (json is string)
{
var obj = JToken.Parse((string)json);
var type = obj.Value<string>("Type");
switch (type)
{
case nameof(BartenderPostConfiguration):
ConfigurationModel = JsonConvert.DeserializeObject<BartenderPostConfiguration>((string)json);
break;
case nameof(ManagerPostConfiguration):
ConfigurationModel = JsonConvert.DeserializeObject<ManagerPostConfiguration>((string)json);
break;
default:
ConfigurationModel = JsonConvert.DeserializeObject<PostConfiguration>((string)json);
break;
}
return ConfigurationModel;
}
return null;
throw new ValidationException("Field Rate is less or equal zero");
}
}

View File

@@ -1,14 +1,11 @@
using Microsoft.Extensions.Localization;
using SquirrelContract.DataModels;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
using SquirrelContract.Mapper;
using SquirrelContract.Resources;
namespace BarBelochkaContract.DataModels;
internal class SalaryDataModel(string employeeId, DateTime salaryDate, double employeeSalary) : IValidation
public class SalaryDataModel(string employeeId, DateTime salaryDate, double employeeSalary) : IValidation
{
private readonly EmployeeDataModel? _employee;
@@ -16,7 +13,6 @@ internal class SalaryDataModel(string employeeId, DateTime salaryDate, double em
public DateTime SalaryDate { get; private set; } = salaryDate;
[AlternativeName("EmployeeSalary")]
public double Salary { get; private set; } = employeeSalary;
public string EmployeeFIO => _employee?.FIO ?? string.Empty;
@@ -26,17 +22,15 @@ internal class SalaryDataModel(string employeeId, DateTime salaryDate, double em
_employee = employee;
}
public SalaryDataModel() : this(string.Empty, DateTime.Now, 0) { }
public void Validate(IStringLocalizer<Messages> localizer)
public void Validate()
{
if (EmployeeId.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "EmployeeId"));
throw new ValidationException("Field EmployeeId is empty");
if (!EmployeeId.IsGuid())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "EmployeeId"));
throw new ValidationException("The value in the field EmployeeId is not a unique identifier");
if (Salary <= 0)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Salary"));
throw new ValidationException("Field Salary is less than or equal to 0");
}
}

View File

@@ -1,12 +1,10 @@
using Microsoft.Extensions.Localization;
using SquirrelContract.Exceptions;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
using SquirrelContract.Resources;
namespace SquirrelContract.DataModels;
internal class SaleCocktailDataModel(string saleId, string cocktailId, int count, double price) : IValidation
public class SaleCocktailDataModel(string saleId, string cocktailId, int count, double price) : IValidation
{
private readonly CocktailDataModel? _cocktail;
@@ -20,32 +18,29 @@ internal class SaleCocktailDataModel(string saleId, string cocktailId, int count
public string CocktailName => _cocktail?.CocktailName ?? string.Empty;
public SaleCocktailDataModel() : this(string.Empty, string.Empty, 0, 0.0) { }
public SaleCocktailDataModel(string saleId, string cocktailId, int count, double price, CocktailDataModel cocktail) : this(saleId, cocktailId, count, price)
{
_cocktail = cocktail;
}
public void Validate(IStringLocalizer<Messages> localizer)
public void Validate()
{
if (SaleId.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "SaleId"));
throw new ValidationException("Field SaleId is empty");
if (!SaleId.IsGuid())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "SaleId"));
throw new ValidationException("The value in the field SaleId is not a unique identifier");
if (CocktailId.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "IProductIdd"));
throw new ValidationException("Field CocktailId is empty");
if (!CocktailId.IsGuid())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "ProductId"));
throw new ValidationException("The value in the field CocktailId is not a unique identifier");
if (Count <= 0)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Count"));
throw new ValidationException("Field Count is less than or equal to 0");
if (Price <= 0)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Price"));
throw new ValidationException("Field Price is less than or equal to 0");
}
}

View File

@@ -1,14 +1,11 @@
using Microsoft.Extensions.Localization;
using SquirrelContract.Enums;
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
using SquirrelContract.Mapper;
using SquirrelContract.Resources;
namespace SquirrelContract.DataModels;
internal class SaleDataModel : IValidation
public class SaleDataModel : IValidation
{
private readonly ClientDataModel? _client;
@@ -30,7 +27,6 @@ internal class SaleDataModel : IValidation
public bool IsCancel { get; private set; }
[AlternativeName("SaleCocktails")]
public List<SaleCocktailDataModel>? Cocktails { get; private set; }
public string ClientFIO => _client?.FIO ?? string.Empty;
@@ -79,34 +75,28 @@ internal class SaleDataModel : IValidation
}
public SaleDataModel(string id, string employeeId, string? clientId, int discountType, List<SaleCocktailDataModel> cocktails) : this(id, employeeId, clientId, (DiscountType)discountType, false, cocktails) { }
public SaleDataModel() : this(string.Empty, string.Empty, string.Empty, DiscountType.None, false, new List<SaleCocktailDataModel>()) { }
public void Validate(IStringLocalizer<Messages> localizer)
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
throw new ValidationException("The value in the field Id is not a unique identifier");
if (EmployeeId.IsEmpty())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "EmployeeId"));
throw new ValidationException("Field EmployeeId is empty");
if (!EmployeeId.IsGuid())
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "EmployeeId"));
throw new ValidationException("The value in the field EmployeeId is not a unique identifier");
if (!ClientId?.IsGuid() ?? !ClientId?.IsEmpty() ?? false)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "ClientId"));
throw new ValidationException("The value in the field ClientId is not a unique identifier");
//if (Sum <= 0)
// throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Sum"));
if (Sum <= 0)
throw new ValidationException("Field Sum is less than or equal to 0");
if (Cocktails is null)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotInitialized"], "Cocktails"));
if (Cocktails.Count == 0)
throw new ValidationException(localizer["ValidationExceptionMessageNoCocktailsInSale"]);
Cocktails.ForEach(x => x.Validate(localizer));
if ((Cocktails?.Count ?? 0) == 0)
throw new ValidationException("The sale must include cocktails");
}
}

View File

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

View File

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

View File

@@ -1,8 +1,6 @@
using Microsoft.Extensions.Localization;
using SquirrelContract.Resources;
namespace SquirrelContract.Exceptions;
namespace SquirrelContract.Exceptions;
internal class IncorrectDatesException(DateTime start, DateTime end, IStringLocalizer<Messages> localizer) :
Exception(string.Format(localizer["IncorrectDatesExceptionMessage"], start.ToShortDateString(), end.ToShortDateString()))
{ }
public class IncorrectDatesException : Exception
{
public IncorrectDatesException(DateTime start, DateTime end) : base($"The end date must be later than the start date.. StartDate: {start:dd.MM.YYYY}. EndDate: {end:dd.MM.YYYY}") { }
}

View File

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

View File

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

View File

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

View File

@@ -10,40 +10,28 @@ public class OperationResponse
protected object? Result { get; set; }
protected string? FileName { get; set; }
public IActionResult GetResponse(HttpRequest request, HttpResponse response)
{
ArgumentNullException.ThrowIfNull(request);
ArgumentNullException.ThrowIfNull(response);
public IActionResult GetResponse(HttpRequest request, HttpResponse response)
{
ArgumentNullException.ThrowIfNull(request);
ArgumentNullException.ThrowIfNull(response);
response.StatusCode = (int)StatusCode;
if (Result is null)
{
return new StatusCodeResult((int)StatusCode);
}
if (Result is Stream stream)
{
return new FileStreamResult(stream, "application/octetstream")
{
FileDownloadName = FileName
};
}
return new ObjectResult(Result);
}
protected static TResult OK<TResult, TData>(TData data) where TResult :
OperationResponse, new() => new() { StatusCode = HttpStatusCode.OK, Result = data };
response.StatusCode = (int)StatusCode;
protected static TResult OK<TResult, TData>(TData data, string fileName) where TResult : OperationResponse, new()
=> new() { StatusCode = HttpStatusCode.OK, Result = data, FileName = fileName };
if (Result is null)
{
return new StatusCodeResult((int)StatusCode);
}
protected static TResult NoContent<TResult>() where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.NoContent };
return new ObjectResult(Result);
}
protected static TResult BadRequest<TResult>(string? errorMessage = null)
where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.BadRequest, Result = errorMessage };
protected static TResult OK<TResult, TData>(TData data) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.OK, Result = data };
protected static TResult NotFound<TResult>(string? errorMessage = null)
where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.NotFound, Result = errorMessage };
protected static TResult NoContent<TResult>() where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.NoContent };
protected static TResult InternalServerError<TResult>(string? errorMessage = null)
where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.InternalServerError, Result = errorMessage };
}
protected static TResult BadRequest<TResult>(string? errorMessage = null) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.BadRequest, Result = errorMessage };
protected static TResult NotFound<TResult>(string? errorMessage = null) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.NotFound, Result = errorMessage };
protected static TResult InternalServerError<TResult>(string? errorMessage = null) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.InternalServerError, Result = errorMessage };
}

View File

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

View File

@@ -1,12 +0,0 @@
namespace SquirrelContract.Mapper;
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)]
public class AlternativeNameAttribute : Attribute
{
public string AlternativeName { get; }
public AlternativeNameAttribute(string alternativeName)
{
AlternativeName = alternativeName;
}
}

View File

@@ -1,281 +0,0 @@
using System.Collections;
using System.Reflection;
namespace SquirrelContract.Mapper;
internal static class CustomMapper
{
public static To MapObject<To>(object obj, To newObject)
{
ArgumentNullException.ThrowIfNull(obj);
ArgumentNullException.ThrowIfNull(newObject);
var typeFrom = obj.GetType();
var typeTo = newObject.GetType();
var propertiesFrom = typeFrom.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(x => x.CanRead)
.ToArray();
// свойств
foreach (var property in typeTo.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(x => x.CanWrite))
{
if (property.GetCustomAttribute<IgnoreMappingAttribute>() is not null)
continue;
var propertyFrom = TryGetPropertyFrom(property, propertiesFrom);
if (propertyFrom is null)
{
FindAndMapDefaultValue(property, newObject);
continue;
}
var fromValue = propertyFrom.GetValue(obj);
var postProcessingAttribute = property.GetCustomAttribute<PostProcessingAttribute>();
if (postProcessingAttribute is not null)
{
var value = PostProcessing(fromValue, postProcessingAttribute, newObject);
if (value is not null)
{
property.SetValue(newObject, value);
}
continue;
}
if (propertyFrom.PropertyType.IsGenericType && propertyFrom.PropertyType.Name.StartsWith("List") && fromValue is not null)
{
fromValue = MapListOfObjects(property, fromValue);
}
if (propertyFrom.PropertyType.IsEnum && property.PropertyType == typeof(string) && fromValue != null)
{
fromValue = fromValue.ToString();
}
else if (!propertyFrom.PropertyType.IsEnum && property.PropertyType.IsEnum && fromValue is not null)
{
if (fromValue is string stringValue)
fromValue = Enum.Parse(property.PropertyType, stringValue);
else
fromValue = Enum.ToObject(property.PropertyType, fromValue);
}
if (fromValue is not null)
{
if (propertyFrom.PropertyType.IsClass
&& property.PropertyType.IsClass
&& propertyFrom.PropertyType != typeof(string)
&& property.PropertyType != typeof(string)
&& !property.PropertyType.IsAssignableFrom(propertyFrom.PropertyType))
{
try
{
var nestedInstance = Activator.CreateInstance(property.PropertyType);
if (nestedInstance != null)
{
var nestedMapped = MapObject(fromValue, nestedInstance);
property.SetValue(newObject, nestedMapped);
continue;
}
}
catch
{
// ignore
}
}
property.SetValue(newObject, fromValue);
}
}
// полей
var fieldsTo = typeTo.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
var fieldsFrom = typeFrom.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
foreach (var field in fieldsTo)
{
if (field.Name.Contains("k__BackingField"))
continue;
if (field.GetCustomAttribute<IgnoreMappingAttribute>() is not null)
continue;
var sourceField = fieldsFrom.FirstOrDefault(f => f.Name == field.Name);
object? fromValue = null;
if (sourceField is not null)
{
fromValue = sourceField.GetValue(obj);
}
else
{
var propertyName = field.Name.TrimStart('_');
var sourceProperty = typeFrom.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (sourceProperty is not null && sourceProperty.CanRead)
{
fromValue = sourceProperty.GetValue(obj);
}
}
if (fromValue is null)
continue;
if (field.FieldType.IsClass && field.FieldType != typeof(string))
{
try
{
var nested = Activator.CreateInstance(field.FieldType)!;
var mapped = MapObject(fromValue, nested);
RemoveReadOnly(field);
field.SetValue(newObject, mapped);
continue;
}
catch
{
// ignore
}
}
RemoveReadOnly(field);
field.SetValue(newObject, fromValue);
}
var classPostProcessing = typeTo.GetCustomAttribute<PostProcessingAttribute>();
if (classPostProcessing is not null && classPostProcessing.MappingCallMethodName is not null)
{
var methodInfo = typeTo.GetMethod(classPostProcessing.MappingCallMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
methodInfo?.Invoke(newObject, []);
}
return newObject;
}
private static void RemoveReadOnly(FieldInfo field)
{
if (!field.IsInitOnly)
return;
var attr = typeof(FieldInfo).GetField("m_fieldAttributes", BindingFlags.Instance | BindingFlags.NonPublic);
if (attr != null)
{
var current = (FieldAttributes)attr.GetValue(field)!;
attr.SetValue(field, current & ~FieldAttributes.InitOnly);
}
}
public static To MapObject<To>(object obj) => MapObject(obj, Activator.CreateInstance<To>()!);
public static To? MapObjectWithNull<To>(object? obj) => obj is null ? default : MapObject(obj, Activator.CreateInstance<To>());
private static PropertyInfo? TryGetPropertyFrom(PropertyInfo propertyTo, PropertyInfo[] propertiesFrom)
{
var customAttribute = propertyTo.GetCustomAttributes<AlternativeNameAttribute>()?
.ToArray()
.FirstOrDefault(x => propertiesFrom.Any(y => y.Name == x.AlternativeName));
if (customAttribute is not null)
{
return propertiesFrom.FirstOrDefault(x => x.Name == customAttribute.AlternativeName);
}
return propertiesFrom.FirstOrDefault(x => x.Name == propertyTo.Name);
}
private static object? PostProcessing<T>(object? value, PostProcessingAttribute postProcessingAttribute, T newObject)
{
if (value is null || newObject is null)
{
return null;
}
if (!string.IsNullOrEmpty(postProcessingAttribute.MappingCallMethodName))
{
var methodInfo =
newObject.GetType().GetMethod(postProcessingAttribute.MappingCallMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
if (methodInfo is not null)
{
return methodInfo.Invoke(newObject, [value]);
}
}
else if (postProcessingAttribute.ActionType != PostProcessingType.None)
{
switch (postProcessingAttribute.ActionType)
{
case PostProcessingType.ToUniversalTime:
return ToUniversalTime(value);
case PostProcessingType.ToLocalTime:
return ToLocalTime(value);
}
}
return null;
}
private static object? ToLocalTime(object? obj)
{
if (obj is DateTime date)
return date.ToLocalTime();
return obj;
}
private static object? ToUniversalTime(object? obj)
{
if (obj is DateTime date)
return date.ToUniversalTime();
return obj;
}
private static void FindAndMapDefaultValue<T>(PropertyInfo property, T newObject)
{
var defaultValueAttribute = property.GetCustomAttribute<DefaultValueAttribute>();
if (defaultValueAttribute is null)
{
return;
}
if (defaultValueAttribute.DefaultValue is not null)
{
property.SetValue(newObject, defaultValueAttribute.DefaultValue);
return;
}
var value = defaultValueAttribute.Func switch
{
DefaultValueFunc.UtcNow => DateTime.UtcNow,
_ => (object?)null,
};
if (value is not null)
{
property.SetValue(newObject, value);
}
}
private static object? MapListOfObjects(PropertyInfo propertyTo, object list)
{
var listResult = Activator.CreateInstance(propertyTo.PropertyType);
var elementType = propertyTo.PropertyType.GenericTypeArguments[0];
foreach (var elem in (IEnumerable)list)
{
object? newElem;
if (elementType.IsPrimitive || elementType == typeof(string) || elementType == typeof(decimal) || elementType == typeof(DateTime))
{
newElem = elem;
}
else
{
newElem = MapObject(elem, Activator.CreateInstance(elementType)!);
}
if (newElem is not null)
{
propertyTo.PropertyType.GetMethod("Add")!.Invoke(listResult, [newElem]);
}
}
return listResult;
}
}
enum DefaultValueFunc
{
None,
UtcNow
}

View File

@@ -1,12 +0,0 @@
namespace SquirrelContract.Mapper;
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class)]
class DefaultValueAttribute : Attribute
{
public object? DefaultValue { get; set; }
public string? FuncName { get; set; }
public DefaultValueFunc Func { get; set; } = DefaultValueFunc.None;
}

View File

@@ -1,7 +0,0 @@
namespace SquirrelContract.Mapper;
[AttributeUsage(AttributeTargets.Property)]
class IgnoreMappingAttribute : Attribute
{
}

View File

@@ -1,9 +0,0 @@
namespace SquirrelContract.Mapper;
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class | AttributeTargets.Field)]
class PostProcessingAttribute : Attribute
{
public string? MappingCallMethodName { get; set; }
public PostProcessingType ActionType { get; set; } = PostProcessingType.None;
}

View File

@@ -1,10 +0,0 @@
namespace SquirrelContract.Mapper;
enum PostProcessingType
{
None = -1,
ToUniversalTime = 1,
ToLocalTime = 2
}

View File

@@ -1,432 +0,0 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace SquirrelContract.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("SquirrelContract.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 DocumentDocCaptionCocktail {
get {
return ResourceManager.GetString("DocumentDocCaptionCocktail", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Дата.
/// </summary>
internal static string DocumentDocCaptionData {
get {
return ResourceManager.GetString("DocumentDocCaptionData", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Предыдущие названия.
/// </summary>
internal static string DocumentDocCaptionPreviousNames {
get {
return ResourceManager.GetString("DocumentDocCaptionPreviousNames", 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 DocumentExcelCaptionCocktail {
get {
return ResourceManager.GetString("DocumentExcelCaptionCocktail", 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 DocumentExcelCaptionDiscount {
get {
return ResourceManager.GetString("DocumentExcelCaptionDiscount", 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>
/// Ищет локализованную строку, похожую на Сотрудник.
/// </summary>
internal static string DocumentExcelHeaderEmployee {
get {
return ResourceManager.GetString("DocumentExcelHeaderEmployee", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на c {0} по {1}.
/// </summary>
internal static string DocumentExcelSubHeader {
get {
return ResourceManager.GetString("DocumentExcelSubHeader", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Начисления.
/// </summary>
internal static string DocumentPdfDiagramCaption {
get {
return ResourceManager.GetString("DocumentPdfDiagramCaption", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Зарплатная ведомость.
/// </summary>
internal static string DocumentPdfHeader {
get {
return ResourceManager.GetString("DocumentPdfHeader", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на за период с {0} по {1}.
/// </summary>
internal static string DocumentPdfSubHeader {
get {
return ResourceManager.GetString("DocumentPdfSubHeader", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Нельзя изменить удаленный элемент (идентификатор: {0}).
/// </summary>
internal static string ElementDeletedExceptionMessage {
get {
return ResourceManager.GetString("ElementDeletedExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Уже существует элемент со значением {0} параметра {1}.
/// </summary>
internal static string ElementExistsExceptionMessage {
get {
return ResourceManager.GetString("ElementExistsExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Элемент не найден по значению = {0}.
/// </summary>
internal static string ElementNotFoundExceptionMessage {
get {
return ResourceManager.GetString("ElementNotFoundExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Дата окончания должна быть позже даты начала. Дата начала: {0}. ​​Дата окончания: {1}.
/// </summary>
internal static string IncorrectDatesExceptionMessage {
get {
return ResourceManager.GetString("IncorrectDatesExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Недостаточно данных для обработки: {0}.
/// </summary>
internal static string NotEnoughDataToProcessExceptionMessage {
get {
return ResourceManager.GetString("NotEnoughDataToProcessExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Не найдены данные.
/// </summary>
internal static string NotFoundDataMessage {
get {
return ResourceManager.GetString("NotFoundDataMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Ошибка при работе в хранилище: {0}.
/// </summary>
internal static string StorageExceptionMessage {
get {
return ResourceManager.GetString("StorageExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Дата трудоустройства не может быть раньше даты рождения ({0}, {1}).
/// </summary>
internal static string ValidationExceptionMessageEmploymentDateAndBirthDate {
get {
return ResourceManager.GetString("ValidationExceptionMessageEmploymentDateAndBirthDate", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле {0} пусто.
/// </summary>
internal static string ValidationExceptionMessageEmptyField {
get {
return ResourceManager.GetString("ValidationExceptionMessageEmptyField", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Фамилия не корректна.
/// </summary>
internal static string ValidationExceptionMessageIncorrectFIO_ {
get {
return ResourceManager.GetString("ValidationExceptionMessageIncorrectFIO ", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле Телефонный номер не является телефонным номером.
/// </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 ValidationExceptionMessageNoProductsInSale {
get {
return ResourceManager.GetString("ValidationExceptionMessageNoProductsInSale", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле {0} не является типом уникального идентификатора.
/// </summary>
internal static string ValidationExceptionMessageNotAId {
get {
return ResourceManager.GetString("ValidationExceptionMessageNotAId", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле {0} не проиницализировано.
/// </summary>
internal static string ValidationExceptionMessageNotInitialized {
get {
return ResourceManager.GetString("ValidationExceptionMessageNotInitialized", resourceCulture);
}
}
}
}

View File

@@ -1,243 +0,0 @@
<?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="DocumentDocCaptionCocktail" xml:space="preserve">
<value>Cocktail</value>
</data>
<data name="DocumentDocHeader" xml:space="preserve">
<value>The history of cocktail changes</value>
</data>
<data name="DocumentDocSubHeader" xml:space="preserve">
<value>Make In Date {0}</value>
</data>
<data name="DocumentExcelCaptionCount" xml:space="preserve">
<value>Count</value>
</data>
<data name="DocumentExcelCaptionDate" xml:space="preserve">
<value>Date</value>
</data>
<data name="DocumentExcelCaptionDiscount" xml:space="preserve">
<value>Discount</value>
</data>
<data name="DocumentExcelCaptionCocktail" xml:space="preserve">
<value>Cocktail</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>Sales for the period</value>
</data>
<data name="DocumentExcelSubHeader" xml:space="preserve">
<value>from {0} to {1}</value>
</data>
<data name="DocumentPdfHeader" xml:space="preserve">
<value>Payroll</value>
</data>
<data name="DocumentPdfSubHeader" xml:space="preserve">
<value>for the period from {0} to {1}</value>
</data>
<data name="DocumentPdfDiagramCaption" xml:space="preserve">
<value>Accruals</value>
</data>
<data name="NotFoundDataMessage" xml:space="preserve">
<value>No data found</value>
</data>
<data name="ValidationExceptionMessageNotAId" xml:space="preserve">
<value>The value in the {0} field is not a unique identifier type.</value>
</data>
<data name="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="ValidationExceptionMessageNotInitialized" xml:space="preserve">
<value>The value in field {0} is not initialized</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="ValidationExceptionMessageNoProductsInSale" xml:space="preserve">
<value>There must be at least one product on sale.</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="ValidationExceptionMessageEmploymentDateAndBirthDate" xml:space="preserve">
<value>Date of employment cannot be earlier than date of birth ({0}, {1})</value>
</data>
<data name="AdapterMessageStorageException" xml:space="preserve">
<value>Error while working with data storage: {0}</value>
</data>
<data name="AdapterMessageEmptyDate" xml:space="preserve">
<value>Data is empty</value>
</data>
<data name="AdapterMessageElementNotFoundException" xml:space="preserve">
<value>Not found element by data: {0}</value>
</data>
<data name="AdapterMessageValidationException" xml:space="preserve">
<value>Incorrect data transmitted: {0}</value>
</data>
<data name="AdapterMessageElementDeletedException" xml:space="preserve">
<value>The item according to the data: {0} has been deleted</value>
</data>
<data name="AdapterMessageInvalidOperationException" xml:space="preserve">
<value>Error processing data: {0}</value>
</data>
<data name="AdapterMessageIncorrectDatesException" xml:space="preserve">
<value>Incorrect dates: {0}</value>
</data>
<data name="ElementDeletedExceptionMessage" xml:space="preserve">
<value>Cannot modify a deleted item (id: {0})</value>
</data>
<data name="ElementExistsExceptionMessage" xml:space="preserve">
<value>There is already an element with value {0} of parameter {1}</value>
</data>
<data name="ElementNotFoundExceptionMessage" xml:space="preserve">
<value>Element not found at value = {0}</value>
</data>
<data name="IncorrectDatesExceptionMessage" xml:space="preserve">
<value>The end date must be later than the start date.. StartDate: {0}. EndDate: {1}</value>
</data>
<data name="NotEnoughDataToProcessExceptionMessage" xml:space="preserve">
<value>Not enough data to process: {0}</value>
</data>
<data name="StorageExceptionMessage" xml:space="preserve">
<value>Error while working in storage: {0}</value>
</data>
<data name="DocumentExcelHeaderEmployee" xml:space="preserve">
<value>Employee</value>
</data>
<data name="DocumentDocCaptionPreviousNames" xml:space="preserve">
<value>Previous names</value>
</data>
<data name="DocumentDocCaptionData" xml:space="preserve">
<value>Data</value>
</data>
<data name="ValidationExceptionMessageIncorrectFIO " xml:space="preserve">
<value>Fio is not correct</value>
</data>
</root>

View File

@@ -1,243 +0,0 @@
<?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="DocumentDocCaptionCocktail" 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="DocumentExcelCaptionDiscount" xml:space="preserve">
<value>Скидка</value>
</data>
<data name="DocumentExcelCaptionCocktail" 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="DocumentPdfHeader" xml:space="preserve">
<value>Зарплатная ведомость</value>
</data>
<data name="DocumentPdfSubHeader" xml:space="preserve">
<value>за период с {0} по {1}</value>
</data>
<data name="DocumentPdfDiagramCaption" xml:space="preserve">
<value>Начисления</value>
</data>
<data name="NotFoundDataMessage" xml:space="preserve">
<value>Не найдены данные</value>
</data>
<data name="ValidationExceptionMessageNotAId" xml:space="preserve">
<value>Значение в поле {0} не является типом уникального идентификатора</value>
</data>
<data name="ValidationExceptionMessageEmptyField" xml:space="preserve">
<value>Значение в поле {0} пусто</value>
</data>
<data name="ValidationExceptionMessageIncorrectPhoneNumber" xml:space="preserve">
<value>Значение в поле Телефонный номер не является телефонным номером</value>
</data>
<data name="ValidationExceptionMessageNotInitialized" xml:space="preserve">
<value>Значение в поле {0} не проиницализировано</value>
</data>
<data name="ValidationExceptionMessageLessOrEqualZero" xml:space="preserve">
<value>Значение в поле {0} меньше или равно 0</value>
</data>
<data name="ValidationExceptionMessageNoProductsInSale" xml:space="preserve">
<value>В продаже должен быть хотя бы один товар</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="ValidationExceptionMessageEmploymentDateAndBirthDate" xml:space="preserve">
<value>Дата трудоустройства не может быть раньше даты рождения ({0}, {1})</value>
</data>
<data name="AdapterMessageStorageException" xml:space="preserve">
<value>Ошибка при работе с хранилищем данных: {0}</value>
</data>
<data name="AdapterMessageEmptyDate" xml:space="preserve">
<value>Данные пусты</value>
</data>
<data name="AdapterMessageElementNotFoundException" xml:space="preserve">
<value>Не найден элемент по данным: {0}</value>
</data>
<data name="AdapterMessageValidationException" xml:space="preserve">
<value>Переданы неверные данные: {0}</value>
</data>
<data name="AdapterMessageElementDeletedException" xml:space="preserve">
<value>Элемент по данным: {0} был удален</value>
</data>
<data name="AdapterMessageInvalidOperationException" xml:space="preserve">
<value>Ошибка при обработке данных: {0}</value>
</data>
<data name="AdapterMessageIncorrectDatesException" xml:space="preserve">
<value>Неправильные даты: {0}</value>
</data>
<data name="ElementDeletedExceptionMessage" xml:space="preserve">
<value>Нельзя изменить удаленный элемент (идентификатор: {0})</value>
</data>
<data name="ElementExistsExceptionMessage" xml:space="preserve">
<value>Уже существует элемент со значением {0} параметра {1}</value>
</data>
<data name="ElementNotFoundExceptionMessage" xml:space="preserve">
<value>Элемент не найден по значению = {0}</value>
</data>
<data name="IncorrectDatesExceptionMessage" xml:space="preserve">
<value>Дата окончания должна быть позже даты начала. Дата начала: {0}. ​​Дата окончания: {1}</value>
</data>
<data name="NotEnoughDataToProcessExceptionMessage" xml:space="preserve">
<value>Недостаточно данных для обработки: {0}</value>
</data>
<data name="StorageExceptionMessage" xml:space="preserve">
<value>Ошибка при работе в хранилище: {0}</value>
</data>
<data name="DocumentExcelHeaderEmployee" xml:space="preserve">
<value>Сотрудник</value>
</data>
<data name="DocumentDocCaptionPreviousNames" xml:space="preserve">
<value>Предыдущие названия</value>
</data>
<data name="DocumentDocCaptionData" xml:space="preserve">
<value>Дата</value>
</data>
<data name="ValidationExceptionMessageIncorrectFIO " xml:space="preserve">
<value>Фамилия не корректна</value>
</data>
</root>

View File

@@ -1,243 +0,0 @@
<?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="DocumentDocCaptionCocktail" 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="DocumentExcelCaptionDiscount" xml:space="preserve">
<value>折扣优惠</value>
</data>
<data name="DocumentExcelCaptionCocktail" 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>从{0}到{1}</value>
</data>
<data name="DocumentPdfHeader" xml:space="preserve">
<value>薪金表</value>
</data>
<data name="DocumentPdfSubHeader" xml:space="preserve">
<value>从{0}到{1}的期间</value>
</data>
<data name="DocumentPdfDiagramCaption" xml:space="preserve">
<value>应计事项</value>
</data>
<data name="NotFoundDataMessage" xml:space="preserve">
<value>未找到数据</value>
</data>
<data name="ValidationExceptionMessageNotAId" xml:space="preserve">
<value>字段 {0} 的值不是唯一标识符类型</value>
</data>
<data name="ValidationExceptionMessageEmptyField" xml:space="preserve">
<value>字段 {0} 的值为空</value>
</data>
<data name="ValidationExceptionMessageIncorrectPhoneNumber" xml:space="preserve">
<value>电话号码字段中的值不是电话号码。</value>
</data>
<data name="ValidationExceptionMessageNotInitialized" xml:space="preserve">
<value>{0}字段中的值未初始化</value>
</data>
<data name="ValidationExceptionMessageLessOrEqualZero" xml:space="preserve">
<value>{0}字段中的值小于或等于0</value>
</data>
<data name="ValidationExceptionMessageNoProductsInSale" xml:space="preserve">
<value>必须至少有一种产品在售。</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="ValidationExceptionMessageEmploymentDateAndBirthDate" xml:space="preserve">
<value>就业日期不能早于出生日期({0},{1})</value>
</data>
<data name="AdapterMessageStorageException" xml:space="preserve">
<value>使用数据仓库时出错:{0}</value>
</data>
<data name="AdapterMessageEmptyDate" xml:space="preserve">
<value>数据为空</value>
</data>
<data name="AdapterMessageElementNotFoundException" xml:space="preserve">
<value>未找到元素数据: {0}</value>
</data>
<data name="AdapterMessageValidationException" xml:space="preserve">
<value>传递的数据不正确: {0}</value>
</data>
<data name="AdapterMessageElementDeletedException" xml:space="preserve">
<value>根据数据的项目:{0}已被删除</value>
</data>
<data name="AdapterMessageInvalidOperationException" xml:space="preserve">
<value>数据处理过程中的错误:{0}</value>
</data>
<data name="AdapterMessageIncorrectDatesException" xml:space="preserve">
<value>不正确的日期:{0}</value>
</data>
<data name="ElementDeletedExceptionMessage" xml:space="preserve">
<value>无法更改已删除的项目(id:{0})</value>
</data>
<data name="ElementExistsExceptionMessage" xml:space="preserve">
<value>已经有一个具有参数{1}的值{0}的元素</value>
</data>
<data name="ElementNotFoundExceptionMessage" xml:space="preserve">
<value>值={0}未找到该元素</value>
</data>
<data name="IncorrectDatesExceptionMessage" xml:space="preserve">
<value>结束日期必须晚于开始日期。 开始日期:{0}。 ​​结束日期:{1}</value>
</data>
<data name="NotEnoughDataToProcessExceptionMessage" xml:space="preserve">
<value>处理数据不足:{0}</value>
</data>
<data name="StorageExceptionMessage" xml:space="preserve">
<value>在存储中工作时出错:{0}</value>
</data>
<data name="DocumentExcelHeaderEmployee" xml:space="preserve">
<value>工人</value>
</data>
<data name="DocumentDocCaptionPreviousNames" xml:space="preserve">
<value>以前的名字</value>
</data>
<data name="DocumentDocCaptionData" xml:space="preserve">
<value>日期</value>
</data>
<data name="ValidationExceptionMessageIncorrectFIO " xml:space="preserve">
<value>名称格式不正确</value>
</data>
</root>

View File

@@ -9,31 +9,6 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.3.0" />
<PackageReference Include="Microsoft.Extensions.Localization" Version="9.0.4" />
</ItemGroup>
<ItemGroup>
<Compile Update="Resources\Messages.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Messages.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Resources\Messages.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Messages.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="SquirrelBusinessLogic" />
<InternalsVisibleTo Include="SquirrelDatabase" />
<InternalsVisibleTo Include="SquirrelWebApi" />
<InternalsVisibleTo Include="SquirrelTests" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
</Project>

View File

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

View File

@@ -2,11 +2,10 @@
namespace SquirrelContract.StoragesContracts;
internal interface ICocktailStorageContract
public interface ICocktailStorageContract
{
List<CocktailDataModel> GetList();
List<CocktailHistoryDataModel> GetHistoryByCocktailId(string cocktailId);
Task<List<CocktailHistoryDataModel>> GetHistoriesListAsync(CancellationToken ct);
CocktailDataModel? GetElementById(string id);
CocktailDataModel? GetElementByName(string name);
void AddElement(CocktailDataModel cocktailDataModel);

View File

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

View File

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

View File

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

View File

@@ -2,12 +2,10 @@
namespace SquirrelContract.StoragesContracts;
internal interface ISaleStorageContract
public interface ISaleStorageContract
{
List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? employeeId = null, string? clientId = null, string? cocktailId = null);
Task<List<SaleDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct);
SaleDataModel? GetElementById(string id);
void AddElement(SaleDataModel saleDataModel);

View File

@@ -1,8 +0,0 @@
namespace SquirrelContract.ViewModels;
public class CocktailAndCocktailHistoryViewModel
{
public required string CocktailName { get; set; }
public required List<string> Histories { get; set; }
public required List<string> Data { get; set; }
}

View File

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

View File

@@ -1,10 +1,7 @@
using SquirrelContract.Mapper;
namespace SquirrelContract.ViewModels;
namespace SquirrelContract.ViewModels;
public class EmployeeViewModel
{
[AlternativeName("EmployeeId")]
public required string Id { get; set; }
public required string FIO { get; set; }
@@ -17,9 +14,7 @@ public class EmployeeViewModel
public bool IsDeleted { get; set; }
[PostProcessing(ActionType = PostProcessingType.ToLocalTime)]
public DateTime BirthDate { get; set; }
[PostProcessing(ActionType = PostProcessingType.ToLocalTime)]
public DateTime EmploymentDate { get; set; }
}

View File

@@ -1,26 +1,12 @@
using SquirrelContract.Infastructure.PostConfigurations;
using SquirrelContract.Mapper;
using System.Text.Json;
namespace SquirrelContract.ViewModels;
namespace SquirrelContract.ViewModels;
public class PostViewModel
{
[AlternativeName("PostId")]
public required string Id { get; set; }
public required string PostName { get; set; }
public required string PostType { get; set; }
[AlternativeName("ConfigurationModel")]
[PostProcessing(MappingCallMethodName = "ParseConfiguration")]
public required string Configuration { get; set; }
private string ParseConfiguration(PostConfiguration? model)
{
if (model == null)
return string.Empty;
return JsonSerializer.Serialize(model, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
}
}

View File

@@ -1,13 +1,9 @@
using SquirrelContract.Mapper;
namespace SquirrelContract.ViewModels;
namespace SquirrelContract.ViewModels;
public class SalaryViewModel
{
public required string EmployeeId { get; set; }
public required string EmployeeFIO { get; set; }
public DateTime SalaryDate { get; set; }
[AlternativeName("EmployeeSalary")]
public double Salary { get; set; }
}

View File

@@ -1,6 +1,4 @@
using SquirrelContract.Mapper;
namespace SquirrelContract.ViewModels;
namespace SquirrelContract.ViewModels;
public class SaleViewModel
{
@@ -14,7 +12,6 @@ public class SaleViewModel
public string? ClientFIO { get; set; }
[PostProcessing(ActionType = PostProcessingType.ToLocalTime)]
public DateTime SaleDate { get; set; }
public double Sum { get; set; }

View File

@@ -1,32 +1,39 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Mapper;
using SquirrelContract.Resources;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
using System;
namespace SquirrelDatabase.Implementations;
internal class ClientStorageContract(SquirrelDbContext squirrelDbContext, IStringLocalizer<Messages> localizer) : IClientStorageContract
public class ClientStorageContract : IClientStorageContract
{
private readonly SquirrelDbContext _dbContext = squirrelDbContext;
private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly SquirrelDbContext _dbContext;
private readonly Mapper _mapper;
public ClientStorageContract(SquirrelDbContext squirrelDbContext)
{
_dbContext = squirrelDbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(SquirrelDbContext).Assembly);
});
_mapper = new Mapper(config);
}
public List<ClientDataModel> GetList()
{
try
{
return [.. _dbContext.Clients.Select(x => CustomMapper.MapObject<ClientDataModel>(x))];
return [.. _dbContext.Clients.Select(x => _mapper.Map<ClientDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -34,12 +41,12 @@ internal class ClientStorageContract(SquirrelDbContext squirrelDbContext, IStrin
{
try
{
return CustomMapper.MapObjectWithNull<ClientDataModel>(GetClientById(id));
return _mapper.Map<ClientDataModel>(GetClientById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -47,12 +54,12 @@ internal class ClientStorageContract(SquirrelDbContext squirrelDbContext, IStrin
{
try
{
return CustomMapper.MapObjectWithNull<ClientDataModel>(_dbContext.Clients.FirstOrDefault(x => x.FIO == fio));
return _mapper.Map<ClientDataModel>(_dbContext.Clients.FirstOrDefault(x => x.FIO == fio));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -60,12 +67,12 @@ internal class ClientStorageContract(SquirrelDbContext squirrelDbContext, IStrin
{
try
{
return CustomMapper.MapObjectWithNull<ClientDataModel>(_dbContext.Clients.FirstOrDefault(x => x.PhoneNumber == phoneNumber));
return _mapper.Map<ClientDataModel>(_dbContext.Clients.FirstOrDefault(x => x.PhoneNumber == phoneNumber));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -73,28 +80,23 @@ internal class ClientStorageContract(SquirrelDbContext squirrelDbContext, IStrin
{
try
{
_dbContext.Clients.Add(CustomMapper.MapObject<Client>(clientDataModel));
_dbContext.Clients.Add(_mapper.Map<Client>(clientDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", clientDataModel.Id, _localizer);
throw new ElementExistsException("Id", clientDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Clients_PhoneNumber" })
{
_dbContext.ChangeTracker.Clear();
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);
throw new ElementExistsException("PhoneNumber", clientDataModel.PhoneNumber);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -102,8 +104,8 @@ internal class ClientStorageContract(SquirrelDbContext squirrelDbContext, IStrin
{
try
{
var element = GetClientById(clientDataModel.Id) ?? throw new ElementNotFoundException(clientDataModel.Id, _localizer);
_dbContext.Clients.Update(CustomMapper.MapObject(clientDataModel, element));
var element = GetClientById(clientDataModel.Id) ?? throw new ElementNotFoundException(clientDataModel.Id);
_dbContext.Clients.Update(_mapper.Map(clientDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
@@ -114,12 +116,12 @@ internal class ClientStorageContract(SquirrelDbContext squirrelDbContext, IStrin
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Clients_PhoneNumber" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PhoneNumber", clientDataModel.PhoneNumber, _localizer);
throw new ElementExistsException("PhoneNumber", clientDataModel.PhoneNumber);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -127,7 +129,7 @@ internal class ClientStorageContract(SquirrelDbContext squirrelDbContext, IStrin
{
try
{
var element = GetClientById(id) ?? throw new ElementNotFoundException(id, _localizer);
var element = GetClientById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Clients.Remove(element);
_dbContext.SaveChanges();
}
@@ -139,7 +141,7 @@ internal class ClientStorageContract(SquirrelDbContext squirrelDbContext, IStrin
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}

View File

@@ -1,31 +1,40 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Mapper;
using SquirrelContract.Resources;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
namespace SquirrelDatabase.Implementations;
internal class CocktailStorageContract(SquirrelDbContext dbContext, IStringLocalizer<Messages> localizer) : ICocktailStorageContract
public class CocktailStorageContract : ICocktailStorageContract
{
private readonly SquirrelDbContext _dbContext = dbContext;
private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly SquirrelDbContext _dbContext;
private readonly Mapper _mapper;
public CocktailStorageContract(SquirrelDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Cocktail, CocktailDataModel>();
cfg.CreateMap<CocktailDataModel, Cocktail>();
cfg.CreateMap<CocktailHistory, CocktailHistoryDataModel>();
});
_mapper = new Mapper(config);
}
public List<CocktailDataModel> GetList()
{
try
{
return [.. _dbContext.Cocktails.Select(x => CustomMapper.MapObject<CocktailDataModel>(x))];
return [.. _dbContext.Cocktails.Select(x => _mapper.Map<CocktailDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -33,25 +42,12 @@ internal class CocktailStorageContract(SquirrelDbContext dbContext, IStringLocal
{
try
{
return [.. _dbContext.CocktailHistories.Include(x => x.Cocktail).Where(x => x.CocktailId == cocktailId).OrderByDescending(x => x.ChangeDate).Select(x => CustomMapper.MapObject<CocktailHistoryDataModel>(x))];
return [.. _dbContext.CocktailHistories.Include(x => x.Cocktail).Where(x => x.CocktailId == cocktailId).OrderByDescending(x => x.ChangeDate).Select(x => _mapper.Map<CocktailHistoryDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
}
}
public async Task<List<CocktailHistoryDataModel>> GetHistoriesListAsync(CancellationToken ct)
{
try
{
return [.. await _dbContext.CocktailHistories.Include(x => x.Cocktail).Select(x => CustomMapper.MapObject<CocktailHistoryDataModel>(x)).ToListAsync(ct)];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -59,12 +55,12 @@ internal class CocktailStorageContract(SquirrelDbContext dbContext, IStringLocal
{
try
{
return CustomMapper.MapObjectWithNull<CocktailDataModel>(GetCocktailById(id));
return _mapper.Map<CocktailDataModel>(GetCocktailById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -72,12 +68,12 @@ internal class CocktailStorageContract(SquirrelDbContext dbContext, IStringLocal
{
try
{
return CustomMapper.MapObjectWithNull<CocktailDataModel>(_dbContext.Cocktails.FirstOrDefault(x => x.CocktailName == name));
return _mapper.Map<CocktailDataModel>(_dbContext.Cocktails.FirstOrDefault(x => x.CocktailName == name));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -85,28 +81,23 @@ internal class CocktailStorageContract(SquirrelDbContext dbContext, IStringLocal
{
try
{
_dbContext.Cocktails.Add(CustomMapper.MapObject<Cocktail>(cocktailDataModel));
_dbContext.Cocktails.Add(_mapper.Map<Cocktail>(cocktailDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", cocktailDataModel.Id, _localizer);
throw new ElementExistsException("Id", cocktailDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Cocktails_CocktailName" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("CocktailName", cocktailDataModel.CocktailName, _localizer);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "PK_Cocktails" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", cocktailDataModel.Id, _localizer);
throw new ElementExistsException("CocktailName", cocktailDataModel.CocktailName);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -117,13 +108,13 @@ internal class CocktailStorageContract(SquirrelDbContext dbContext, IStringLocal
var transaction = _dbContext.Database.BeginTransaction();
try
{
var element = GetCocktailById(cocktailDataModel.Id) ?? throw new ElementNotFoundException(cocktailDataModel.Id, _localizer);
var element = GetCocktailById(cocktailDataModel.Id) ?? throw new ElementNotFoundException(cocktailDataModel.Id);
if (element.Price != cocktailDataModel.Price)
{
_dbContext.CocktailHistories.Add(new CocktailHistory() { CocktailId = element.Id, OldPrice = element.Price });
_dbContext.SaveChanges();
}
_dbContext.Cocktails.Update(CustomMapper.MapObject(cocktailDataModel, element));
_dbContext.Cocktails.Update(_mapper.Map(cocktailDataModel, element));
_dbContext.SaveChanges();
transaction.Commit();
}
@@ -136,7 +127,7 @@ internal class CocktailStorageContract(SquirrelDbContext dbContext, IStringLocal
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Cocktails_CocktailName" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("CocktailName", cocktailDataModel.CocktailName, _localizer);
throw new ElementExistsException("CocktailName", cocktailDataModel.CocktailName);
}
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
{
@@ -146,7 +137,7 @@ internal class CocktailStorageContract(SquirrelDbContext dbContext, IStringLocal
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -154,7 +145,7 @@ internal class CocktailStorageContract(SquirrelDbContext dbContext, IStringLocal
{
try
{
var element = GetCocktailById(id) ?? throw new ElementNotFoundException(id, _localizer);
var element = GetCocktailById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Cocktails.Remove(element);
_dbContext.SaveChanges();
}
@@ -166,7 +157,7 @@ internal class CocktailStorageContract(SquirrelDbContext dbContext, IStringLocal
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -174,7 +165,7 @@ internal class CocktailStorageContract(SquirrelDbContext dbContext, IStringLocal
{
try
{
var element = GetCocktailById(id) ?? throw new ElementNotFoundException(id, _localizer);
var element = GetCocktailById(id) ?? throw new ElementNotFoundException(id);
_dbContext.SaveChanges();
}
catch

View File

@@ -1,21 +1,28 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Mapper;
using SquirrelContract.Resources;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
namespace SquirrelDatabase.Implementations;
internal class EmployeeStorageContract(SquirrelDbContext dbContext, IStringLocalizer<Messages> localizer) : IEmployeeStorageContract
public class EmployeeStorageContract : IEmployeeStorageContract
{
private readonly SquirrelDbContext _dbContext = dbContext;
private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly SquirrelDbContext _dbContext;
private readonly Mapper _mapper;
public EmployeeStorageContract(SquirrelDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Post, PostDataModel>()
.ForMember(x => x.Id, x => x.MapFrom(src => src.PostId));
cfg.CreateMap<Employee, EmployeeDataModel>();
cfg.CreateMap<EmployeeDataModel, Employee>();
});
_mapper = new Mapper(config);
}
public List<EmployeeDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null)
{
@@ -38,12 +45,12 @@ internal class EmployeeStorageContract(SquirrelDbContext dbContext, IStringLocal
{
query = query.Where(x => x.EmploymentDate >= DateTime.SpecifyKind(fromEmploymentDate ?? DateTime.UtcNow, DateTimeKind.Utc) && x.EmploymentDate <= DateTime.SpecifyKind(toEmploymentDate ?? DateTime.UtcNow, DateTimeKind.Utc));
}
return [.. JoinPost(query).Select(x => CustomMapper.MapObject<EmployeeDataModel>(x))];
return [.. JoinPost(query).Select(x => _mapper.Map<EmployeeDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -51,12 +58,12 @@ internal class EmployeeStorageContract(SquirrelDbContext dbContext, IStringLocal
{
try
{
return CustomMapper.MapObjectWithNull<EmployeeDataModel>(GetEmployeeById(id));
return _mapper.Map<EmployeeDataModel>(GetEmployeeById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -64,12 +71,12 @@ internal class EmployeeStorageContract(SquirrelDbContext dbContext, IStringLocal
{
try
{
return CustomMapper.MapObjectWithNull<EmployeeDataModel>(AddPost(_dbContext.Employees.FirstOrDefault(x => x.FIO == fio && !x.IsDeleted)));
return _mapper.Map<EmployeeDataModel>(AddPost(_dbContext.Employees.FirstOrDefault(x => x.FIO == fio && !x.IsDeleted)));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -77,12 +84,12 @@ internal class EmployeeStorageContract(SquirrelDbContext dbContext, IStringLocal
{
try
{
return CustomMapper.MapObjectWithNull<EmployeeDataModel>(AddPost(_dbContext.Employees.FirstOrDefault(x => x.Email == email && !x.IsDeleted)));
return _mapper.Map<EmployeeDataModel>(AddPost(_dbContext.Employees.FirstOrDefault(x => x.Email == email && !x.IsDeleted)));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -90,23 +97,18 @@ internal class EmployeeStorageContract(SquirrelDbContext dbContext, IStringLocal
{
try
{
_dbContext.Employees.Add(CustomMapper.MapObject<Employee>(employeeDataModel));
_dbContext.Employees.Add(_mapper.Map<Employee>(employeeDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", employeeDataModel.Id, _localizer);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "PK_Employees" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", employeeDataModel.Id, _localizer);
throw new ElementExistsException("Id", employeeDataModel.Id);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -114,8 +116,8 @@ internal class EmployeeStorageContract(SquirrelDbContext dbContext, IStringLocal
{
try
{
var element = GetEmployeeById(employeeDataModel.Id) ?? throw new ElementNotFoundException(employeeDataModel.Id, _localizer);
_dbContext.Employees.Update(CustomMapper.MapObject(employeeDataModel, element));
var element = GetEmployeeById(employeeDataModel.Id) ?? throw new ElementNotFoundException(employeeDataModel.Id);
_dbContext.Employees.Update(_mapper.Map(employeeDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
@@ -126,7 +128,7 @@ internal class EmployeeStorageContract(SquirrelDbContext dbContext, IStringLocal
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -134,7 +136,7 @@ internal class EmployeeStorageContract(SquirrelDbContext dbContext, IStringLocal
{
try
{
var element = GetEmployeeById(id) ?? throw new ElementNotFoundException(id, _localizer);
var element = GetEmployeeById(id) ?? throw new ElementNotFoundException(id);
element.IsDeleted = true;
_dbContext.SaveChanges();
}
@@ -146,7 +148,7 @@ internal class EmployeeStorageContract(SquirrelDbContext dbContext, IStringLocal
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -161,7 +163,7 @@ internal class EmployeeStorageContract(SquirrelDbContext dbContext, IStringLocal
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}

View File

@@ -1,31 +1,46 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Mapper;
using SquirrelContract.Resources;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
namespace SquirrelDatabase.Implementations;
internal class PostStorageContract(SquirrelDbContext dbContext, IStringLocalizer<Messages> localizer) : IPostStorageContract
public class PostStorageContract : IPostStorageContract
{
private readonly SquirrelDbContext _dbContext = dbContext;
private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly SquirrelDbContext _dbContext;
private readonly Mapper _mapper;
public PostStorageContract(SquirrelDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Post, PostDataModel>()
.ForMember(x => x.Id, x => x.MapFrom(src => src.PostId));
cfg.CreateMap<PostDataModel, Post>()
.ForMember(x => x.Id, x => x.Ignore())
.ForMember(x => x.PostId, x => x.MapFrom(src => src.Id))
.ForMember(x => x.IsActual, x => x.MapFrom(src => true))
.ForMember(x => x.ChangeDate, x => x.MapFrom(src => DateTime.UtcNow))
.ForMember(x => x.Configuration, x => x.MapFrom(src =>
src.ConfigurationModel));
});
_mapper = new Mapper(config);
}
public List<PostDataModel> GetList()
{
try
{
return [.. _dbContext.Posts.Select(x => CustomMapper.MapObject<PostDataModel>(x))];
return [.. _dbContext.Posts.Select(x => _mapper.Map<PostDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -33,12 +48,12 @@ internal class PostStorageContract(SquirrelDbContext dbContext, IStringLocalizer
{
try
{
return [.. _dbContext.Posts.Where(x => x.PostId == postId).Select(x => CustomMapper.MapObjectWithNull<PostDataModel>(x))];
return [.. _dbContext.Posts.Where(x => x.PostId == postId).Select(x => _mapper.Map<PostDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -46,12 +61,12 @@ internal class PostStorageContract(SquirrelDbContext dbContext, IStringLocalizer
{
try
{
return CustomMapper.MapObjectWithNull<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostId == id && x.IsActual));
return _mapper.Map<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostId == id && x.IsActual));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -59,12 +74,12 @@ internal class PostStorageContract(SquirrelDbContext dbContext, IStringLocalizer
{
try
{
return CustomMapper.MapObjectWithNull<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostName == name && x.IsActual));
return _mapper.Map<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostName == name && x.IsActual));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -72,27 +87,23 @@ internal class PostStorageContract(SquirrelDbContext dbContext, IStringLocalizer
{
try
{
var post = MapToEntity(postDataModel);
post.IsActual = true;
post.ChangeDate = DateTime.UtcNow;
_dbContext.Posts.Add(post);
_dbContext.Posts.Add(_mapper.Map<Post>(postDataModel));
_dbContext.SaveChanges();
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostName", postDataModel.PostName, _localizer);
throw new ElementExistsException("PostName", postDataModel.PostName);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostId_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostId", postDataModel.Id, _localizer);
throw new ElementExistsException("PostId", postDataModel.Id);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -103,18 +114,14 @@ internal class PostStorageContract(SquirrelDbContext dbContext, IStringLocalizer
var transaction = _dbContext.Database.BeginTransaction();
try
{
var element = GetPostById(postDataModel.Id) ?? throw new ElementNotFoundException(postDataModel.Id, _localizer);
var element = GetPostById(postDataModel.Id) ?? throw new ElementNotFoundException(postDataModel.Id);
if (!element.IsActual)
{
throw new ElementDeletedException(postDataModel.Id);
}
element.IsActual = false;
_dbContext.SaveChanges();
var newElement = MapToEntity(postDataModel);
newElement.IsActual = true;
newElement.ChangeDate = DateTime.UtcNow;
var newElement = _mapper.Map<Post>(postDataModel);
_dbContext.Posts.Add(newElement);
_dbContext.SaveChanges();
transaction.Commit();
@@ -128,7 +135,7 @@ internal class PostStorageContract(SquirrelDbContext dbContext, IStringLocalizer
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostName", postDataModel.PostName, _localizer);
throw new ElementExistsException("PostName", postDataModel.PostName);
}
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
{
@@ -138,7 +145,7 @@ internal class PostStorageContract(SquirrelDbContext dbContext, IStringLocalizer
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -146,7 +153,7 @@ internal class PostStorageContract(SquirrelDbContext dbContext, IStringLocalizer
{
try
{
var element = GetPostById(id) ?? throw new ElementNotFoundException(id, _localizer);
var element = GetPostById(id) ?? throw new ElementNotFoundException(id);
if (!element.IsActual)
{
throw new ElementDeletedException(id);
@@ -165,7 +172,7 @@ internal class PostStorageContract(SquirrelDbContext dbContext, IStringLocalizer
{
try
{
var element = GetPostById(id) ?? throw new ElementNotFoundException(id, _localizer);
var element = GetPostById(id) ?? throw new ElementNotFoundException(id);
element.IsActual = true;
_dbContext.SaveChanges();
}
@@ -176,13 +183,5 @@ internal class PostStorageContract(SquirrelDbContext dbContext, IStringLocalizer
}
}
private Post MapToEntity(PostDataModel model)
{
var post = CustomMapper.MapObject<Post>(model);
post.PostId = model.Id;
post.Configuration = model.ConfigurationModel;
return post;
}
private Post? GetPostById(string id) => _dbContext.Posts.Where(x => x.PostId == id).OrderByDescending(x => x.ChangeDate).FirstOrDefault();
}

View File

@@ -1,20 +1,30 @@
using AutoMapper;
using BarBelochkaContract.DataModels;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Mapper;
using SquirrelContract.Resources;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
namespace SquirrelDatabase.Implementations;
internal class SalaryStorageContract(SquirrelDbContext dbContext, IStringLocalizer<Messages> localizer) : ISalaryStorageContract
public class SalaryStorageContract : ISalaryStorageContract
{
private readonly SquirrelDbContext _dbContext = dbContext;
private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly SquirrelDbContext _dbContext;
private readonly Mapper _mapper;
public SalaryStorageContract(SquirrelDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Employee, EmployeeDataModel>();
cfg.CreateMap<Salary, SalaryDataModel>();
cfg.CreateMap<SalaryDataModel, Salary>()
.ForMember(dest => dest.EmployeeSalary, opt => opt.MapFrom(src => src.Salary));
});
_mapper = new Mapper(config);
}
public List<SalaryDataModel> GetList(DateTime? startDate, DateTime? endDate, string? employeeId = null)
{
@@ -27,28 +37,12 @@ internal class SalaryStorageContract(SquirrelDbContext dbContext, IStringLocaliz
query = query.Where(x => x.SalaryDate <= DateTime.SpecifyKind(endDate ?? DateTime.UtcNow, DateTimeKind.Utc));
if (employeeId != null)
query = query.Where(x => x.EmployeeId == employeeId);
return [.. query.Select(x => CustomMapper.MapObject<SalaryDataModel>(x))];
return [.. query.Select(x => _mapper.Map<SalaryDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
}
}
public async Task<List<SalaryDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct)
{
try
{
return [.. await _dbContext.Salaries.Include(x =>
x.Employee).Where(x => x.SalaryDate >= DateTime.SpecifyKind(startDate, DateTimeKind.Utc) &&
x.SalaryDate <= DateTime.SpecifyKind(endDate, DateTimeKind.Utc))
.Select(x => CustomMapper.MapObject<SalaryDataModel>(x)).ToListAsync(ct)];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -56,22 +50,13 @@ internal class SalaryStorageContract(SquirrelDbContext dbContext, IStringLocaliz
{
try
{
var salary = MapToEntity(salaryDataModel);
_dbContext.Salaries.Add(salary);
_dbContext.Salaries.Add(_mapper.Map<Salary>(salaryDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
private Salary MapToEntity(SalaryDataModel dataModel)
{
var salary = CustomMapper.MapObject<Salary>(dataModel);
salary.EmployeeSalary = dataModel.Salary;
return salary;
}
}

View File

@@ -1,19 +1,39 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Mapper;
using SquirrelContract.Resources;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
using System;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace SquirrelDatabase.Implementations;
internal class SaleStorageContract(SquirrelDbContext dbContext, IStringLocalizer<Messages> localizer) : ISaleStorageContract
public class SaleStorageContract : ISaleStorageContract
{
private readonly SquirrelDbContext _dbContext = dbContext;
private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly SquirrelDbContext _dbContext;
private readonly Mapper _mapper;
public SaleStorageContract(SquirrelDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Client, ClientDataModel>();
cfg.CreateMap<Cocktail, CocktailDataModel>();
cfg.CreateMap<Employee, EmployeeDataModel>();
cfg.CreateMap<SaleCocktail, SaleCocktailDataModel>();
cfg.CreateMap<SaleCocktailDataModel, SaleCocktail>()
.ForMember(x => x.Cocktail, x => x.Ignore());
cfg.CreateMap<Sale, SaleDataModel>();
cfg.CreateMap<SaleDataModel, Sale>()
.ForMember(x => x.IsCancel, x => x.MapFrom(src => false))
.ForMember(x => x.SaleCocktails, x => x.MapFrom(src => src.Cocktails))
.ForMember(x => x.Employee, x => x.Ignore())
.ForMember(x => x.Client, x => x.Ignore());
});
_mapper = new Mapper(config);
}
public List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? employeeId = null, string? clientId = null, string? cocktailId = null)
{
@@ -36,33 +56,12 @@ internal class SaleStorageContract(SquirrelDbContext dbContext, IStringLocalizer
if (cocktailId != null)
query = query.Where(x => x.SaleCocktails!.Any(y => y.CocktailId == cocktailId));
var s = query.ToList();
return [.. query.Select(x => CustomMapper.MapObject<SaleDataModel>(x))];
return [.. query.Select(x => _mapper.Map<SaleDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
}
}
public async Task<List<SaleDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct)
{
try
{
return [.. await _dbContext.Sales
.Include(x => x.Employee)
.Include(x => x.Client)
.Include(x => x.SaleCocktails)!
.ThenInclude(sc => sc.Cocktail)
.Where(x => x.SaleDate >= DateTime.SpecifyKind(startDate, DateTimeKind.Utc)
&& x.SaleDate < DateTime.SpecifyKind(endDate, DateTimeKind.Utc))
.Select(x => CustomMapper.MapObject<SaleDataModel>(x))
.ToListAsync(ct)];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -70,13 +69,12 @@ internal class SaleStorageContract(SquirrelDbContext dbContext, IStringLocalizer
{
try
{
var sale = GetSaleById(id);
return sale != null ? CustomMapper.MapObject<SaleDataModel>(sale) : null;
return _mapper.Map<SaleDataModel>(GetSaleById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -84,14 +82,13 @@ internal class SaleStorageContract(SquirrelDbContext dbContext, IStringLocalizer
{
try
{
var sale = MapToEntity(saleDataModel);
_dbContext.Sales.Add(sale);
_dbContext.Sales.Add(_mapper.Map<Sale>(saleDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
@@ -99,7 +96,7 @@ internal class SaleStorageContract(SquirrelDbContext dbContext, IStringLocalizer
{
try
{
var element = GetSaleById(id) ?? throw new ElementNotFoundException(id, _localizer);
var element = GetSaleById(id) ?? throw new ElementNotFoundException(id);
if (element.IsCancel)
{
throw new ElementDeletedException(id);
@@ -115,27 +112,9 @@ internal class SaleStorageContract(SquirrelDbContext dbContext, IStringLocalizer
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex, _localizer);
throw new StorageException(ex);
}
}
private Sale MapToEntity(SaleDataModel dataModel)
{
var sale = CustomMapper.MapObject<Sale>(dataModel);
sale.IsCancel = false;
sale.SaleCocktails = dataModel.Cocktails?
.Select(p => new SaleCocktail
{
CocktailId = p.CocktailId,
Count = p.Count,
Price = p.Price,
SaleId = sale.Id
})
.ToList();
return sale;
}
private Sale? GetSaleById(string id) => _dbContext.Sales.Include(x => x.Client).Include(x => x.Employee).Include(x => x.SaleCocktails)!.ThenInclude(x => x.Cocktail).FirstOrDefault(x => x.Id == id);
}

View File

@@ -1,6 +1,5 @@
using AutoMapper;
using SquirrelContract.DataModels;
using SquirrelContract.Mapper;
using System.ComponentModel.DataAnnotations.Schema;
namespace SquirrelDatabase.Models;
@@ -25,7 +24,6 @@ public class Employee
public DateTime? DateOfDelete { get; set; }
[NotMapped]
[IgnoreMapping]
public Post? Post { get; set; }
[ForeignKey("EmployeeId")]

View File

@@ -2,7 +2,6 @@
using SquirrelContract.DataModels;
using SquirrelContract.Enums;
using SquirrelContract.Infastructure.PostConfigurations;
using SquirrelContract.Mapper;
namespace SquirrelDatabase.Models;
@@ -16,12 +15,9 @@ public class Post
public PostType PostType { get; set; }
[AlternativeName("ConfigurationModel")]
public required PostConfiguration Configuration { get; set; }
[DefaultValue(DefaultValue = true)]
public bool IsActual { get; set; }
[DefaultValue(FuncName = "UtcNow")]
public DateTime ChangeDate { get; set; }
}

View File

@@ -1,5 +1,5 @@
using AutoMapper;
using SquirrelContract.Mapper;
using BarBelochkaContract.DataModels;
namespace SquirrelDatabase.Models;
@@ -11,7 +11,6 @@ public class Salary
public DateTime SalaryDate { get; set; }
[AlternativeName("EmployeeSalary")]
public double EmployeeSalary { get; set; }
public Employee? Employee { get; set; }

View File

@@ -24,7 +24,7 @@
<ItemGroup>
<InternalsVisibleTo Include="SquirrelTests" />
<InternalsVisibleTo Include="SquirrelWebApi" />
<InternalVisibleTo Include="SquirrelWebApi" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>

View File

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

View File

@@ -5,7 +5,6 @@ using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using Microsoft.Extensions.Logging;
using SquirrelContract.BusinessLogicContracts;
using SquirrelTests.Infrastructure;
namespace SquirrelTests.BusinessLogicContractsTests;
@@ -19,7 +18,7 @@ internal class ClientBusinessLogicContractTests
public void OneTimeSetUp()
{
_clientStorageContract = new Mock<IClientStorageContract>();
_clientBusinessLogicContract = new ClientBusinessLogicContract(_clientStorageContract.Object, StringLocalizerMockCreator.GetObject(), new Mock<ILogger>().Object);
_clientBusinessLogicContract = new ClientBusinessLogicContract(_clientStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
@@ -59,11 +58,19 @@ internal class ClientBusinessLogicContractTests
_clientStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllClients_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.GetAllClients(), Throws.TypeOf<NullListException>());
_clientStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllClients_StorageThrowError_ThrowException_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_clientStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.GetAllClients(), Throws.TypeOf<StorageException>());
_clientStorageContract.Verify(x => x.GetList(), Times.Once);
@@ -159,9 +166,9 @@ internal class ClientBusinessLogicContractTests
public void GetClientByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_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(), StringLocalizerMockCreator.GetObject()));
_clientStorageContract.Setup(x => x.GetElementByPhoneNumber(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_clientStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_clientStorageContract.Setup(x => x.GetElementByFIO(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_clientStorageContract.Setup(x => x.GetElementByPhoneNumber(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.GetClientByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _clientBusinessLogicContract.GetClientByData("fio"), Throws.TypeOf<StorageException>());
@@ -194,7 +201,7 @@ internal class ClientBusinessLogicContractTests
public void InsertClient_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.AddElement(It.IsAny<ClientDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
_clientStorageContract.Setup(x => x.AddElement(It.IsAny<ClientDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.InsertClient(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0)), Throws.TypeOf<ElementExistsException>());
_clientStorageContract.Verify(x => x.AddElement(It.IsAny<ClientDataModel>()), Times.Once);
@@ -220,7 +227,7 @@ internal class ClientBusinessLogicContractTests
public void InsertClient_StorageThrowError_ThrowException_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.AddElement(It.IsAny<ClientDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_clientStorageContract.Setup(x => x.AddElement(It.IsAny<ClientDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.InsertClient(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0)), Throws.TypeOf<StorageException>());
_clientStorageContract.Verify(x => x.AddElement(It.IsAny<ClientDataModel>()), Times.Once);
@@ -249,7 +256,7 @@ internal class ClientBusinessLogicContractTests
public void UpdateClient_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.UpdElement(It.IsAny<ClientDataModel>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetObject()));
_clientStorageContract.Setup(x => x.UpdElement(It.IsAny<ClientDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.UpdateClient(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0)), Throws.TypeOf<ElementNotFoundException>());
_clientStorageContract.Verify(x => x.UpdElement(It.IsAny<ClientDataModel>()), Times.Once);
@@ -259,7 +266,7 @@ internal class ClientBusinessLogicContractTests
public void UpdateClient_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.UpdElement(It.IsAny<ClientDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
_clientStorageContract.Setup(x => x.UpdElement(It.IsAny<ClientDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.UpdateClient(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0)), Throws.TypeOf<ElementExistsException>());
_clientStorageContract.Verify(x => x.UpdElement(It.IsAny<ClientDataModel>()), Times.Once);
@@ -285,7 +292,7 @@ internal class ClientBusinessLogicContractTests
public void UpdateClient_StorageThrowError_ThrowException_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.UpdElement(It.IsAny<ClientDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_clientStorageContract.Setup(x => x.UpdElement(It.IsAny<ClientDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.UpdateClient(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0)), Throws.TypeOf<StorageException>());
_clientStorageContract.Verify(x => x.UpdElement(It.IsAny<ClientDataModel>()), Times.Once);
@@ -309,7 +316,7 @@ internal class ClientBusinessLogicContractTests
public void DeleteClient_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetObject()));
_clientStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.DeleteClient(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_clientStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
@@ -336,7 +343,7 @@ internal class ClientBusinessLogicContractTests
public void DeleteClient_StorageThrowError_ThrowException_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_clientStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.DeleteClient(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_clientStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);

View File

@@ -6,7 +6,6 @@ using SquirrelContract.DataModels;
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using SquirrelTests.Infrastructure;
using System.Xml.Linq;
using static NUnit.Framework.Internal.OSPlatform;
@@ -22,7 +21,7 @@ internal class CocktailBusinessLogicContractTests
public void OneTimeSetUp()
{
_cocktailStorageContract = new Mock<ICocktailStorageContract>();
_cocktailBusinessLogicContract = new CocktailBusinessLogicContract(_cocktailStorageContract.Object, StringLocalizerMockCreator.GetObject(), new Mock<ILogger>().Object);
_cocktailBusinessLogicContract = new CocktailBusinessLogicContract(_cocktailStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
@@ -62,11 +61,19 @@ internal class CocktailBusinessLogicContractTests
_cocktailStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllCocktails_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.GetAllCocktails(), Throws.TypeOf<NullListException>());
_cocktailStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllCocktails_StorageThrowError_ThrowException_Test()
{
//Arrange
_cocktailStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_cocktailStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.GetAllCocktails(), Throws.TypeOf<StorageException>());
_cocktailStorageContract.Verify(x => x.GetList(), Times.Once);
@@ -122,11 +129,19 @@ internal class CocktailBusinessLogicContractTests
_cocktailStorageContract.Verify(x => x.GetHistoryByCocktailId(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetCocktailHistoryByCocktail_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.GetCocktailHistoryByCocktail(Guid.NewGuid().ToString()), Throws.TypeOf<NullListException>());
_cocktailStorageContract.Verify(x => x.GetHistoryByCocktailId(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetCocktailHistoryByCocktail_StorageThrowError_ThrowException_Test()
{
//Arrange
_cocktailStorageContract.Setup(x => x.GetHistoryByCocktailId(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_cocktailStorageContract.Setup(x => x.GetHistoryByCocktailId(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.GetCocktailHistoryByCocktail(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_cocktailStorageContract.Verify(x => x.GetHistoryByCocktailId(It.IsAny<string>()), Times.Once);
@@ -192,8 +207,8 @@ internal class CocktailBusinessLogicContractTests
public void GetCocktailByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_cocktailStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_cocktailStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_cocktailStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_cocktailStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.GetCocktailByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _cocktailBusinessLogicContract.GetCocktailByData("name"), Throws.TypeOf<StorageException>());
@@ -224,7 +239,7 @@ internal class CocktailBusinessLogicContractTests
public void InsertCocktail_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_cocktailStorageContract.Setup(x => x.AddElement(It.IsAny<CocktailDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
_cocktailStorageContract.Setup(x => x.AddElement(It.IsAny<CocktailDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.InsertCocktail(new(Guid.NewGuid().ToString(), "name", 10, AlcoholType.Wine)), Throws.TypeOf<ElementExistsException>());
_cocktailStorageContract.Verify(x => x.AddElement(It.IsAny<CocktailDataModel>()), Times.Once);
@@ -250,7 +265,7 @@ internal class CocktailBusinessLogicContractTests
public void InsertCocktail_StorageThrowError_ThrowException_Test()
{
//Arrange
_cocktailStorageContract.Setup(x => x.AddElement(It.IsAny<CocktailDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_cocktailStorageContract.Setup(x => x.AddElement(It.IsAny<CocktailDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.InsertCocktail(new(Guid.NewGuid().ToString(), "name", 10, AlcoholType.Wine)), Throws.TypeOf<StorageException>());
_cocktailStorageContract.Verify(x => x.AddElement(It.IsAny<CocktailDataModel>()), Times.Once);
@@ -279,7 +294,7 @@ internal class CocktailBusinessLogicContractTests
public void UpdateCocktail_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_cocktailStorageContract.Setup(x => x.UpdElement(It.IsAny<CocktailDataModel>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetObject()));
_cocktailStorageContract.Setup(x => x.UpdElement(It.IsAny<CocktailDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.UpdateCocktail(new(Guid.NewGuid().ToString(), "name", 10, AlcoholType.Wine)), Throws.TypeOf<ElementNotFoundException>());
_cocktailStorageContract.Verify(x => x.UpdElement(It.IsAny<CocktailDataModel>()), Times.Once);
@@ -289,7 +304,7 @@ internal class CocktailBusinessLogicContractTests
public void UpdateCocktail_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_cocktailStorageContract.Setup(x => x.UpdElement(It.IsAny<CocktailDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
_cocktailStorageContract.Setup(x => x.UpdElement(It.IsAny<CocktailDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.UpdateCocktail(new(Guid.NewGuid().ToString(), "name", 10, AlcoholType.Wine)), Throws.TypeOf<ElementExistsException>());
_cocktailStorageContract.Verify(x => x.UpdElement(It.IsAny<CocktailDataModel>()), Times.Once);
@@ -315,7 +330,7 @@ internal class CocktailBusinessLogicContractTests
public void UpdateCocktail_StorageThrowError_ThrowException_Test()
{
//Arrange
_cocktailStorageContract.Setup(x => x.UpdElement(It.IsAny<CocktailDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_cocktailStorageContract.Setup(x => x.UpdElement(It.IsAny<CocktailDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.UpdateCocktail(new(Guid.NewGuid().ToString(), "name", 10, AlcoholType.Wine)), Throws.TypeOf<StorageException>());
_cocktailStorageContract.Verify(x => x.UpdElement(It.IsAny<CocktailDataModel>()), Times.Once);
@@ -340,7 +355,7 @@ internal class CocktailBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
_cocktailStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetObject()));
_cocktailStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.DeleteCocktail(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_cocktailStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
@@ -367,7 +382,7 @@ internal class CocktailBusinessLogicContractTests
public void DeleteCocktail_StorageThrowError_ThrowException_Test()
{
//Arrange
_cocktailStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_cocktailStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _cocktailBusinessLogicContract.DeleteCocktail(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_cocktailStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);

View File

@@ -5,7 +5,6 @@ using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using SquirrelTests.Infrastructure;
namespace SquirrelTests.BusinessLogicContractsTests;
@@ -19,7 +18,7 @@ internal class EmployeeBusinessLogicContractTests
public void OneTimeSetUp()
{
_employeeStorageContract = new Mock<IEmployeeStorageContract>();
_employeeBusinessLogicContract = new EmployeeBusinessLogicContract(_employeeStorageContract.Object, StringLocalizerMockCreator.GetObject(), new Mock<ILogger>().Object);
_employeeBusinessLogicContract = new EmployeeBusinessLogicContract(_employeeStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
@@ -73,11 +72,19 @@ internal class EmployeeBusinessLogicContractTests
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), null, null, null, null, null), Times.Exactly(2));
}
[Test]
public void GetAllEmployees_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployees(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllEmployees_StorageThrowError_ThrowException_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployees(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), null, null, null, null, null), Times.Once);
@@ -146,11 +153,19 @@ internal class EmployeeBusinessLogicContractTests
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllEmployeesByPost_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByPost(Guid.NewGuid().ToString(), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllEmployeesByPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByPost(Guid.NewGuid().ToString(), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
@@ -214,11 +229,19 @@ internal class EmployeeBusinessLogicContractTests
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllEmployeesByBirthDate_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByBirthDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllEmployeesByBirthDate_StorageThrowError_ThrowException_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByBirthDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
@@ -282,11 +305,19 @@ internal class EmployeeBusinessLogicContractTests
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllEmployeesByEmploymentDate_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllEmployeesByEmploymentDate_StorageThrowError_ThrowException_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
@@ -378,8 +409,8 @@ internal class EmployeeBusinessLogicContractTests
public void GetEmployeeByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_employeeStorageContract.Setup(x => x.GetElementByFIO(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_employeeStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_employeeStorageContract.Setup(x => x.GetElementByFIO(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetEmployeeByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _employeeBusinessLogicContract.GetEmployeeByData("fio"), Throws.TypeOf<StorageException>());
@@ -410,7 +441,7 @@ internal class EmployeeBusinessLogicContractTests
public void InsertEmployee_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.AddElement(It.IsAny<EmployeeDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
_employeeStorageContract.Setup(x => x.AddElement(It.IsAny<EmployeeDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.InsertEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementExistsException>());
_employeeStorageContract.Verify(x => x.AddElement(It.IsAny<EmployeeDataModel>()), Times.Once);
@@ -436,7 +467,7 @@ internal class EmployeeBusinessLogicContractTests
public void InsertEmployee_StorageThrowError_ThrowException_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.AddElement(It.IsAny<EmployeeDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_employeeStorageContract.Setup(x => x.AddElement(It.IsAny<EmployeeDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.InsertEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>());
_employeeStorageContract.Verify(x => x.AddElement(It.IsAny<EmployeeDataModel>()), Times.Once);
@@ -465,7 +496,7 @@ internal class EmployeeBusinessLogicContractTests
public void UpdateEmployee_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.UpdElement(It.IsAny<EmployeeDataModel>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetObject()));
_employeeStorageContract.Setup(x => x.UpdElement(It.IsAny<EmployeeDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.UpdateEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementNotFoundException>());
_employeeStorageContract.Verify(x => x.UpdElement(It.IsAny<EmployeeDataModel>()), Times.Once);
@@ -491,7 +522,7 @@ internal class EmployeeBusinessLogicContractTests
public void UpdateEmployee_StorageThrowError_ThrowException_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.UpdElement(It.IsAny<EmployeeDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_employeeStorageContract.Setup(x => x.UpdElement(It.IsAny<EmployeeDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.UpdateEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>());
_employeeStorageContract.Verify(x => x.UpdElement(It.IsAny<EmployeeDataModel>()), Times.Once);
@@ -516,7 +547,7 @@ internal class EmployeeBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
_employeeStorageContract.Setup(x => x.DelElement(It.Is((string x) => x != id))).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetObject()));
_employeeStorageContract.Setup(x => x.DelElement(It.Is((string x) => x != id))).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.DeleteEmployee(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_employeeStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
@@ -543,7 +574,7 @@ internal class EmployeeBusinessLogicContractTests
public void DeleteEmployee_StorageThrowError_ThrowException_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_employeeStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.DeleteEmployee(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_employeeStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);

View File

@@ -6,7 +6,6 @@ using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
using SquirrelContract.Infastructure.PostConfigurations;
using SquirrelContract.StoragesContracts;
using SquirrelTests.Infrastructure;
namespace SquirrelTests.BusinessLogicContractsTests;
@@ -20,7 +19,7 @@ internal class PostBusinessLogicContractTests
public void OneTimeSetUp()
{
_postStorageContract = new Mock<IPostStorageContract>();
_postBusinessLogicContract = new PostBusinessLogicContract(_postStorageContract.Object, StringLocalizerMockCreator.GetObject(), new Mock<ILogger>().Object);
_postBusinessLogicContract = new PostBusinessLogicContract(_postStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
@@ -66,11 +65,19 @@ internal class PostBusinessLogicContractTests
});
}
[Test]
public void GetAllPosts_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllPosts(), Throws.TypeOf<NullListException>());
_postStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllPosts_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_postStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllPosts(), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetList(), Times.Once);
@@ -125,11 +132,19 @@ internal class PostBusinessLogicContractTests
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllDataOfPost_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(Guid.NewGuid().ToString()), Throws.TypeOf<NullListException>());
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllDataOfPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
@@ -197,8 +212,8 @@ internal class PostBusinessLogicContractTests
public void GetPostByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_postStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _postBusinessLogicContract.GetPostByData("name"), Throws.TypeOf<StorageException>());
@@ -228,7 +243,7 @@ internal class PostBusinessLogicContractTests
public void InsertPost_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Bartender, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
@@ -254,7 +269,7 @@ internal class PostBusinessLogicContractTests
public void InsertPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Bartender, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
@@ -282,7 +297,7 @@ internal class PostBusinessLogicContractTests
public void UpdatePost_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementNotFoundException("", StringLocalizerMockCreator.GetObject()));
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Bartender, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
@@ -292,7 +307,7 @@ internal class PostBusinessLogicContractTests
public void UpdatePost_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.Bartender, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
@@ -318,7 +333,7 @@ internal class PostBusinessLogicContractTests
public void UpdatePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Bartender, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
@@ -343,7 +358,7 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetObject()));
_postStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
@@ -370,7 +385,7 @@ internal class PostBusinessLogicContractTests
public void DeletePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_postStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
@@ -395,7 +410,7 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetObject()));
_postStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);
@@ -422,7 +437,7 @@ internal class PostBusinessLogicContractTests
public void RestorePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_postStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);

View File

@@ -1,447 +0,0 @@
using SquirrelBusinessLogic.Implementations;
using SquirrelBusinessLogic.OfficePackage;
using SquirrelContract.DataModels;
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
using BarBelochkaContract.DataModels;
using static NUnit.Framework.Internal.OSPlatform;
using SquirrelTests.Infrastructure;
using SquirrelContract.Resources;
namespace SquirrelTests.BusinessLogicContractsTests;
[TestFixture]
internal class ReportContractTests
{
private ReportContract _reportContract;
private Mock<ISaleStorageContract> _saleStorageContract;
private Mock<ICocktailStorageContract> _cocktailStorageContract;
private Mock<ISalaryStorageContract> _salaryStorageContract;
private Mock<BaseWordBuilder> _baseWordBuilder;
private Mock<BaseExcelBuilder> _baseExcelBuilder;
private Mock<BasePdfBuilder> _basePdfBuilder;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_saleStorageContract = new Mock<ISaleStorageContract>();
_cocktailStorageContract = new Mock<ICocktailStorageContract>();
_salaryStorageContract = new Mock<ISalaryStorageContract>();
_baseWordBuilder = new Mock<BaseWordBuilder>();
_baseExcelBuilder = new Mock<BaseExcelBuilder>();
_basePdfBuilder = new Mock<BasePdfBuilder>();
_reportContract = new ReportContract(_cocktailStorageContract.Object, _saleStorageContract.Object, _salaryStorageContract.Object,
_baseWordBuilder.Object, _baseExcelBuilder.Object, _basePdfBuilder.Object, new Mock<ILogger>().Object, StringLocalizerMockCreator.GetObject());
}
[SetUp]
public void SetUp()
{
_saleStorageContract.Reset();
_salaryStorageContract.Reset();
_cocktailStorageContract.Reset();
}
[Test]
public async Task GetDataHistoriesByCocktail_ShouldSuccess_Test()
{
//Arrange
var cocktailId1 = Guid.NewGuid().ToString();
var cocktailId2 = Guid.NewGuid().ToString();
var cocktail1 = new CocktailDataModel(cocktailId1, "name1", 10.5, AlcoholType.Vodka);
var cocktail2 = new CocktailDataModel(cocktailId1, "name2", 10.5, AlcoholType.Vodka);
_cocktailStorageContract.Setup(x => x.GetHistoriesListAsync(It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(new List<CocktailHistoryDataModel>()
{
new(cocktailId1, 22, DateTime.UtcNow, cocktail1),
new(cocktailId2, 21, DateTime.UtcNow, cocktail2),
new(cocktailId1, 33, DateTime.UtcNow, cocktail1),
new(cocktailId1, 32, DateTime.UtcNow, cocktail1),
new(cocktailId2, 65, DateTime.UtcNow, cocktail2)
}));
//Act
var data = await _reportContract.GetDataCocktailsHistoryAsync(CancellationToken.None);
//Assert
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(2));
Assert.Multiple(() =>
{
Assert.That(data.First(x => x.CocktailName == cocktail1.CocktailName).Histories, Has.Count.EqualTo(3));
Assert.That(data.First(x => x.CocktailName == cocktail2.CocktailName).Histories, Has.Count.EqualTo(2));
});
_cocktailStorageContract.Verify(x => x.GetHistoriesListAsync(It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public async Task GetDataHistoriesByCocktail_WhenNoRecords_ShouldSuccess_Test()
{
//Arrange
_cocktailStorageContract.Setup(x =>
x.GetHistoriesListAsync(It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<CocktailHistoryDataModel>());
//Act
var data = await _reportContract.GetDataCocktailsHistoryAsync(CancellationToken.None);
//Assert
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(0));
_cocktailStorageContract.Verify(x =>
x.GetHistoriesListAsync(It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public void GetDataHistoriesByCocktail_WhenStorageThrowError_ShouldFail_Test()
{
//Arrange
_cocktailStorageContract.Setup(x =>
x.GetHistoriesListAsync(It.IsAny<CancellationToken>()))
.ThrowsAsync(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act & Assert
Assert.That(async () => await
_reportContract.GetDataCocktailsHistoryAsync(CancellationToken.None),
Throws.TypeOf<StorageException>());
_cocktailStorageContract.Verify(x =>
x.GetHistoriesListAsync(It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public async Task CreateDocumentHistoriesByCocktail_ShouldSuccess_Test()
{
// Arrange
var cocktailId1 = Guid.NewGuid().ToString();
var cocktailId2 = Guid.NewGuid().ToString();
var cocktail1 = new CocktailDataModel(cocktailId1, "name1", 10.5, AlcoholType.Vodka);
var cocktail2 = new CocktailDataModel(cocktailId1, "name2", 10.5, AlcoholType.Vodka);
var histories = new List<CocktailHistoryDataModel>()
{
new(cocktailId1, 22, DateTime.UtcNow, cocktail1),
new(cocktailId1, 33, DateTime.UtcNow, cocktail1),
new(cocktailId1, 32, DateTime.UtcNow, cocktail1),
new(cocktailId2, 21, DateTime.UtcNow, cocktail2),
new(cocktailId2, 65, DateTime.UtcNow, cocktail2)
};
_cocktailStorageContract.Setup(x => x.GetHistoriesListAsync(It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(histories));
_baseWordBuilder.Setup(x => x.AddHeader(It.IsAny<string>())).Returns(_baseWordBuilder.Object);
_baseWordBuilder.Setup(x => x.AddParagraph(It.IsAny<string>())).Returns(_baseWordBuilder.Object);
var countRows = 0;
string[] firstRow = [];
string[] secondRow = [];
_baseWordBuilder.Setup(x => x.AddTable(It.IsAny<int[]>(),
It.IsAny<List<string[]>>()))
.Callback((int[] widths, List<string[]> data) =>
{
countRows = data.Count;
if (data.Count > 0) firstRow = data[0];
if (data.Count > 1) secondRow = data[1];
})
.Returns(_baseWordBuilder.Object);
// Act
var data = await _reportContract.CreateDocumentCocktailsHistoryAsync(CancellationToken.None);
// Assert
_cocktailStorageContract.Verify(x => x.GetHistoriesListAsync(It.IsAny<CancellationToken>()), Times.Once);
_baseWordBuilder.Verify(x => x.AddHeader(It.IsAny<string>()), Times.Once);
_baseWordBuilder.Verify(x => x.AddParagraph(It.IsAny<string>()), Times.Once);
_baseWordBuilder.Verify(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>()), Times.Once);
_baseWordBuilder.Verify(x => x.Build(), Times.Once);
Assert.Multiple(() =>
{
Assert.That(countRows, Is.EqualTo(8));
Assert.That(firstRow, Has.Length.EqualTo(3));
Assert.That(secondRow, Has.Length.EqualTo(3));
});
}
[Test]
public async Task GetDataBySalesByPeriod_ShouldSuccess_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(new
List<SaleDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.None, false, [new SaleCocktailDataModel("",
Guid.NewGuid().ToString(), 10, 10)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.None, false, [new SaleCocktailDataModel("",
Guid.NewGuid().ToString(), 10, 10)]),
}));
//Act
var data = await _reportContract.GetDataBySalesAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None);
//Assert
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(2));
_saleStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public async Task GetDataBySalesByPeriod_WhenNoRecords_ShouldSuccess_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(new List<SaleDataModel>()));
//Act
var data = await
_reportContract.GetDataBySalesAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None);
//Assert
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(0));
_saleStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public void GetDataBySalesByPeriod_WhenIncorrectDates_ShouldFail_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(async () => await
_reportContract.GetDataBySalesAsync(date, date, CancellationToken.None),
Throws.TypeOf<IncorrectDatesException>());
Assert.That(async () => await
_reportContract.GetDataBySalesAsync(date, DateTime.UtcNow.AddDays(-1),
CancellationToken.None), Throws.TypeOf<IncorrectDatesException>());
}
[Test]
public void GetDataBySalesByPeriod_WhenStorageThrowError_ShouldFail_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
.Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
//Act&Assert
Assert.That(async () => await _reportContract.GetDataBySalesAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None),
Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(),
It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public async Task CreateDocumentSalesByPeriod_ShouldeSuccess_Test()
{
var cocktail1 = new CocktailDataModel(Guid.NewGuid().ToString(), "name 1", 10.5, AlcoholType.Vodka);
var cocktail2 = new CocktailDataModel(Guid.NewGuid().ToString(), "name 2", 10.5, AlcoholType.Vodka);
_saleStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(new List<SaleDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.RegularCustomer, false, [new SaleCocktailDataModel("", cocktail1.Id, 10, 10, cocktail1), new SaleCocktailDataModel("", cocktail2.Id, 10, 10, cocktail2)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.RegularCustomer, false, [new SaleCocktailDataModel("", cocktail2.Id, 10, 10, cocktail2)])
}));
_baseExcelBuilder.Setup(x => x.AddHeader(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>())).Returns(_baseExcelBuilder.Object);
_baseExcelBuilder.Setup(x => x.AddParagraph(It.IsAny<string>(), It.IsAny<int>())).Returns(_baseExcelBuilder.Object);
var countRows = 0;
string[] firstRow = [];
string[] secondRow = [];
string[] thirdRow = [];
_baseExcelBuilder.Setup(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>()))
.Callback((int[] widths, List<string[]> data) =>
{
countRows = data.Count;
firstRow = data[0];
secondRow = data[1];
thirdRow = data[2];
})
.Returns(_baseExcelBuilder.Object);
//Act
var data = await _reportContract.CreateDocumentSalesByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None);
//Assert
Assert.Multiple(() =>
{
Assert.That(countRows, Is.EqualTo(7));
Assert.That(firstRow, Is.Not.EqualTo(default));
Assert.That(secondRow, Is.Not.EqualTo(default));
});
_saleStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
_baseExcelBuilder.Verify(x => x.AddHeader(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()), Times.Once);
_baseExcelBuilder.Verify(x => x.AddParagraph(It.IsAny<string>(), It.IsAny<int>()), Times.Once);
_baseExcelBuilder.Verify(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>()), Times.Once);
_baseExcelBuilder.Verify(x => x.Build(), Times.Once);
}
[Test]
public async Task GetDataSalaryByPeriod_ShouldSuccess_Test()
{
// Arrange
var startDate = DateTime.UtcNow.AddDays(-20);
var endDate = DateTime.UtcNow.AddDays(5);
var employee1 = new EmployeeDataModel(
Guid.NewGuid().ToString(),
"fio 1",
"abc@gmail.com",
Guid.NewGuid().ToString(),
DateTime.UtcNow.AddYears(-20),
DateTime.UtcNow.AddDays(-3));
var employee2 = new EmployeeDataModel(
Guid.NewGuid().ToString(),
"fio 2",
"abc@gmail.com",
Guid.NewGuid().ToString(),
DateTime.UtcNow.AddYears(-20),
DateTime.UtcNow.AddDays(-3));
_salaryStorageContract.Setup(x =>
x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<SalaryDataModel>()
{
new(employee1.Id, DateTime.UtcNow.AddDays(-10), 100),
new(employee1.Id, endDate, 1000),
new(employee1.Id, startDate, 1000),
new(employee2.Id, DateTime.UtcNow.AddDays(-10), 100),
new(employee2.Id, DateTime.UtcNow.AddDays(-5), 200)
});
// Act
var data = await _reportContract.GetDataSalaryByPeriodAsync(
DateTime.UtcNow.AddDays(-1),
DateTime.UtcNow,
CancellationToken.None);
// Assert
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(2));
var totalSalary = data.First();
Assert.Multiple(() =>
{
Assert.That(totalSalary, Is.Not.Null);
Assert.That(totalSalary.TotalSalary, Is.EqualTo(2100));
});
_salaryStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(),
It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public async Task GetDataSalaryByPeriod_WhenNoRecords_ShouldSuccess_Test()
{
// Arrange
_salaryStorageContract.Setup(x =>
x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<SalaryDataModel>());
// Act
var data = await _reportContract.GetDataSalaryByPeriodAsync(
DateTime.UtcNow.AddDays(-1),
DateTime.UtcNow,
CancellationToken.None);
// Assert
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(0));
_salaryStorageContract.Verify(x =>
x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()),
Times.Once);
}
[Test]
public void GetDataSalaryByPeriod_WhenIncorrectDates_ShouldFail_Test()
{
// Arrange
var date = DateTime.UtcNow;
// Act & Assert
Assert.That(async () => await _reportContract.GetDataSalaryByPeriodAsync(
date, date, CancellationToken.None),
Throws.TypeOf<IncorrectDatesException>());
Assert.That(async () => await _reportContract.GetDataSalaryByPeriodAsync(
date, DateTime.UtcNow.AddDays(-1), CancellationToken.None),
Throws.TypeOf<IncorrectDatesException>());
}
[Test]
public void GetDataBySalaryByPeriod_WhenStorageThrowError_ShouldFail_Test()
{
// Arrange
_salaryStorageContract.Setup(x =>
x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
.ThrowsAsync(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
// Act & Assert
Assert.That(async () => await _reportContract.GetDataSalaryByPeriodAsync(
DateTime.UtcNow.AddDays(-1),
DateTime.UtcNow,
CancellationToken.None),
Throws.TypeOf<StorageException>());
_salaryStorageContract.Verify(x =>
x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()),
Times.Once);
}
[Test]
public async Task CreateDocumentSalaryByPeriod_ShouldeSuccess_Test()
{
//Arrange
var startDate = DateTime.UtcNow.AddDays(-20);
var endDate = DateTime.UtcNow.AddDays(5);
var employee1 = new EmployeeDataModel(Guid.NewGuid().ToString(), "fio 1", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-20), DateTime.UtcNow.AddDays(-3));
var employee2 = new EmployeeDataModel(Guid.NewGuid().ToString(), "fio 2", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-20), DateTime.UtcNow.AddDays(-3));
_salaryStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(new List<SalaryDataModel>()
{
new(employee1.Id, DateTime.UtcNow.AddDays(-10), 100, employee1),
new(employee1.Id, endDate, 1000, employee1),
new(employee1.Id, startDate, 1000, employee1),
new(employee2.Id, DateTime.UtcNow.AddDays(-10), 100, employee2),
new(employee2.Id, DateTime.UtcNow.AddDays(-5), 200, employee2)
}));
_basePdfBuilder.Setup(x => x.AddHeader(It.IsAny<string>())).Returns(_basePdfBuilder.Object);
_basePdfBuilder.Setup(x => x.AddParagraph(It.IsAny<string>())).Returns(_basePdfBuilder.Object);
var countRows = 0;
(string, double) firstRow = default;
(string, double) secondRow = default;
_basePdfBuilder.Setup(x => x.AddPieChart(It.IsAny<string>(), It.IsAny<List<(string, double)>>()))
.Callback((string header, List<(string, double)> data) =>
{
countRows = data.Count;
firstRow = data[0];
secondRow = data[1];
})
.Returns(_basePdfBuilder.Object);
//Act
var data = await _reportContract.CreateDocumentSalaryByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None);
//Assert
Assert.Multiple(() =>
{
Assert.That(countRows, Is.EqualTo(2));
Assert.That(firstRow, Is.Not.EqualTo(default));
Assert.That(secondRow, Is.Not.EqualTo(default));
});
Assert.Multiple(() =>
{
Assert.That(firstRow.Item1, Is.EqualTo(employee1.FIO));
Assert.That(firstRow.Item2, Is.EqualTo(2100));
Assert.That(secondRow.Item1, Is.EqualTo(employee2.FIO));
Assert.That(secondRow.Item2, Is.EqualTo(300));
});
_salaryStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
_basePdfBuilder.Verify(x => x.AddHeader(It.IsAny<string>()), Times.Once);
_basePdfBuilder.Verify(x => x.AddParagraph(It.IsAny<string>()), Times.Once);
_basePdfBuilder.Verify(x => x.AddPieChart(It.IsAny<string>(), It.IsAny<List<(string, double)>>()), Times.Once);
_basePdfBuilder.Verify(x => x.Build(), Times.Once);
}
}

View File

@@ -8,7 +8,6 @@ using SquirrelContract.Exceptions;
using SquirrelContract.Infastructure.PostConfigurations;
using SquirrelContract.Infrastructure;
using SquirrelContract.StoragesContracts;
using SquirrelTests.Infrastructure;
namespace SquirrelTests.BusinessLogicContractsTests;
@@ -30,7 +29,7 @@ internal class SalaryBusinessLogicContractTests
_postStorageContract = new Mock<IPostStorageContract>();
_employeeStorageContract = new Mock<IEmployeeStorageContract>();
_salaryBusinessLogicContract = new SalaryBusinessLogicContract(_salaryStorageContract.Object,
_saleStorageContract.Object, _postStorageContract.Object, _employeeStorageContract.Object, StringLocalizerMockCreator.GetObject(), new Mock<ILogger>().Object, _salaryConfigurationTest);
_saleStorageContract.Object, _postStorageContract.Object, _employeeStorageContract.Object, new Mock<ILogger>().Object, _salaryConfigurationTest);
}
[TearDown]
@@ -87,12 +86,19 @@ internal class SalaryBusinessLogicContractTests
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalaries_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalaries_StorageThrowError_ThrowException_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
@@ -161,11 +167,19 @@ internal class SalaryBusinessLogicContractTests
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalariesByEmployee_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByEmployee(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), Guid.NewGuid().ToString()), Throws.TypeOf<NullListException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalariesByEmployee_StorageThrowError_ThrowException_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByEmployee(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
@@ -248,13 +262,52 @@ internal class SalaryBusinessLogicContractTests
Assert.That(sum, Is.EqualTo(rate));
}
[Test]
public void CalculateSalaryByMounth_SaleStorageReturnNull_ThrowException_Test()
{
//Arrange
var employeeId = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Bartender, new PostConfiguration() { Rate = 100 }));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new EmployeeDataModel(employeeId, "Test", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
[Test]
public void CalculateSalaryByMounth_PostStorageReturnNull_ThrowException_Test()
{
//Arrange
var employeeId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employeeId, null, DiscountType.None, false, [])]);
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new EmployeeDataModel(employeeId, "Test", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
[Test]
public void CalculateSalaryByMounth_EmployeeStorageReturnNull_ThrowException_Test()
{
//Arrange
var employeeId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employeeId, null, DiscountType.None, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Bartender, new PostConfiguration() { Rate = 100 }));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
[Test]
public void CalculateSalaryByMounth_SaleStorageThrowException_ThrowException_Test()
{
//Arrange
var employeeId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
.Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Bartender, new PostConfiguration() { Rate = 100 }));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
@@ -271,7 +324,7 @@ internal class SalaryBusinessLogicContractTests
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employeeId, null, DiscountType.None, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
.Throws(new StorageException(new InvalidOperationException()));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new EmployeeDataModel(employeeId, "Test", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
@@ -288,7 +341,7 @@ internal class SalaryBusinessLogicContractTests
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Bartender, new PostConfiguration() { Rate = 100 }));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
}

View File

@@ -5,7 +5,6 @@ using SquirrelContract.DataModels;
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using SquirrelTests.Infrastructure;
namespace SquirrelTests.BusinessLogicContractsTests;
@@ -19,7 +18,7 @@ internal class SaleBusinessLogicContractTests
public void OneTimeSetUp()
{
_saleStorageContract = new Mock<ISaleStorageContract>();
_saleBusinessLogicContract = new SaleBusinessLogicContract(_saleStorageContract.Object, StringLocalizerMockCreator.GetObject(), new Mock<ILogger>().Object);
_saleBusinessLogicContract = new SaleBusinessLogicContract(_saleStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
@@ -73,11 +72,19 @@ internal class SaleBusinessLogicContractTests
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
@@ -146,11 +153,19 @@ internal class SaleBusinessLogicContractTests
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByEmployeeByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByEmployeeByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
@@ -219,11 +234,19 @@ internal class SaleBusinessLogicContractTests
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByClientByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByClientByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
@@ -292,11 +315,19 @@ internal class SaleBusinessLogicContractTests
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByCocktailByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByCocktailByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByCocktailByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByCocktailByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
@@ -347,7 +378,7 @@ internal class SaleBusinessLogicContractTests
public void GetSaleByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_saleStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetSaleByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
@@ -381,7 +412,7 @@ internal class SaleBusinessLogicContractTests
public void InsertSale_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new ElementExistsException("Data", "Data", StringLocalizerMockCreator.GetObject()));
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), DiscountType.None, false, [new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])), Throws.TypeOf<ElementExistsException>());
@@ -408,7 +439,7 @@ internal class SaleBusinessLogicContractTests
public void InsertSale_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), DiscountType.None, false, [new SaleCocktailDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])), Throws.TypeOf<StorageException>());
@@ -434,7 +465,7 @@ internal class SaleBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id, StringLocalizerMockCreator.GetObject()));
_saleStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.CancelSale(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
@@ -461,7 +492,7 @@ internal class SaleBusinessLogicContractTests
public void CancelSale_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException(), StringLocalizerMockCreator.GetObject()));
_saleStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.CancelSale(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);

View File

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

View File

@@ -1,7 +1,6 @@
using SquirrelContract.DataModels;
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
using SquirrelTests.Infrastructure;
namespace SquirrelTests.DataModelsTests;
@@ -12,41 +11,41 @@ internal class CocktailDataModelTests
public void IdIsNullOrEmptyTest()
{
var cocktail = CreateDataModel(null, "name", 10.5, AlcoholType.Beer);
Assert.That(() => cocktail.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
cocktail = CreateDataModel(string.Empty, "name", 10.5, AlcoholType.Beer);
Assert.That(() => cocktail.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var cocktail = CreateDataModel("id", "name", 10.5, AlcoholType.Beer);
Assert.That(() => cocktail.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CocktailNameIsNullOrEmptyTest()
{
var cocktail = CreateDataModel(Guid.NewGuid().ToString(), null, 10.5, AlcoholType.Beer);
Assert.That(() => cocktail.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
cocktail = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, 10.5, AlcoholType.Beer);
Assert.That(() => cocktail.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PriceIsLessOrZeroTest()
{
var cocktail = CreateDataModel(Guid.NewGuid().ToString(), null, 0, AlcoholType.Beer);
Assert.That(() => cocktail.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
cocktail = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, -10.5, AlcoholType.Beer);
Assert.That(() => cocktail.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void BaseAlcoholIsNoneTest()
{
var cocktail = CreateDataModel(Guid.NewGuid().ToString(), null, 0, AlcoholType.None);
Assert.That(() => cocktail.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -57,7 +56,7 @@ internal class CocktailDataModelTests
var price = 10.5;
var baseAlcohol = AlcoholType.Vodka;
var cocktail = CreateDataModel(cocktailId, cocktailName, price, baseAlcohol);
Assert.That(() => cocktail.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.That(() => cocktail.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(cocktail.Id, Is.EqualTo(cocktailId));

View File

@@ -1,6 +1,5 @@
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelTests.Infrastructure;
namespace SquirrelTests.DataModelsTests;
@@ -11,25 +10,25 @@ internal class CocktailHistoryDataModelTests
public void CocktailIdIsNullOrEmptyTest()
{
var cocktail = CreateDataModel(null, 10);
Assert.That(() => cocktail.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
cocktail = CreateDataModel(string.Empty, 10);
Assert.That(() => cocktail.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ProductIdIsNotGuidTest()
{
var cocktail = CreateDataModel("id", 10);
Assert.That(() => cocktail.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void OldPriceIsLessOrZeroTest()
{
var cocktail = CreateDataModel(Guid.NewGuid().ToString(), 0);
Assert.That(() => cocktail.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
cocktail = CreateDataModel(Guid.NewGuid().ToString(), -10);
Assert.That(() => cocktail.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -38,7 +37,7 @@ internal class CocktailHistoryDataModelTests
var cocktailId = Guid.NewGuid().ToString();
var oldPrice = 10;
var cocktailHistory = CreateDataModel(cocktailId, oldPrice);
Assert.That(() => cocktailHistory.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.That(() => cocktailHistory.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(cocktailHistory.CocktailId, Is.EqualTo(cocktailId));

View File

@@ -1,6 +1,5 @@
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelTests.Infrastructure;
namespace SquirrelTests.DataModelsTests;
@@ -11,73 +10,73 @@ internal class EmployeeDataModelTests
public void IdIsNullOrEmptyTest()
{
var employee = CreateDataModel(null, "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => employee.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
employee = CreateDataModel(string.Empty, "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => employee.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var employee = CreateDataModel("id", "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => employee.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void FIOIsNullOrEmptyTest()
{
var employee = CreateDataModel(Guid.NewGuid().ToString(), null, "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => employee.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
employee = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => employee.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void EmailIsNullOrEmptyTest()
{
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", null, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => employee.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", string.Empty, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => employee.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void EmailIsIncorrectTest()
{
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => employee.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostIdIsNullOrEmptyTest()
{
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", null, DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => employee.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", string.Empty, DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => employee.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostIdIsNotGuidTest()
{
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", "postId", DateTime.Now.AddYears(-18), DateTime.Now, false);
Assert.That(() => employee.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void BirthDateIsNotCorrectTest()
{
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(1), DateTime.Now, false);
Assert.That(() => employee.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void BirthDateAndEmploymentDateIsNotCorrectTest()
{
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now.AddYears(-18).AddDays(-1), false);
Assert.That(() => employee.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now.AddYears(-16), false);
Assert.That(() => employee.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -91,15 +90,15 @@ internal class EmployeeDataModelTests
var employmentDate = DateTime.Now;
var isDelete = false;
var employee = CreateDataModel(employeeId, fio, employeeEmail, postId, birthDate, employmentDate, isDelete);
Assert.That(() => employee.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.That(() => employee.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(employee.Id, Is.EqualTo(employeeId));
Assert.That(employee.FIO, Is.EqualTo(fio));
Assert.That(employee.Email, Is.EqualTo(employeeEmail));
Assert.That(employee.PostId, Is.EqualTo(postId));
Assert.That(employee.BirthDate, Is.EqualTo(birthDate.ToUniversalTime()));
Assert.That(employee.EmploymentDate, Is.EqualTo(employmentDate.ToUniversalTime()));
Assert.That(employee.BirthDate, Is.EqualTo(birthDate));
Assert.That(employee.EmploymentDate, Is.EqualTo(employmentDate));
Assert.That(employee.IsDeleted, Is.EqualTo(isDelete));
});
}

View File

@@ -2,7 +2,6 @@
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
using SquirrelContract.Infastructure.PostConfigurations;
using SquirrelTests.Infrastructure;
namespace SquirrelTests.DataModelsTests;
@@ -13,39 +12,39 @@ internal class PostDataModelTests
public void IdIsNullOrEmptyTest()
{
var post = CreateDataModel(null, "name", PostType.Bartender, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(string.Empty, "name", PostType.Bartender, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var post = CreateDataModel("id", "name", PostType.Bartender, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostNameIsEmptyTest()
{
var manufacturer = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Bartender, new PostConfiguration() { Rate = 10 });
Assert.That(() => manufacturer.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
manufacturer = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Bartender, new PostConfiguration() { Rate = 10 });
Assert.That(() => manufacturer.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostTypeIsNoneTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.None, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ConfigurationModelIsNullTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Bartender, null);
Assert.That(() => post.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
@@ -53,9 +52,9 @@ internal class PostDataModelTests
public void RateIsLessOrZeroTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Bartender, new PostConfiguration() { Rate = 0 });
Assert.That(() => post.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Bartender, new PostConfiguration() { Rate = -10 });
Assert.That(() => post.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -66,10 +65,7 @@ internal class PostDataModelTests
var postType = PostType.Bartender;
var configuration = new PostConfiguration() { Rate = 10 };
var post = CreateDataModel(postId, postName, postType, configuration);
Assert.That(() =>
post.Validate(StringLocalizerMockCreator.GetObject()),
Throws.Nothing);
Assert.That(() => post.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(post.Id, Is.EqualTo(postId));
@@ -77,8 +73,6 @@ internal class PostDataModelTests
Assert.That(post.PostType, Is.EqualTo(postType));
Assert.That(post.ConfigurationModel, Is.EqualTo(configuration));
Assert.That(post.ConfigurationModel.Rate, Is.EqualTo(configuration.Rate));
Assert.That(post.ConfigurationModel.CultureName, Is.Not.Empty);
});
}

View File

@@ -1,6 +1,5 @@
using BarBelochkaContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelTests.Infrastructure;
namespace SquirrelTests.DataModelsTests;
@@ -11,25 +10,25 @@ internal class SalaryDataModelTests
public void EmployeeIdIsEmptyTest()
{
var salary = CreateDataModel(null, DateTime.Now, 10);
Assert.That(() => salary.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
salary = CreateDataModel(string.Empty, DateTime.Now, 10);
Assert.That(() => salary.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void EmployeeIdIsNotGuidTest()
{
var salary = CreateDataModel("employeeId", DateTime.Now, 10);
Assert.That(() => salary.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void SalaryIsLessOrZeroTest()
{
var salary = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0);
Assert.That(() => salary.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
salary = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now, -10);
Assert.That(() => salary.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -39,7 +38,7 @@ internal class SalaryDataModelTests
var salaryDate = DateTime.Now.AddDays(-3).AddMinutes(-5);
var enployeeSalary = 10;
var salary = CreateDataModel(employeeId, salaryDate, enployeeSalary);
Assert.That(() => salary.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.That(() => salary.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(salary.EmployeeId, Is.EqualTo(employeeId));

View File

@@ -1,6 +1,5 @@
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelTests.Infrastructure;
namespace SquirrelTests.DataModelsTests;
@@ -11,50 +10,50 @@ internal class SaleCocktailDataModelTests
public void SaleIdIsNullOrEmptyTest()
{
var saleCocktail = CreateDataModel(null, Guid.NewGuid().ToString(), 10, 1.1);
Assert.That(() => saleCocktail.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
saleCocktail = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10, 1.1);
Assert.That(() => saleCocktail.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void SaleIdIsNotGuidTest()
{
var saleCocktail = CreateDataModel("saleId", Guid.NewGuid().ToString(), 10, 1.1);
Assert.That(() => saleCocktail.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CocktailIdIsNullOrEmptyTest()
{
var saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), null, 10, 1.1);
Assert.That(() => saleCocktail.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
saleCocktail = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 10, 1.1);
Assert.That(() => saleCocktail.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CocktailIdIsNotGuidTest()
{
var saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), "cocktailId", 10, 1.1);
Assert.That(() => saleCocktail.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CountIsLessOrZeroTest()
{
var saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0, 1.1);
Assert.That(() => saleCocktail.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -10, 1.1);
Assert.That(() => saleCocktail.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PriceIsLessOrZeroTest()
{
var saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 0);
Assert.That(() => saleCocktail.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
saleCocktail = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, -10);
Assert.That(() => saleCocktail.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => saleCocktail.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -65,7 +64,7 @@ internal class SaleCocktailDataModelTests
var count = 10;
var price = 1.2;
var saleCocktail = CreateDataModel(saleId, cocktailId, count, price);
Assert.That(() => saleCocktail.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.That(() => saleCocktail.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(saleCocktail.SaleId, Is.EqualTo(saleId));

View File

@@ -1,7 +1,6 @@
using SquirrelContract.DataModels;
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
using SquirrelTests.Infrastructure;
namespace SquirrelTests.DataModelsTests;
@@ -12,47 +11,47 @@ internal class SaleDataModelTests
public void IdIsNullOrEmptyTest()
{
var sale = CreateDataModel(null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
sale = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var sale = CreateDataModel("id", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void EmployeeIdIsNullOrEmptyTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), null, Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
sale = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void EmployeeIdIsNotGuidTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), "employeeId", Guid.NewGuid().ToString(), DiscountType.OnSale, false, CreateSubDataModel());
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void ClientIdIsNotGuidTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "clientId", DiscountType.OnSale, false, CreateSubDataModel());
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void CocktailsIsNullOrEmptyTest()
{
var sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.OnSale, false, null);
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
sale = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.OnSale, false, []);
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetObject()), Throws.TypeOf<ValidationException>());
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
@@ -110,7 +109,7 @@ internal class SaleDataModelTests
var isCancel = true;
var cocktails = CreateSubDataModel();
var sale = CreateDataModel(saleId, employeeId, clientId, discountType, isCancel, cocktails);
Assert.That(() => sale.Validate(StringLocalizerMockCreator.GetObject()), Throws.Nothing);
Assert.That(() => sale.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(sale.Id, Is.EqualTo(saleId));

View File

@@ -1,21 +0,0 @@
using SquirrelContract.Resources;
using Microsoft.Extensions.Localization;
using Moq;
namespace SquirrelTests.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

@@ -1,448 +0,0 @@
using Castle.Core.Configuration;
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Wordprocessing;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.EntityFrameworkCore.Metadata.Conventions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using Serilog;
using SquirrelContract.BindingModels;
using SquirrelContract.Enums;
using SquirrelContract.Infastructure.PostConfigurations;
using SquirrelDatabase;
using SquirrelTests.Infrastructure;
using System.Net;
using System.Text;
using System.Text.Json;
using static NUnit.Framework.Internal.OSPlatform;
namespace SquirrelTests.LocalizationTests;
internal abstract class BaseLocalizationControllerTests
{
protected abstract string GetLocale();
private WebApplicationFactory<Program> _webApplication;
protected HttpClient HttpClient { get; private set; }
protected static SquirrelDbContext SquirrelDbContext { get; private set; }
protected static readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNameCaseInsensitive = true };
private static string _employeeId;
private static string _postId;
private static string _cocktailId;
[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());
SquirrelDbContext = _webApplication.Services.GetRequiredService<SquirrelDbContext>();
SquirrelDbContext.Database.EnsureDeleted();
SquirrelDbContext.Database.EnsureCreated();
}
[SetUp]
public void SetUp()
{
_employeeId = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "Employee").Id;
_postId = SquirrelDbContext.InsertPostToDatabaseAndReturn(postName: "Post").PostId;
_cocktailId = SquirrelDbContext.InsertCocktailToDatabaseAndReturn().Id;
}
[TearDown]
public void TearDown()
{
SquirrelDbContext.RemoveSalariesFromDatabase();
SquirrelDbContext.RemoveEmployeesFromDatabase();
SquirrelDbContext.RemovePostsFromDatabase();
SquirrelDbContext.RemoveCocktailsFromDatabase();
SquirrelDbContext.RemoveSalesFromDatabase();
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
SquirrelDbContext?.Database.EnsureDeleted();
SquirrelDbContext?.Dispose();
HttpClient?.Dispose();
_webApplication?.Dispose();
}
protected static async Task<T?> GetModelFromResponseAsync<T>(HttpResponseMessage response) =>
JsonSerializer.Deserialize<T>(await response.Content.ReadAsStringAsync(), JsonSerializerOptions);
protected static StringContent MakeContent(object model) =>
new(JsonSerializer.Serialize(model), Encoding.UTF8, "application/json");
[Test]
public async Task LoadCocktailsHistory_ReturnsFile()
{
//Arrange
SquirrelDbContext.InsertCocktailToDatabaseAndReturn(cocktailName: "Cocktail1");
SquirrelDbContext.InsertCocktailToDatabaseAndReturn(cocktailName: "Cocktail2");
SquirrelDbContext.InsertCocktailToDatabaseAndReturn(cocktailName: "Cocktail3");
//Act
var response = await HttpClient.GetAsync("/api/report/LoadHistories");
//Assert
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 AssertStreamAsync(response, $"file-{GetLocale()}.docx");
}
[Test]
public async Task LoadSales_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var employee = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn();
var cocktail1 = SquirrelDbContext.InsertCocktailToDatabaseAndReturn(cocktailName: "name 1");
var cocktail2 = SquirrelDbContext.InsertCocktailToDatabaseAndReturn(cocktailName: "name 2");
SquirrelDbContext.InsertSaleToDatabaseAndReturn(employee.Id, cocktails: [(cocktail1.Id, 10, 1.1), (cocktail2.Id, 10, 1.1)]);
SquirrelDbContext.InsertSaleToDatabaseAndReturn(employee.Id, cocktails: [(cocktail1.Id, 10, 1.1)]);
//Act
var response = await HttpClient.GetAsync($"/api/report/loadsales?fromDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
await AssertStreamAsync(response, $"file-{GetLocale()}.xlsx");
}
[Test]
public async Task LoadSalary_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var post = SquirrelDbContext.InsertPostToDatabaseAndReturn();
var employee1 = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "Иванов И.И", postId: post.PostId).AddPost(post);
var employee2 = SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(fio: "Ванов И.И", postId: post.PostId).AddPost(post);
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(employee1.Id, employeeSalary: 100, salaryDate: DateTime.UtcNow.AddDays(-10));
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(employee1.Id, employeeSalary: 1000, salaryDate: DateTime.UtcNow.AddDays(-5));
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(employee1.Id, employeeSalary: 200, salaryDate: DateTime.UtcNow.AddDays(5));
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(employee2.Id, employeeSalary: 500, salaryDate: DateTime.UtcNow.AddDays(-5));
SquirrelDbContext.InsertSalaryToDatabaseAndReturn(employee2.Id, employeeSalary: 300, salaryDate: DateTime.UtcNow.AddDays(-3));
//Act
var response = await HttpClient.GetAsync($"/api/report/loadsalary?fromDate={DateTime.Now.AddDays(-7):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.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("posts")]
[TestCase("employees/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()));
}
private static IEnumerable<TestCaseData> TestDataElementExists()
{
yield return new TestCaseData(() =>
{
var model = CreateEmployeeModel(_postId);
SquirrelDbContext.InsertEmployeeToDatabaseAndReturn(model.Id, postId: _postId);
return model;
}, "employees/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> TestDataIdIncorrect()
{
yield return new TestCaseData(() => {
var model = CreateSaleModel();
model.Id = "Id";
return model;
}, "sales/sale");
yield return new TestCaseData(() => {
var model = CreateCocktailModel();
model.Id = "Id";
return model;
}, "cocktails/register");
yield return new TestCaseData(() => {
var model = CreateEmployeeModel(_postId);
model.Id = "Id";
return model;
}, "employees/register");
yield return new TestCaseData(() => {
var model = CreateClientModel();
model.Id = "Id";
return model;
}, "clients");
}
protected abstract string MessageElementIdIncorrect();
[TestCaseSource(nameof(TestDataIdIncorrect))]
public async Task Api_Post_WhenDataIsIncorrect_ShouldBadRequest_Test(Func<object> createModel, string path)
{
//Arrange
var model = createModel();
//Act
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/{path}", MakeContent(model));
//Assert
Assert.That(JToken.Parse(await responseWithIdIncorrect.Content.ReadAsStringAsync()).ToString(), Does.StartWith(MessageElementIdIncorrect()));
}
[TestCase("cocktails/delete")]
[TestCase("sales/cancel")]
[TestCase("posts")]
[TestCase("employees/delete")]
[TestCase("clients")]
public async Task Api_DelElement_NotFound_Test(string path)
{
//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 PostBindingModel CreatePostModel(string? postId = null, string postName = "name", PostType postType = PostType.Manager, string? configuration = null)
=> new()
{
Id = postId ?? Guid.NewGuid().ToString(),
PostName = postName,
PostType = postType.ToString(),
ConfigurationJson = configuration ?? JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 })
};
protected abstract string MessageValidationErrorIDIsEmpty();
private static IEnumerable<TestCaseData> TestDataValidationErrorIdIsEmpty()
{
yield return new TestCaseData(() =>
{
var model = CreatePostModel();
model.Id = "";
return model;
}, "posts");
yield return new TestCaseData(() =>
{
var model = CreateCocktailModel();
model.Id = "";
return model;
}, "cocktails/changeinfo");
yield return new TestCaseData(() => {
var model = CreateEmployeeModel(_postId);
model.Id = "";
return model;
}, "employees/changeinfo/");
yield return new TestCaseData(() =>
{
var model = CreateClientModel();
model.Id = "";
return model;
}, "clients");
}
[TestCaseSource(nameof(TestDataValidationErrorIdIsEmpty))]
public async Task Api_Put_ValidationError_IdIsEmpty_ShouldBadRequest_Test(Func<object> createModel, string path)
{
//Arrange
var model = createModel();
//Act
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/{path}", MakeContent(model));
//Assert
Assert.That(JToken.Parse(await responseWithIdIncorrect.Content.ReadAsStringAsync()).ToString(), Does.StartWith(MessageValidationErrorIDIsEmpty()));
}
protected abstract string MessageValidationErrorIDIsNotGuid();
private static IEnumerable<TestCaseData> TestDataValidationErrorIdIsNotGuid()
{
yield return new TestCaseData(() =>
{
var model = CreatePostModel();
model.Id = "id";
return model;
}, "posts");
yield return new TestCaseData(() =>
{
var model = CreateCocktailModel();
model.Id = "id";
return model;
}, "cocktails/changeinfo");
yield return new TestCaseData(() => {
var model = CreateEmployeeModel(_postId);
model.Id = "id";
return model;
}, "employees/changeinfo/");
yield return new TestCaseData(() =>
{
var model = CreateClientModel();
model.Id = "id";
return model;
}, "clients");
}
[TestCaseSource(nameof(TestDataValidationErrorIdIsNotGuid))]
public async Task Api_Put_ValidationError_IIsNotGuid_ShouldBadRequest_Test(Func<object> createModel, string path)
{
//Arrange
var model = createModel();
//Act
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/{path}", MakeContent(model));
//Assert
Assert.That(JToken.Parse(await responseWithIdIncorrect.Content.ReadAsStringAsync()).ToString(), Does.StartWith(MessageValidationErrorIDIsNotGuid()));
}
protected abstract string MessageValidationStringIsEmpty();
private static IEnumerable<TestCaseData> TestDataValidationErrorStringIsEmpty()
{
yield return new TestCaseData(() =>
{
var model = CreateCocktailModel();
model.CocktailName = "";
return model;
}, "cocktails/changeinfo");
}
[TestCaseSource(nameof(TestDataValidationErrorStringIsEmpty))]
public async Task Api_Put_ValidationError_StringIsEmpty_ShouldBadRequest_Test(Func<object> createModel, string path)
{
//Arrange
var model = createModel();
//Act
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/{path}", MakeContent(model));
//Assert
Assert.That(JToken.Parse(await responseWithIdIncorrect.Content.ReadAsStringAsync()).ToString(), Does.StartWith(MessageValidationStringIsEmpty()));
}
protected abstract string MessageElemenValidationErrorPostNameEmpty();
[TestCase("posts")]
public async Task Api_Put_ValidationError_PostNameIsEmpty_ShouldBadRequest_Test(string path)
{
//Arrange
var model = CreatePostModel();
model.PostName = "";
//Act
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/{path}", MakeContent(model));
//Assert
Assert.That(JToken.Parse(await responseWithIdIncorrect.Content.ReadAsStringAsync()).ToString(), Does.StartWith(MessageElemenValidationErrorPostNameEmpty()));
}
protected abstract string MessageElemenValidationErrorFioISEmpty();
[TestCase("employees/changeinfo/")]
public async Task Api_Put_ValidationError_FioIsEmpty_ShouldBadRequest_Test(string path)
{
//Arrange
var model = CreateEmployeeModel(_postId);
model.FIO = "";
//Act
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/{path}", MakeContent(model));
//Assert
Assert.That(JToken.Parse(await responseWithIdIncorrect.Content.ReadAsStringAsync()).ToString(), Does.StartWith(MessageElemenValidationErrorFioISEmpty()));
}
private static EmployeeBindingModel CreateEmployeeModel(string postId, string? id = null, string fio = "fio", string email = "abc@gmail.com", DateTime? birthDate = null, DateTime? employmentDate = null)
{
return new()
{
Id = id ?? Guid.NewGuid().ToString(),
FIO = fio,
Email = email,
BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-22),
EmploymentDate = employmentDate ?? DateTime.UtcNow.AddDays(-5),
PostId = postId
};
}
private static CocktailBindingModel CreateCocktailModel(string? id = null, string name = "name", AlcoholType type = AlcoholType.Vodka, double price = 1)
=> new()
{
Id = id ?? Guid.NewGuid().ToString(),
CocktailName = name,
BaseAlcohol = type.ToString(),
Price = price
};
private static SaleBindingModel CreateSaleModel(string? employeeId = null, string? clientId = null, string? cocktailId = null, string? id = null, DiscountType discountType = DiscountType.OnSale, int count = 1, double price = 1.1)
{
var saleId = id ?? Guid.NewGuid().ToString();
return new()
{
Id = saleId,
EmployeeId = employeeId,
ClientId = clientId,
DiscountType = (int)discountType,
Cocktails = [new SaleCocktailBindingModel { SaleId = saleId, CocktailId = cocktailId, Count = count, Price = price }]
};
}
private static ClientBindingModel CreateClientModel(string? id = null, string fio = "fio", string phoneNumber = "+7-666-666-66-66", double discountSize = 10) =>
new()
{
Id = id ?? Guid.NewGuid().ToString(),
FIO = fio,
PhoneNumber = phoneNumber,
DiscountSize = discountSize
};
}

View File

@@ -1,15 +0,0 @@
namespace SquirrelTests.LocalizationTests;
[TestFixture]
internal class DefaultTests : BaseLocalizationControllerTests
{
protected override string GetLocale() => "bla-BLA";
protected override string MessageElementExists() => "Уже существует элемент со значением";
protected override string MessageElementNotFound() => "Не найден элемент по данным";
protected override string MessageElementIdIncorrect() => "Переданы неверные данные";
protected override string MessageValidationErrorIDIsEmpty() => "Переданы неверные данные: Значение в поле Id пусто";
protected override string MessageValidationErrorIDIsNotGuid() => "Переданы неверные данные: Значение в поле Id не является типом уникального идентификатора";
protected override string MessageValidationStringIsEmpty() => "Переданы неверные данные: Значение в поле CocktailName пусто";
protected override string MessageElemenValidationErrorPostNameEmpty() => "Переданы неверные данные: Значение в поле PostName пусто";
protected override string MessageElemenValidationErrorFioISEmpty() => "Переданы неверные данные: Значение в поле FIO пусто";
}

View File

@@ -1,17 +0,0 @@
using System.Xml.Linq;
namespace SquirrelTests.LocalizationTests;
internal class EnUSTests : BaseLocalizationControllerTests
{
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 MessageElementIdIncorrect() => "Incorrect data transmitted";
protected override string MessageValidationErrorIDIsEmpty() => "Incorrect data transmitted: The value in field Id is empty";
protected override string MessageValidationErrorIDIsNotGuid() => "Incorrect data transmitted: The value in the Id field is not a unique identifier type.";
protected override string MessageValidationStringIsEmpty() => "Incorrect data transmitted: The value in field CocktailName is empty";
protected override string MessageElemenValidationErrorPostNameEmpty() => "Incorrect data transmitted: The value in field PostName is empty";
protected override string MessageElemenValidationErrorFioISEmpty() => "Incorrect data transmitted: The value in field FIO is empty";
}

View File

@@ -1,14 +0,0 @@
namespace SquirrelTests.LocalizationTests;
internal class RuRUTests : BaseLocalizationControllerTests
{
protected override string GetLocale() => "ru-RU";
protected override string MessageElementExists() => "Уже существует элемент со значением";
protected override string MessageElementNotFound() => "Не найден элемент по данным";
protected override string MessageElementIdIncorrect() => "Переданы неверные данные";
protected override string MessageValidationErrorIDIsEmpty() => "Переданы неверные данные: Значение в поле Id пусто";
protected override string MessageValidationErrorIDIsNotGuid() => "Переданы неверные данные: Значение в поле Id не является типом уникального идентификатора";
protected override string MessageValidationStringIsEmpty() => "Переданы неверные данные: Значение в поле CocktailName пусто";
protected override string MessageElemenValidationErrorPostNameEmpty() => "Переданы неверные данные: Значение в поле PostName пусто";
protected override string MessageElemenValidationErrorFioISEmpty() => "Переданы неверные данные: Значение в поле FIO пусто";
}

View File

@@ -1,15 +0,0 @@
namespace SquirrelTests.LocalizationTests;
[TestFixture]
internal class ZhCNTests : BaseLocalizationControllerTests
{
protected override string GetLocale() => "zh-CN";
protected override string MessageElementExists() => "已经有一个具有参数";
protected override string MessageElementNotFound() => "未找到元素数据";
protected override string MessageElementIdIncorrect() => "传递的数据不正确";
protected override string MessageValidationErrorIDIsEmpty() => "传递的数据不正确: 字段 Id 的值为空";
protected override string MessageValidationErrorIDIsNotGuid() => "传递的数据不正确: 字段 Id 的值不是唯一标识符类型";
protected override string MessageValidationStringIsEmpty() => "传递的数据不正确: 字段 CocktailName 的值为空";
protected override string MessageElemenValidationErrorPostNameEmpty() => "传递的数据不正确: 字段 PostName 的值为空";
protected override string MessageElemenValidationErrorFioISEmpty() => "传递的数据不正确: 字段 FIO 的值为空";
}

View File

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

View File

@@ -18,7 +18,7 @@ internal class CocktailStorageContractTests : BaseStorageContractTest
[SetUp]
public void SetUp()
{
_cocktailStorageContract = new CocktailStorageContract(SquirrelDbContext, StringLocalizerMockCreator.GetObject());
_cocktailStorageContract = new CocktailStorageContract(SquirrelDbContext);
}
[TearDown]

View File

@@ -18,7 +18,7 @@ internal class EmployeeStorageContractTests : BaseStorageContractTest
[SetUp]
public void SetUp()
{
_workerStorageContract = new EmployeeStorageContract(SquirrelDbContext, StringLocalizerMockCreator.GetObject());
_workerStorageContract = new EmployeeStorageContract(SquirrelDbContext);
}
[TearDown]

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