forked from slavaxom9k/PIBD-23_Fomichev_V.S._MagicCarpet
Compare commits
6 Commits
lab04_Api_
...
lab06_Repo
| Author | SHA1 | Date | |
|---|---|---|---|
| bf2577198b | |||
| 478200b4a4 | |||
| e984b4d66f | |||
| afe18e1631 | |||
| c9793000e3 | |||
| 064a7c88b2 |
@@ -1,74 +0,0 @@
|
||||
using MagicCarpetContracts.BusinessLogicContracts;
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using MagicCarpetContracts.Enums;
|
||||
using MagicCarpetContracts.Exceptions;
|
||||
using MagicCarpetContracts.Extensions;
|
||||
using MagicCarpetContracts.StoragesContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetBusinessLogic.Implementations;
|
||||
|
||||
public class AgencyBusinessLogicContract(IAgencyStorageContract agencyStorageContract, ILogger logger) : IAgencyBusinessLogicContract
|
||||
{
|
||||
private readonly IAgencyStorageContract _agencyStorageContract = agencyStorageContract;
|
||||
private readonly ILogger _logger = logger;
|
||||
public List<AgencyDataModel> GetAllComponents()
|
||||
{
|
||||
_logger.LogInformation("GetAllComponents");
|
||||
return _agencyStorageContract.GetList() ?? throw new NullListException();
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
public AgencyDataModel GetComponentByData(string data)
|
||||
{
|
||||
_logger.LogInformation("Get element by data: {data}", data);
|
||||
if (data.IsEmpty())
|
||||
{
|
||||
throw new ArgumentNullException(nameof(data));
|
||||
}
|
||||
if (!data.IsGuid())
|
||||
{
|
||||
throw new ElementNotFoundException(data);
|
||||
}
|
||||
return _agencyStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
|
||||
|
||||
return new("", TourType.None, 0, []);
|
||||
}
|
||||
|
||||
public void InsertComponent(AgencyDataModel agencyDataModel)
|
||||
{
|
||||
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(agencyDataModel));
|
||||
ArgumentNullException.ThrowIfNull(agencyDataModel);
|
||||
agencyDataModel.Validate();
|
||||
_agencyStorageContract.AddElement(agencyDataModel);
|
||||
}
|
||||
|
||||
public void UpdateComponent(AgencyDataModel agencyDataModel)
|
||||
{
|
||||
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(agencyDataModel));
|
||||
ArgumentNullException.ThrowIfNull(agencyDataModel);
|
||||
agencyDataModel.Validate();
|
||||
_agencyStorageContract.UpdElement(agencyDataModel);
|
||||
}
|
||||
|
||||
public void DeleteComponent(string id)
|
||||
{
|
||||
logger.LogInformation("Delete by id: {id}", id);
|
||||
if (id.IsEmpty())
|
||||
{
|
||||
throw new ArgumentNullException(nameof(id));
|
||||
}
|
||||
if (!id.IsGuid())
|
||||
{
|
||||
throw new ValidationException("Id is not a unique identifier");
|
||||
}
|
||||
_agencyStorageContract.DelElement(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
using MagicCarpetBusinessLogic.OfficePackage;
|
||||
using MagicCarpetContracts.BusinessLogicContracts;
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using MagicCarpetContracts.Exceptions;
|
||||
using MagicCarpetContracts.Extensions;
|
||||
using MagicCarpetContracts.StoragesContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
namespace MagicCarpetBusinessLogic.Implementations;
|
||||
|
||||
public class ReportContract(ITourStorageContract tourStorageContract, ISalaryStorageContract salaryStorageContract, ISaleStorageContract saleStorageContract,
|
||||
BaseWordBuilder baseWordBuilder, BaseExcelBuilder baseExcelBuilder, BasePdfBuilder basePdfBuilder, ILogger logger) : IReportContract
|
||||
{
|
||||
private readonly ITourStorageContract _cocktailStorageContract = tourStorageContract;
|
||||
private readonly ISalaryStorageContract _salaryStorageContract = salaryStorageContract;
|
||||
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
|
||||
private readonly BaseWordBuilder _baseWordBuilder = baseWordBuilder;
|
||||
private readonly BaseExcelBuilder _baseExcelBuilder = baseExcelBuilder;
|
||||
private readonly BasePdfBuilder _basePdfBuilder = basePdfBuilder;
|
||||
private readonly ILogger _logger = logger;
|
||||
|
||||
internal static readonly string[] documentHeader = ["Название тура", "Старая цена", "Дата"];
|
||||
internal static readonly string[] tableHeader = ["Дата", "Сумма", "Скидка", "Товар", "Кол-во"];
|
||||
|
||||
public Task<List<TourAndTourHistoryDataModel>> GetDataToursHistoryAsync(CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Get data PostHistory");
|
||||
return GetToursHistoriesAsync(ct);
|
||||
}
|
||||
|
||||
public async Task<Stream> CreateDocumentToursHistoryAsync(CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Create report TourHistory");
|
||||
var data = await GetToursHistoriesAsync(ct) ?? throw new InvalidOperationException("No found data");
|
||||
|
||||
return _baseWordBuilder
|
||||
.AddHeader("История туров")
|
||||
.AddParagraph($"Сформировано на дату {DateTime.Now}")
|
||||
.AddTable(
|
||||
[3000, 3000, 3000],
|
||||
[.. new List<string[]>() { documentHeader }
|
||||
.Union(data.SelectMany(x =>
|
||||
(new List<string[]>() { new[] { x.TourName, "", "" } })
|
||||
.Union(x.Histories.Zip(x.Data, (price, date) => new[] { "", price, date }))
|
||||
).ToList())
|
||||
])
|
||||
.Build();
|
||||
}
|
||||
|
||||
private async Task<List<TourAndTourHistoryDataModel>> GetToursHistoriesAsync(CancellationToken ct) =>
|
||||
[.. (await _cocktailStorageContract.GetHistoriesListAsync(ct)).GroupBy(x => x.TourName).Select(x => new TourAndTourHistoryDataModel {
|
||||
TourName = 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)
|
||||
{
|
||||
string[] tableHeader1 = ["Сотрудник", "Дата", "Сумма", "Скидка", "Товар", "Кол-во"];
|
||||
|
||||
_logger.LogInformation("Create report SalesByPeriod from {dateStart} to {dateFinish}", dateStart, dateFinish);
|
||||
var data = await GetDataBySalesAsync(dateStart, dateFinish, ct) ?? throw new InvalidOperationException("No found data");
|
||||
|
||||
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.Tours ?? Enumerable.Empty<SaleTourDataModel>())
|
||||
{
|
||||
tableRows.Add(new string[]
|
||||
{
|
||||
"", "", "", "", cocktail.TourName, cocktail.Count.ToString("N2")
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
tableRows.Add(new string[]
|
||||
{
|
||||
"Всего", "", data.Sum(x => x.Sum).ToString("N2"), data.Sum(x => x.Discount).ToString("N2"), "", ""
|
||||
});
|
||||
|
||||
return _baseExcelBuilder
|
||||
.AddHeader("Продажи за период", 0, 6)
|
||||
.AddParagraph($"с {dateStart.ToShortDateString()} по {dateFinish.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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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("No found data");
|
||||
return _basePdfBuilder
|
||||
.AddHeader("Зарплатная ведомость")
|
||||
.AddParagraph($"за период с {dateStart.ToShortDateString()} по {dateFinish.ToShortDateString()}")
|
||||
.AddPieChart("Начисления", [.. data.Select(x => (x.EmployeeFIO, x.TotalSalary))])
|
||||
.Build();
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using MagicCarpetContracts.Exceptions;
|
||||
using MagicCarpetContracts.Extensions;
|
||||
using MagicCarpetContracts.Infrastructure;
|
||||
using MagicCarpetContracts.Infrastructure.PostConfigurations;
|
||||
using MagicCarpetContracts.StoragesContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
@@ -12,13 +14,15 @@ using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetBusinessLogic.Implementations;
|
||||
public class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract,ISaleStorageContract saleStorageContract,
|
||||
IPostStorageContract postStorageContract, IEmployeeStorageContract employeeStorageContract, ILogger logger) : ISalaryBusinessLogicContract
|
||||
IPostStorageContract postStorageContract, IEmployeeStorageContract employeeStorageContract, ILogger logger, IConfigurationSalary сonfiguration) : ISalaryBusinessLogicContract
|
||||
{
|
||||
private readonly ILogger _logger = logger;
|
||||
private readonly ISalaryStorageContract _salaryStorageContract = salaryStorageContract;
|
||||
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
|
||||
private readonly IPostStorageContract _postStorageContract = postStorageContract;
|
||||
private readonly IEmployeeStorageContract _employeeStorageContract = employeeStorageContract;
|
||||
private readonly IConfigurationSalary _salaryConfiguration = сonfiguration;
|
||||
private readonly Lock _lockObject = new();
|
||||
public List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
_logger.LogInformation("GetAllSalaries params: {fromDate}, {toDate}", fromDate, toDate);
|
||||
@@ -55,13 +59,66 @@ public class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageCon
|
||||
var employees = _employeeStorageContract.GetList() ?? throw new NullListException();
|
||||
foreach (var employee in employees)
|
||||
{
|
||||
var sales = _saleStorageContract.GetList(startDate, finishDate, employeeId: employee.Id)?.Sum(x => x.Sum) ??
|
||||
throw new NullListException();
|
||||
var post = _postStorageContract.GetElementById(employee.PostId) ??
|
||||
throw new NullListException();
|
||||
var salary = post.Salary + sales * 0.1;
|
||||
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,
|
||||
TravelAgentPostConfiguration cpc => CalculateSalaryForTravelAgent(sales, startDate, finishDate, cpc),
|
||||
ChiefPostConfiguration spc => CalculateSalaryForChief(startDate, finishDate, spc),
|
||||
PostConfiguration pc => pc.Rate,
|
||||
};
|
||||
_logger.LogDebug("The employee {employeeId} was paid a salary of {salary}", employee.Id, salary);
|
||||
_salaryStorageContract.AddElement(new SalaryDataModel(employee.Id, DateTime.SpecifyKind(finishDate, DateTimeKind.Utc), salary));
|
||||
_salaryStorageContract.AddElement(new SalaryDataModel(employee.Id, finishDate, salary));
|
||||
}
|
||||
}
|
||||
private double CalculateSalaryForTravelAgent(List<SaleDataModel> sales, DateTime startDate, DateTime finishDate, TravelAgentPostConfiguration config)
|
||||
{
|
||||
var calcPercent = 0.0;
|
||||
var dates = new List<DateTime>();
|
||||
for (var date = startDate; date < finishDate; date = date.AddDays(1))
|
||||
{
|
||||
dates.Add(date);
|
||||
}
|
||||
|
||||
var parallelOptions = new ParallelOptions
|
||||
{
|
||||
MaxDegreeOfParallelism = _salaryConfiguration.MaxConcurrentThreads
|
||||
};
|
||||
|
||||
Parallel.ForEach(dates, parallelOptions, date =>
|
||||
{
|
||||
var salesInDay = sales.Where(x => x.SaleDate.Date == date.Date).ToArray();
|
||||
if (salesInDay.Length > 0)
|
||||
{
|
||||
lock (_lockObject)
|
||||
{
|
||||
calcPercent += (salesInDay.Sum(x => x.Sum) / salesInDay.Length) * config.SalePercent;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
double calcBonusTask = 0;
|
||||
try
|
||||
{
|
||||
calcBonusTask = sales.Where(x => x.Sum > _salaryConfiguration.ExtraSaleSum).Sum(x => x.Sum) * config.BonusForExtraSales;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error in bonus calculation");
|
||||
}
|
||||
return config.Rate + calcPercent + calcBonusTask;
|
||||
}
|
||||
private double CalculateSalaryForChief(DateTime startDate, DateTime finishDate, ChiefPostConfiguration config)
|
||||
{
|
||||
try
|
||||
{
|
||||
return config.Rate + config.PersonalCountTrendPremium * _employeeStorageContract.GetEmployeeTrend(startDate, finishDate);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error in the chief payroll process");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,11 +13,10 @@ using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetBusinessLogic.Implementations;
|
||||
|
||||
public class SaleBusinessLogicContract(ISaleStorageContract saleStorageContract,IAgencyStorageContract agencyStorageContract, ILogger logger) : ISaleBusinessLogicContract
|
||||
public class SaleBusinessLogicContract(ISaleStorageContract saleStorageContract, ILogger logger) : ISaleBusinessLogicContract
|
||||
{
|
||||
private readonly ILogger _logger = logger;
|
||||
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
|
||||
private readonly IAgencyStorageContract _agencyStorageContract = agencyStorageContract;
|
||||
|
||||
public List<SaleDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
@@ -102,10 +101,6 @@ public class SaleBusinessLogicContract(ISaleStorageContract saleStorageContract,
|
||||
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(saleDataModel));
|
||||
ArgumentNullException.ThrowIfNull(saleDataModel);
|
||||
saleDataModel.Validate();
|
||||
if (!_agencyStorageContract.CheckComponents(saleDataModel))
|
||||
{
|
||||
throw new InsufficientException("Dont have tour in agency");
|
||||
}
|
||||
_saleStorageContract.AddElement(saleDataModel);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
using MagicCarpetContracts.BusinessLogicContracts;
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using MagicCarpetContracts.Enums;
|
||||
using MagicCarpetContracts.Exceptions;
|
||||
using MagicCarpetContracts.Extensions;
|
||||
using MagicCarpetContracts.StoragesContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetBusinessLogic.Implementations;
|
||||
|
||||
public class SuppliesBusinessLogicContract(ISuppliesStorageContract suppliesStorageContract, ILogger logger) : ISuppliesBusinessLogicContract
|
||||
{
|
||||
private readonly ISuppliesStorageContract _suppliesStorageContract = suppliesStorageContract;
|
||||
private readonly ILogger _logger = logger;
|
||||
|
||||
public List<SuppliesDataModel> GetAllComponents()
|
||||
{
|
||||
_logger.LogInformation("GetAllComponents");
|
||||
return _suppliesStorageContract.GetList() ?? throw new NullListException();
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
public SuppliesDataModel GetComponentByData(string data)
|
||||
{
|
||||
_logger.LogInformation("Get element by data: {data}", data);
|
||||
if (data.IsEmpty())
|
||||
{
|
||||
throw new ArgumentNullException(nameof(data));
|
||||
}
|
||||
if (!data.IsGuid())
|
||||
{
|
||||
throw new ElementNotFoundException(data);
|
||||
}
|
||||
return _suppliesStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
|
||||
|
||||
return new("", TourType.None, DateTime.UtcNow, 0, []);
|
||||
}
|
||||
|
||||
public void InsertComponent(SuppliesDataModel suppliesDataModel)
|
||||
{
|
||||
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(suppliesDataModel));
|
||||
ArgumentNullException.ThrowIfNull(suppliesDataModel);
|
||||
suppliesDataModel.Validate();
|
||||
_suppliesStorageContract.AddElement(suppliesDataModel);
|
||||
}
|
||||
|
||||
public void UpdateComponent(SuppliesDataModel suppliesDataModel)
|
||||
{
|
||||
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(suppliesDataModel));
|
||||
ArgumentNullException.ThrowIfNull(suppliesDataModel);
|
||||
suppliesDataModel.Validate();
|
||||
_suppliesStorageContract.UpdElement(suppliesDataModel);
|
||||
}
|
||||
}
|
||||
@@ -56,6 +56,7 @@ public class TourBusinessLogicContract(ITourStorageContract tourStorageContract,
|
||||
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(tourDataModel));
|
||||
ArgumentNullException.ThrowIfNull(tourDataModel);
|
||||
tourDataModel.Validate();
|
||||
_tourStorageContract.AddElement(tourDataModel);
|
||||
}
|
||||
|
||||
public void UpdateTour(TourDataModel tourDataModel)
|
||||
@@ -63,6 +64,7 @@ public class TourBusinessLogicContract(ITourStorageContract tourStorageContract,
|
||||
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(tourDataModel));
|
||||
ArgumentNullException.ThrowIfNull(tourDataModel);
|
||||
tourDataModel.Validate();
|
||||
_tourStorageContract.UpdElement(tourDataModel);
|
||||
}
|
||||
|
||||
public void DeleteTour(string id)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
@@ -11,7 +11,9 @@
|
||||
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.2" />
|
||||
<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" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetBusinessLogic.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();
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetBusinessLogic.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();
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetBusinessLogic.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();
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
using MigraDoc.DocumentObjectModel;
|
||||
using MigraDoc.DocumentObjectModel.Shapes.Charts;
|
||||
using MigraDoc.Rendering;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetBusinessLogic.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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
using DocumentFormat.OpenXml.Packaging;
|
||||
using DocumentFormat.OpenXml.Spreadsheet;
|
||||
using DocumentFormat.OpenXml;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetBusinessLogic.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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
using DocumentFormat.OpenXml;
|
||||
using DocumentFormat.OpenXml.Packaging;
|
||||
using DocumentFormat.OpenXml.Wordprocessing;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetBusinessLogic.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;
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
using MagicCarpetContracts.AdapterContracts.OperationResponses;
|
||||
using MagicCarpetContracts.BindingModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.AdapterContracts;
|
||||
|
||||
public interface IAgencyAdapter
|
||||
{
|
||||
AgencyOperationResponse GetAllComponents();
|
||||
AgencyOperationResponse GetComponentByData(string data);
|
||||
AgencyOperationResponse InsertComponent(AgencyBindingModel warehouseDataModel);
|
||||
AgencyOperationResponse UpdateComponent(AgencyBindingModel warehouseDataModel);
|
||||
AgencyOperationResponse DeleteComponent(string id);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using MagicCarpetContracts.AdapterContracts.OperationResponses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.AdapterContracts;
|
||||
|
||||
public interface IReportAdapter
|
||||
{
|
||||
Task<ReportOperationResponse> GetDataToursHistoryAsync(CancellationToken ct);
|
||||
Task<ReportOperationResponse> GetDataBySalesByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
Task<ReportOperationResponse> GetDataSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
Task<ReportOperationResponse> CreateDocumentToursHistoryAsync(CancellationToken ct);
|
||||
Task<ReportOperationResponse> CreateDocumentSalesByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
Task<ReportOperationResponse> CreateDocumentSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
using MagicCarpetContracts.AdapterContracts.OperationResponses;
|
||||
using MagicCarpetContracts.BindingModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.AdapterContracts;
|
||||
|
||||
public interface ISuppliesAdapter
|
||||
{
|
||||
SuppliesOperationResponse GetAllComponents();
|
||||
SuppliesOperationResponse GetComponentByData(string data);
|
||||
SuppliesOperationResponse InsertComponent(SuppliesBindingModel componentDataModel);
|
||||
SuppliesOperationResponse UpdateComponent(SuppliesBindingModel componentDataModel);
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using MagicCarpetContracts.Infrastructure;
|
||||
using MagicCarpetContracts.ViewModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class AgencyOperationResponse : OperationResponse
|
||||
{
|
||||
public static AgencyOperationResponse OK(List<AgencyViewModel> data) => OK<AgencyOperationResponse, List<AgencyViewModel>>(data);
|
||||
|
||||
public static AgencyOperationResponse OK(AgencyViewModel data) => OK<AgencyOperationResponse, AgencyViewModel>(data);
|
||||
|
||||
public static AgencyOperationResponse NoContent() => NoContent<AgencyOperationResponse>();
|
||||
|
||||
public static AgencyOperationResponse NotFound(string message) => NotFound<AgencyOperationResponse>(message);
|
||||
|
||||
public static AgencyOperationResponse BadRequest(string message) => BadRequest<AgencyOperationResponse>(message);
|
||||
|
||||
public static AgencyOperationResponse InternalServerError(string message) => InternalServerError<AgencyOperationResponse>(message);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
using MagicCarpetContracts.Infrastructure;
|
||||
using MagicCarpetContracts.ViewModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class ReportOperationResponse : OperationResponse
|
||||
{
|
||||
public static ReportOperationResponse OK(List<TourAndTourHistoryViewModel> data) => OK<ReportOperationResponse, List<TourAndTourHistoryViewModel>>(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);
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
using MagicCarpetContracts.Infrastructure;
|
||||
using MagicCarpetContracts.ViewModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class SuppliesOperationResponse : OperationResponse
|
||||
{
|
||||
public static SuppliesOperationResponse OK(List<SuppliesViewModel> data) => OK<SuppliesOperationResponse, List<SuppliesViewModel>>(data);
|
||||
|
||||
public static SuppliesOperationResponse OK(SuppliesViewModel data) => OK<SuppliesOperationResponse, SuppliesViewModel>(data);
|
||||
|
||||
public static SuppliesOperationResponse NoContent() => NoContent<SuppliesOperationResponse>();
|
||||
|
||||
public static SuppliesOperationResponse NotFound(string message) => NotFound<SuppliesOperationResponse>(message);
|
||||
|
||||
public static SuppliesOperationResponse BadRequest(string message) => BadRequest<SuppliesOperationResponse>(message);
|
||||
|
||||
public static SuppliesOperationResponse InternalServerError(string message) => InternalServerError<SuppliesOperationResponse>(message);
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
using MagicCarpetContracts.Enums;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.BindingModels;
|
||||
|
||||
public class AgencyBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public TourType? TourType { get; set; }
|
||||
public int Count { get; set; }
|
||||
public List<TourAgencyBindingModel>? Tours { get; set; }
|
||||
}
|
||||
@@ -16,5 +16,5 @@ public class PostBindingModel
|
||||
|
||||
public string? PostType { get; set; }
|
||||
|
||||
public double Salary { get; set; }
|
||||
public string? ConfigurationJson { get; set; }
|
||||
}
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
using MagicCarpetContracts.Enums;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.BindingModels;
|
||||
|
||||
public class SuppliesBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public TourType? TourType { get; set; }
|
||||
public DateTime ProductuionDate { get; set; }
|
||||
public int Count { get; set; }
|
||||
public List<TourSuppliesBindingModel>? Tours { get; set; }
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.BindingModels;
|
||||
|
||||
public class TourAgencyBindingModel
|
||||
{
|
||||
public string? AgencyId { get; set; }
|
||||
public string? TourId { get; set; }
|
||||
public int Count { get; set; }
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.BindingModels;
|
||||
|
||||
public class TourSuppliesBindingModel
|
||||
{
|
||||
public string? SuppliesId { get; set; }
|
||||
public string? TourId { get; set; }
|
||||
public int Count { get; set; }
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.BusinessLogicContracts;
|
||||
|
||||
public interface IAgencyBusinessLogicContract
|
||||
{
|
||||
List<AgencyDataModel> GetAllComponents();
|
||||
AgencyDataModel GetComponentByData(string data);
|
||||
void InsertComponent(AgencyDataModel agencyDataModel);
|
||||
void UpdateComponent(AgencyDataModel agencyDataModel);
|
||||
void DeleteComponent(string id);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.BusinessLogicContracts;
|
||||
|
||||
public interface IReportContract
|
||||
{
|
||||
Task<List<TourAndTourHistoryDataModel>> GetDataToursHistoryAsync(CancellationToken ct);
|
||||
Task<Stream> CreateDocumentToursHistoryAsync(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);
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.BusinessLogicContracts;
|
||||
|
||||
public interface ISuppliesBusinessLogicContract
|
||||
{
|
||||
List<SuppliesDataModel> GetAllComponents();
|
||||
SuppliesDataModel GetComponentByData(string data);
|
||||
void InsertComponent(SuppliesDataModel componentDataModel);
|
||||
void UpdateComponent(SuppliesDataModel componentDataModel);
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
using MagicCarpetContracts.Enums;
|
||||
using MagicCarpetContracts.Exceptions;
|
||||
using MagicCarpetContracts.Extensions;
|
||||
using MagicCarpetContracts.Infrastructure;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.DataModels;
|
||||
|
||||
public class AgencyDataModel(string id, TourType tourType, int count, List<TourAgencyDataModel> tours) : IValidation
|
||||
{
|
||||
public string Id { get; private set; } = id;
|
||||
public TourType TourType { get; private set; } = tourType;
|
||||
public int Count { get; private set; } = count;
|
||||
public List<TourAgencyDataModel> Tours { get; private set; } = tours;
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (Id.IsEmpty())
|
||||
throw new ValidationException("Field Id is empty");
|
||||
if (!Id.IsGuid())
|
||||
throw new ValidationException("The value in the field Id is not a unique identifier");
|
||||
if (TourType == TourType.None)
|
||||
throw new ValidationException("Field Type is empty");
|
||||
if (Count <= 0)
|
||||
throw new ValidationException("Field Count is less than or equal to 0");
|
||||
if ((Tours?.Count ?? 0) == 0)
|
||||
throw new ValidationException("The sale must include tours");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.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; }
|
||||
}
|
||||
@@ -2,6 +2,10 @@
|
||||
using MagicCarpetContracts.Exceptions;
|
||||
using MagicCarpetContracts.Extensions;
|
||||
using MagicCarpetContracts.Infrastructure;
|
||||
using MagicCarpetContracts.Infrastructure.PostConfigurations;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@@ -10,12 +14,26 @@ using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.DataModels;
|
||||
|
||||
public class PostDataModel(string postId, string postName, PostType postType, double salary) : IValidation
|
||||
public class PostDataModel(string postId, string postName, PostType postType, PostConfiguration configuration) : IValidation
|
||||
{
|
||||
public string Id { get; private set; } = postId;
|
||||
public string PostName { get; private set; } = postName;
|
||||
public PostType PostType { get; private set; } = postType;
|
||||
public double Salary { get; private set; } = salary;
|
||||
public PostConfiguration ConfigurationModel { get; private set; } = configuration;
|
||||
|
||||
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(TravelAgentPostConfiguration) => JsonConvert.DeserializeObject<TravelAgentPostConfiguration>(configurationJson)!,
|
||||
nameof(ChiefPostConfiguration) => JsonConvert.DeserializeObject<ChiefPostConfiguration>(configurationJson)!,
|
||||
_ => JsonConvert.DeserializeObject<PostConfiguration>(configurationJson)!,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
@@ -27,7 +45,9 @@ public class PostDataModel(string postId, string postName, PostType postType, do
|
||||
throw new ValidationException("Field PostName is empty");
|
||||
if (PostType == PostType.None)
|
||||
throw new ValidationException("Field PostType is empty");
|
||||
if (Salary <= 0)
|
||||
throw new ValidationException("Field Salary is empty");
|
||||
if (ConfigurationModel is null)
|
||||
throw new ValidationException("Field ConfigurationModel is not initialized");
|
||||
if (ConfigurationModel!.Rate <= 0)
|
||||
throw new ValidationException("Field Rate is less or equal zero");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
using MagicCarpetContracts.Enums;
|
||||
using MagicCarpetContracts.Exceptions;
|
||||
using MagicCarpetContracts.Extensions;
|
||||
using MagicCarpetContracts.Infrastructure;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using static System.Runtime.InteropServices.JavaScript.JSType;
|
||||
|
||||
namespace MagicCarpetContracts.DataModels;
|
||||
|
||||
public class SuppliesDataModel(string id, TourType tourType, DateTime productuionDate, int count, List<TourSuppliesDataModel> tours) : IValidation
|
||||
{
|
||||
public string Id { get; private set; } = id;
|
||||
public TourType TourType { get; private set; } = tourType;
|
||||
public DateTime ProductuionDate { get; private set; } = productuionDate;
|
||||
public int Count { get; private set; } = count;
|
||||
public List<TourSuppliesDataModel> Tours { get; private set; } = tours;
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (Id.IsEmpty())
|
||||
throw new ValidationException("Field Id is empty");
|
||||
if (!Id.IsGuid())
|
||||
throw new ValidationException("The value in the field Id is not a unique identifier");
|
||||
if (TourType == TourType.None)
|
||||
throw new ValidationException("Field Type is empty");
|
||||
if (Count <= 0)
|
||||
throw new ValidationException("Field Count is less than or equal to 0");
|
||||
if ((Tours?.Count ?? 0) == 0)
|
||||
throw new ValidationException("The sale must include tours");
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
using MagicCarpetContracts.Exceptions;
|
||||
using MagicCarpetContracts.Extensions;
|
||||
using MagicCarpetContracts.Infrastructure;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.DataModels;
|
||||
|
||||
public class TourAgencyDataModel(string agencyId, string tourId, int count) : IValidation
|
||||
{
|
||||
public string AgencyId { get; private set; } = agencyId;
|
||||
public string TourId { get; private set; } = tourId;
|
||||
public int Count { get; private set; } = count;
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (AgencyId.IsEmpty())
|
||||
throw new ValidationException("Field AgencyId is empty");
|
||||
if (!AgencyId.IsGuid())
|
||||
throw new ValidationException("The value in the field AgencyId is not a unique identifier");
|
||||
if (TourId.IsEmpty())
|
||||
throw new ValidationException("Field TourId is empty");
|
||||
if (!TourId.IsGuid())
|
||||
throw new ValidationException("The value in the field TourId is not a unique identifier");
|
||||
if (Count <= 0)
|
||||
throw new ValidationException("Field Count is less than or equal to 0");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.DataModels;
|
||||
|
||||
public class TourAndTourHistoryDataModel
|
||||
{
|
||||
public required string TourName { get; set; }
|
||||
public required List<string> Histories { get; set; }
|
||||
public required List<string> Data { get; set; }
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
using MagicCarpetContracts.Exceptions;
|
||||
using MagicCarpetContracts.Extensions;
|
||||
using MagicCarpetContracts.Infrastructure;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.DataModels;
|
||||
|
||||
public class TourSuppliesDataModel(string suppliesId, string tourId, int count) : IValidation
|
||||
{
|
||||
public string SuppliesId { get; private set; } = suppliesId;
|
||||
public string TourId { get; private set; } = tourId;
|
||||
public int Count { get; private set; } = count;
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (SuppliesId.IsEmpty())
|
||||
throw new ValidationException("Field SuppliesId is empty");
|
||||
if (!SuppliesId.IsGuid())
|
||||
throw new ValidationException("The value in the field SuppliesId is not a unique identifier");
|
||||
if (TourId.IsEmpty())
|
||||
throw new ValidationException("Field TourId is empty");
|
||||
if (!TourId.IsGuid())
|
||||
throw new ValidationException("The value in the field BlandId is not a unique identifier");
|
||||
if (Count <= 0)
|
||||
throw new ValidationException("Field Count is less than or equal to 0");
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.Exceptions;
|
||||
|
||||
public class InsufficientException(string message) : Exception(message)
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.Infrastructure;
|
||||
|
||||
public interface IConfigurationSalary
|
||||
{
|
||||
double ExtraSaleSum { get; }
|
||||
|
||||
int MaxConcurrentThreads { get; }
|
||||
}
|
||||
@@ -11,32 +11,41 @@ namespace MagicCarpetContracts.Infrastructure;
|
||||
|
||||
public class OperationResponse
|
||||
{
|
||||
public HttpStatusCode StatusCode { get; set; }
|
||||
protected HttpStatusCode StatusCode { get; set; }
|
||||
|
||||
public object? Result { get; set; }
|
||||
protected object? Result { get; set; }
|
||||
|
||||
protected string? FileName { get; set; }
|
||||
|
||||
public IActionResult GetResponse(HttpRequest request, HttpResponse response)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
ArgumentNullException.ThrowIfNull(response);
|
||||
|
||||
response.StatusCode = (int)StatusCode;
|
||||
|
||||
if (Result is null)
|
||||
{
|
||||
return new StatusCodeResult((int)StatusCode);
|
||||
}
|
||||
|
||||
if (Result is Stream stream)
|
||||
{
|
||||
return new FileStreamResult(stream, "application/octetstream")
|
||||
{
|
||||
FileDownloadName = FileName
|
||||
};
|
||||
}
|
||||
return new ObjectResult(Result);
|
||||
}
|
||||
|
||||
protected static TResult OK<TResult, TData>(TData data) where TResult : OperationResponse,
|
||||
new() => new() { StatusCode = HttpStatusCode.OK, Result = data };
|
||||
|
||||
protected static TResult NoContent<TResult>() where TResult : OperationResponse,
|
||||
protected static TResult OK<TResult, TData>(TData data, string fileName) where TResult : OperationResponse,
|
||||
new() => new() { StatusCode = HttpStatusCode.OK, Result = data, FileName = fileName };
|
||||
|
||||
protected static TResult NoContent<TResult>() where TResult : OperationResponse,
|
||||
new() => new() { StatusCode = HttpStatusCode.NoContent };
|
||||
|
||||
protected static TResult BadRequest<TResult>(string? errorMessage = null) where TResult : OperationResponse,
|
||||
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,
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.Infrastructure.PostConfigurations;
|
||||
|
||||
public class ChiefPostConfiguration : PostConfiguration
|
||||
{
|
||||
public override string Type => nameof(ChiefPostConfiguration);
|
||||
public double PersonalCountTrendPremium { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.Infrastructure.PostConfigurations;
|
||||
|
||||
public class PostConfiguration
|
||||
{
|
||||
public virtual string Type => nameof(PostConfiguration);
|
||||
public double Rate { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.Infrastructure.PostConfigurations;
|
||||
|
||||
public class TravelAgentPostConfiguration : PostConfiguration
|
||||
{
|
||||
public override string Type => nameof(TravelAgentPostConfiguration);
|
||||
public double SalePercent { get; set; }
|
||||
public double BonusForExtraSales { get; set; }
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.StoragesContracts;
|
||||
|
||||
public interface IAgencyStorageContract
|
||||
{
|
||||
List<AgencyDataModel> GetList();
|
||||
AgencyDataModel GetElementById(string id);
|
||||
void AddElement(AgencyDataModel agencyDataModel);
|
||||
void UpdElement(AgencyDataModel agencyDataModel);
|
||||
void DelElement(string id);
|
||||
bool CheckComponents(SaleDataModel saleDataModel);
|
||||
}
|
||||
@@ -23,4 +23,6 @@ public interface IEmployeeStorageContract
|
||||
void UpdElement(EmployeeDataModel employeeDataModel);
|
||||
|
||||
void DelElement(string id);
|
||||
|
||||
int GetEmployeeTrend(DateTime fromPeriod, DateTime toPeriod);
|
||||
}
|
||||
|
||||
@@ -11,5 +11,7 @@ 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);
|
||||
}
|
||||
|
||||
@@ -12,6 +12,8 @@ public interface ISaleStorageContract
|
||||
List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? employeeId = null,
|
||||
string? clientId = null, string? tourId = null);
|
||||
|
||||
Task<List<SaleDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct);
|
||||
|
||||
SaleDataModel? GetElementById(string id);
|
||||
|
||||
void AddElement(SaleDataModel saleDataModel);
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.StoragesContracts;
|
||||
|
||||
public interface ISuppliesStorageContract
|
||||
{
|
||||
List<SuppliesDataModel> GetList(DateTime? startDate = null);
|
||||
SuppliesDataModel GetElementById(string id);
|
||||
void AddElement(SuppliesDataModel suppliesDataModel);
|
||||
void UpdElement(SuppliesDataModel suppliesDataModel);
|
||||
}
|
||||
@@ -11,6 +11,7 @@ public interface ITourStorageContract
|
||||
{
|
||||
List<TourDataModel> GetList();
|
||||
List<TourHistoryDataModel> GetHistoryByTourId(string tourId);
|
||||
Task<List<TourHistoryDataModel>> GetHistoriesListAsync(CancellationToken ct);
|
||||
TourDataModel? GetElementById(string id);
|
||||
TourDataModel? GetElementByName(string name);
|
||||
void AddElement(TourDataModel tourDataModel);
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
using MagicCarpetContracts.Enums;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.ViewModels;
|
||||
|
||||
public class AgencyViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
public required TourType TourType { get; set; }
|
||||
public required int Count { get; set; }
|
||||
public required List<TourAgencyViewModel> Tours { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.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; }
|
||||
}
|
||||
@@ -14,5 +14,5 @@ public class PostViewModel
|
||||
|
||||
public required string PostType { get; set; }
|
||||
|
||||
public double Salary { get; set; }
|
||||
public required string Configuration { get; set; }
|
||||
}
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
using MagicCarpetContracts.Enums;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.ViewModels;
|
||||
|
||||
public class SuppliesViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
public required TourType TourType { get; set; }
|
||||
public DateTime ProductuionDate { get; set; }
|
||||
public int Count { get; set; }
|
||||
public required List<TourSuppliesViewModel> Tours { get; set; }
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.ViewModels;
|
||||
|
||||
public class TourAgencyViewModel
|
||||
{
|
||||
public required string AgencyId { get; set; }
|
||||
public required string TourId { get; set; }
|
||||
public int Count { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.ViewModels;
|
||||
|
||||
public class TourAndTourHistoryViewModel
|
||||
{
|
||||
public required string TourName { get; set; }
|
||||
public required List<string> Histories { get; set; }
|
||||
public required List<string> Data { get; set; }
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetContracts.ViewModels;
|
||||
|
||||
public class TourSuppliesViewModel
|
||||
{
|
||||
public required string SuppliesId { get; set; }
|
||||
public required string TourId { get; set; }
|
||||
public int Count { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using MagicCarpetContracts.Infrastructure;
|
||||
|
||||
namespace MagicCarpetDatabase;
|
||||
|
||||
class DefaultConfigurationDatabase : IConfigurationDatabase
|
||||
{
|
||||
public string ConnectionString => "";
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
using AutoMapper;
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using MagicCarpetContracts.Exceptions;
|
||||
using MagicCarpetContracts.StoragesContracts;
|
||||
using MagicCarpetDatabase.Models;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetDatabase.Implementations;
|
||||
|
||||
public class AgencyStorageContract : IAgencyStorageContract
|
||||
{
|
||||
private readonly MagicCarpetDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public AgencyStorageContract(MagicCarpetDbContext dbContext)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.AddMaps(typeof(TourAgency));
|
||||
cfg.AddMaps(typeof(Agency));
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<AgencyDataModel> GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return [.. _dbContext.Agencies.Select(x => _mapper.Map<AgencyDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public AgencyDataModel GetElementById(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<AgencyDataModel>(GetAgencyById(id));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddElement(AgencyDataModel agencyDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_dbContext.Agencies.Add(_mapper.Map<Agency>(agencyDataModel));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdElement(AgencyDataModel agencyDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
var element = GetAgencyById(agencyDataModel.Id) ?? throw new ElementNotFoundException(agencyDataModel.Id);
|
||||
_dbContext.Agencies.Update(_mapper.Map(agencyDataModel, element));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (ElementNotFoundException)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void DelElement(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var element = GetAgencyById(id) ?? throw new ElementNotFoundException(id);
|
||||
_dbContext.Agencies.Remove(element);
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (ElementNotFoundException)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public bool CheckComponents(SaleDataModel saleDataModel)
|
||||
{
|
||||
using (var transaction = _dbContext.Database.BeginTransaction())
|
||||
{
|
||||
foreach (SaleTourDataModel sale_tour in saleDataModel.Tours)
|
||||
{
|
||||
var tour = _dbContext.Tours.FirstOrDefault(x => x.Id == sale_tour.TourId);
|
||||
var agency = _dbContext.Agencies.FirstOrDefault(x => x.TourType == tour.TourType && x.Count >= sale_tour.Count);
|
||||
|
||||
if (agency == null)
|
||||
{
|
||||
transaction.Rollback();
|
||||
return false;
|
||||
}
|
||||
if (agency.Count - sale_tour.Count == 0)
|
||||
{
|
||||
DelElement(agency.Id);
|
||||
}
|
||||
else
|
||||
{
|
||||
agency.Count -= sale_tour.Count;
|
||||
}
|
||||
}
|
||||
transaction.Commit();
|
||||
_dbContext.SaveChanges();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private Agency? GetAgencyById(string id) => _dbContext.Agencies.FirstOrDefault(x => x.Id == id);
|
||||
}
|
||||
@@ -157,6 +157,21 @@ public class EmployeeStorageContract : IEmployeeStorageContract
|
||||
}
|
||||
}
|
||||
|
||||
public int GetEmployeeTrend(DateTime fromPeriod, DateTime toPeriod)
|
||||
{
|
||||
try
|
||||
{
|
||||
var countWorkersOnBegining = _dbContext.Employees.Count(x => x.EmploymentDate < fromPeriod && (!x.IsDeleted || x.DateOfDelete > fromPeriod));
|
||||
var countWorkersOnEnding = _dbContext.Employees.Count(x => x.EmploymentDate < toPeriod && (!x.IsDeleted || x.DateOfDelete > toPeriod));
|
||||
return countWorkersOnEnding - countWorkersOnBegining;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private Employee? GetEmployeeById(string id) => AddPost(_dbContext.Employees.FirstOrDefault(x => x.Id == id && !x.IsDeleted));
|
||||
|
||||
private IQueryable<Employee> JoinPost(IQueryable<Employee> query)
|
||||
|
||||
@@ -29,7 +29,9 @@ public class PostStorageContract : IPostStorageContract
|
||||
.ForMember(x => x.Id, x => x.Ignore())
|
||||
.ForMember(x => x.PostId, x => x.MapFrom(src => src.Id))
|
||||
.ForMember(x => x.IsActual, x => x.MapFrom(src => true))
|
||||
.ForMember(x => x.ChangeDate, x => x.MapFrom(src => DateTime.UtcNow));
|
||||
.ForMember(x => x.ChangeDate, x => x.MapFrom(src => DateTime.UtcNow))
|
||||
.ForMember(x => x.Configuration, x => x.MapFrom(src =>
|
||||
src.ConfigurationModel));
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
@@ -50,6 +50,22 @@ public class SalaryStorageContract : ISalaryStorageContract
|
||||
}
|
||||
}
|
||||
|
||||
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 => _mapper.Map<SalaryDataModel>(x)).ToListAsync(ct)];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddElement(SalaryDataModel salaryDataModel)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -68,6 +68,27 @@ public class SaleStorageContract : ISaleStorageContract
|
||||
}
|
||||
}
|
||||
|
||||
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.SaleTours)!
|
||||
.ThenInclude(sc => sc.Tour)
|
||||
.Where(x => x.SaleDate >= DateTime.SpecifyKind(startDate, DateTimeKind.Utc)
|
||||
&& x.SaleDate < DateTime.SpecifyKind(endDate, DateTimeKind.Utc))
|
||||
.Select(x => _mapper.Map<SaleDataModel>(x))
|
||||
.ToListAsync(ct)];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public SaleDataModel? GetElementById(string id)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -1,100 +0,0 @@
|
||||
using AutoMapper;
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using MagicCarpetContracts.Exceptions;
|
||||
using MagicCarpetContracts.StoragesContracts;
|
||||
using MagicCarpetDatabase.Models;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetDatabase.Implementations;
|
||||
|
||||
public class SuppliesStorageContract : ISuppliesStorageContract
|
||||
{
|
||||
private readonly MagicCarpetDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public SuppliesStorageContract(MagicCarpetDbContext dbContext)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Supplies, SuppliesDataModel>()
|
||||
.ConstructUsing(src => new SuppliesDataModel(
|
||||
src.Id,
|
||||
src.Type,
|
||||
src.ProductuionDate,
|
||||
src.Count,
|
||||
_mapper.Map<List<TourSuppliesDataModel>>(src.Tours)
|
||||
));
|
||||
|
||||
cfg.CreateMap<SuppliesDataModel, Supplies>();
|
||||
cfg.CreateMap<TourSuppliesDataModel, TourSupplies>().ReverseMap();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<SuppliesDataModel> GetList(DateTime? startDate = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
return [.. _dbContext.Supplieses.Select(x => _mapper.Map<SuppliesDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public SuppliesDataModel GetElementById(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<SuppliesDataModel>(GetSuppliesById(id));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddElement(SuppliesDataModel suppliesDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_dbContext.Supplieses.Add(_mapper.Map<Supplies>(suppliesDataModel));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdElement(SuppliesDataModel suppliesDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
var element = GetSuppliesById(suppliesDataModel.Id) ?? throw new ElementNotFoundException(suppliesDataModel.Id);
|
||||
_dbContext.Supplieses.Update(_mapper.Map(suppliesDataModel, element));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (ElementNotFoundException)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private Supplies? GetSuppliesById(string id) => _dbContext.Supplieses.FirstOrDefault(x => x.Id == id);
|
||||
}
|
||||
@@ -7,7 +7,6 @@ using Microsoft.EntityFrameworkCore;
|
||||
using Npgsql;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
@@ -26,7 +25,7 @@ public class TourStorageContract : ITourStorageContract
|
||||
{
|
||||
cfg.CreateMap<Tour, TourDataModel>();
|
||||
cfg.CreateMap<TourDataModel, Tour>();
|
||||
cfg.CreateMap<TourHistory, TourHistoryDataModel>(); ;
|
||||
cfg.CreateMap<TourHistory, TourHistoryDataModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
@@ -57,6 +56,19 @@ public class TourStorageContract : ITourStorageContract
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<List<TourHistoryDataModel>> GetHistoriesListAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return [.. await _dbContext.TourHistories.Include(x => x.Tour).Select(x => _mapper.Map<TourHistoryDataModel>(x)).ToListAsync(ct)];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public TourDataModel? GetElementById(string id)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -8,7 +8,12 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoMapper" Version="14.0.0" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.2" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.3" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.3">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.3" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
using MagicCarpetContracts.Infrastructure;
|
||||
using MagicCarpetContracts.Infrastructure.PostConfigurations;
|
||||
using MagicCarpetDatabase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@@ -44,9 +47,12 @@ public class MagicCarpetDbContext(IConfigurationDatabase configurationDatabase)
|
||||
|
||||
modelBuilder.Entity<SaleTour>().HasKey(x => new { x.SaleId, x.TourId });
|
||||
|
||||
modelBuilder.Entity<TourSupplies>().HasKey(x => new { x.SuppliesId, x.TourId });
|
||||
|
||||
modelBuilder.Entity<TourAgency>().HasKey(x => new { x.AgencyId, x.TourId });
|
||||
modelBuilder.Entity<Post>()
|
||||
.Property(x => x.Configuration)
|
||||
.HasColumnType("jsonb")
|
||||
.HasConversion(
|
||||
x => SerializePostConfiguration(x),
|
||||
x => DeserialzePostConfiguration(x));
|
||||
}
|
||||
|
||||
public DbSet<Client> Clients { get; set; }
|
||||
@@ -64,8 +70,12 @@ public class MagicCarpetDbContext(IConfigurationDatabase configurationDatabase)
|
||||
public DbSet<SaleTour> SaleTours { get; set; }
|
||||
|
||||
public DbSet<Employee> Employees { get; set; }
|
||||
public DbSet<Supplies> Supplieses { get; set; }
|
||||
public DbSet<Agency> Agencies { get; set; }
|
||||
public DbSet<TourSupplies> TourSupplieses { get; set; }
|
||||
public DbSet<TourAgency> TourAgensies { get; set; }
|
||||
|
||||
private static string SerializePostConfiguration(PostConfiguration postConfiguration) => JsonConvert.SerializeObject(postConfiguration);
|
||||
private static PostConfiguration DeserialzePostConfiguration(string jsonString) => JToken.Parse(jsonString).Value<string>("Type") switch
|
||||
{
|
||||
nameof(TravelAgentPostConfiguration) => JsonConvert.DeserializeObject<TravelAgentPostConfiguration>(jsonString)!,
|
||||
nameof(ChiefPostConfiguration) => JsonConvert.DeserializeObject<ChiefPostConfiguration>(jsonString)!,
|
||||
_ => JsonConvert.DeserializeObject<PostConfiguration>(jsonString)!,
|
||||
};
|
||||
}
|
||||
|
||||
333
MagicCarpetProject/MagicCarpetDatabase/Migrations/20250408110058_FirstMigration.Designer.cs
generated
Normal file
333
MagicCarpetProject/MagicCarpetDatabase/Migrations/20250408110058_FirstMigration.Designer.cs
generated
Normal file
@@ -0,0 +1,333 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using MagicCarpetDatabase;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace MagicCarpetDatabase.Migrations
|
||||
{
|
||||
[DbContext(typeof(MagicCarpetDbContext))]
|
||||
[Migration("20250408110058_FirstMigration")]
|
||||
partial class FirstMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "9.0.3")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Client", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<double>("DiscountSize")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<string>("FIO")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PhoneNumber")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PhoneNumber")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Clients");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Employee", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("BirthDate")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Email")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("EmploymentDate")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("FIO")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("IsDeleted")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("PostId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Employees");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Post", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("ChangeDate")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<bool>("IsActual")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("PostId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PostName")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("PostType")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<double>("Salary")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PostId", "IsActual")
|
||||
.IsUnique()
|
||||
.HasFilter("\"IsActual\" = TRUE");
|
||||
|
||||
b.HasIndex("PostName", "IsActual")
|
||||
.IsUnique()
|
||||
.HasFilter("\"IsActual\" = TRUE");
|
||||
|
||||
b.ToTable("Posts");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Salary", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("EmployeeId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<double>("EmployeeSalary")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<DateTime>("SalaryDate")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("EmployeeId");
|
||||
|
||||
b.ToTable("Salaries");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Sale", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ClientId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<double>("Discount")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<int>("DiscountType")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("EmployeeId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("IsCancel")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<DateTime>("SaleDate")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<double>("Sum")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ClientId");
|
||||
|
||||
b.HasIndex("EmployeeId");
|
||||
|
||||
b.ToTable("Sales");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.SaleTour", b =>
|
||||
{
|
||||
b.Property<string>("SaleId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("TourId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Count")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<double>("Price")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.HasKey("SaleId", "TourId");
|
||||
|
||||
b.HasIndex("TourId");
|
||||
|
||||
b.ToTable("SaleTours");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Tour", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<double>("Price")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<string>("TourCountry")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("TourName")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("TourType")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("TourName")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Tours");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.TourHistory", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("ChangeDate")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<double>("OldPrice")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<string>("TourId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("TourId");
|
||||
|
||||
b.ToTable("TourHistories");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Salary", b =>
|
||||
{
|
||||
b.HasOne("MagicCarpetDatabase.Models.Employee", "Employee")
|
||||
.WithMany("Salaries")
|
||||
.HasForeignKey("EmployeeId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Employee");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Sale", b =>
|
||||
{
|
||||
b.HasOne("MagicCarpetDatabase.Models.Client", "Client")
|
||||
.WithMany("Sales")
|
||||
.HasForeignKey("ClientId")
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
b.HasOne("MagicCarpetDatabase.Models.Employee", "Employee")
|
||||
.WithMany("Sales")
|
||||
.HasForeignKey("EmployeeId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Client");
|
||||
|
||||
b.Navigation("Employee");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.SaleTour", b =>
|
||||
{
|
||||
b.HasOne("MagicCarpetDatabase.Models.Sale", "Sale")
|
||||
.WithMany("SaleTours")
|
||||
.HasForeignKey("SaleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("MagicCarpetDatabase.Models.Tour", "Tour")
|
||||
.WithMany("SaleTours")
|
||||
.HasForeignKey("TourId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Sale");
|
||||
|
||||
b.Navigation("Tour");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.TourHistory", b =>
|
||||
{
|
||||
b.HasOne("MagicCarpetDatabase.Models.Tour", "Tour")
|
||||
.WithMany("TourHistories")
|
||||
.HasForeignKey("TourId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Tour");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Client", b =>
|
||||
{
|
||||
b.Navigation("Sales");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Employee", b =>
|
||||
{
|
||||
b.Navigation("Salaries");
|
||||
|
||||
b.Navigation("Sales");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Sale", b =>
|
||||
{
|
||||
b.Navigation("SaleTours");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Tour", b =>
|
||||
{
|
||||
b.Navigation("SaleTours");
|
||||
|
||||
b.Navigation("TourHistories");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace MagicCarpetDatabase.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class FirstMigration : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Clients",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<string>(type: "text", nullable: false),
|
||||
FIO = table.Column<string>(type: "text", nullable: false),
|
||||
PhoneNumber = table.Column<string>(type: "text", nullable: false),
|
||||
DiscountSize = table.Column<double>(type: "double precision", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Clients", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Employees",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<string>(type: "text", nullable: false),
|
||||
FIO = table.Column<string>(type: "text", nullable: false),
|
||||
Email = table.Column<string>(type: "text", nullable: false),
|
||||
PostId = table.Column<string>(type: "text", nullable: false),
|
||||
BirthDate = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
|
||||
EmploymentDate = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
|
||||
IsDeleted = table.Column<bool>(type: "boolean", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Employees", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Posts",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<string>(type: "text", nullable: false),
|
||||
PostId = table.Column<string>(type: "text", nullable: false),
|
||||
PostName = table.Column<string>(type: "text", nullable: false),
|
||||
PostType = table.Column<int>(type: "integer", nullable: false),
|
||||
Salary = table.Column<double>(type: "double precision", nullable: false),
|
||||
IsActual = table.Column<bool>(type: "boolean", nullable: false),
|
||||
ChangeDate = table.Column<DateTime>(type: "timestamp with time zone", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Posts", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Tours",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<string>(type: "text", nullable: false),
|
||||
TourName = table.Column<string>(type: "text", nullable: false),
|
||||
TourCountry = table.Column<string>(type: "text", nullable: true),
|
||||
Price = table.Column<double>(type: "double precision", nullable: false),
|
||||
TourType = table.Column<int>(type: "integer", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Tours", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Salaries",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<string>(type: "text", nullable: false),
|
||||
EmployeeId = table.Column<string>(type: "text", nullable: false),
|
||||
SalaryDate = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
|
||||
EmployeeSalary = table.Column<double>(type: "double precision", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Salaries", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_Salaries_Employees_EmployeeId",
|
||||
column: x => x.EmployeeId,
|
||||
principalTable: "Employees",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Sales",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<string>(type: "text", nullable: false),
|
||||
EmployeeId = table.Column<string>(type: "text", nullable: false),
|
||||
ClientId = table.Column<string>(type: "text", nullable: true),
|
||||
SaleDate = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
|
||||
Sum = table.Column<double>(type: "double precision", nullable: false),
|
||||
DiscountType = table.Column<int>(type: "integer", nullable: false),
|
||||
Discount = table.Column<double>(type: "double precision", nullable: false),
|
||||
IsCancel = table.Column<bool>(type: "boolean", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Sales", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_Sales_Clients_ClientId",
|
||||
column: x => x.ClientId,
|
||||
principalTable: "Clients",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.SetNull);
|
||||
table.ForeignKey(
|
||||
name: "FK_Sales_Employees_EmployeeId",
|
||||
column: x => x.EmployeeId,
|
||||
principalTable: "Employees",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "TourHistories",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<string>(type: "text", nullable: false),
|
||||
TourId = table.Column<string>(type: "text", nullable: false),
|
||||
OldPrice = table.Column<double>(type: "double precision", nullable: false),
|
||||
ChangeDate = table.Column<DateTime>(type: "timestamp with time zone", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_TourHistories", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_TourHistories_Tours_TourId",
|
||||
column: x => x.TourId,
|
||||
principalTable: "Tours",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "SaleTours",
|
||||
columns: table => new
|
||||
{
|
||||
SaleId = table.Column<string>(type: "text", nullable: false),
|
||||
TourId = table.Column<string>(type: "text", nullable: false),
|
||||
Count = table.Column<int>(type: "integer", nullable: false),
|
||||
Price = table.Column<double>(type: "double precision", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_SaleTours", x => new { x.SaleId, x.TourId });
|
||||
table.ForeignKey(
|
||||
name: "FK_SaleTours_Sales_SaleId",
|
||||
column: x => x.SaleId,
|
||||
principalTable: "Sales",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
table.ForeignKey(
|
||||
name: "FK_SaleTours_Tours_TourId",
|
||||
column: x => x.TourId,
|
||||
principalTable: "Tours",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Clients_PhoneNumber",
|
||||
table: "Clients",
|
||||
column: "PhoneNumber",
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Posts_PostId_IsActual",
|
||||
table: "Posts",
|
||||
columns: new[] { "PostId", "IsActual" },
|
||||
unique: true,
|
||||
filter: "\"IsActual\" = TRUE");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Posts_PostName_IsActual",
|
||||
table: "Posts",
|
||||
columns: new[] { "PostName", "IsActual" },
|
||||
unique: true,
|
||||
filter: "\"IsActual\" = TRUE");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Salaries_EmployeeId",
|
||||
table: "Salaries",
|
||||
column: "EmployeeId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Sales_ClientId",
|
||||
table: "Sales",
|
||||
column: "ClientId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Sales_EmployeeId",
|
||||
table: "Sales",
|
||||
column: "EmployeeId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_SaleTours_TourId",
|
||||
table: "SaleTours",
|
||||
column: "TourId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_TourHistories_TourId",
|
||||
table: "TourHistories",
|
||||
column: "TourId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Tours_TourName",
|
||||
table: "Tours",
|
||||
column: "TourName",
|
||||
unique: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "Posts");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Salaries");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "SaleTours");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "TourHistories");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Sales");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Tours");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Clients");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Employees");
|
||||
}
|
||||
}
|
||||
}
|
||||
337
MagicCarpetProject/MagicCarpetDatabase/Migrations/20250410053313_ChangeEmployeeAndPost.Designer.cs
generated
Normal file
337
MagicCarpetProject/MagicCarpetDatabase/Migrations/20250410053313_ChangeEmployeeAndPost.Designer.cs
generated
Normal file
@@ -0,0 +1,337 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using MagicCarpetDatabase;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace MagicCarpetDatabase.Migrations
|
||||
{
|
||||
[DbContext(typeof(MagicCarpetDbContext))]
|
||||
[Migration("20250410053313_ChangeEmployeeAndPost")]
|
||||
partial class ChangeEmployeeAndPost
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "9.0.3")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Client", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<double>("DiscountSize")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<string>("FIO")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PhoneNumber")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PhoneNumber")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Clients");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Employee", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("BirthDate")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<DateTime?>("DateOfDelete")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Email")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("EmploymentDate")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("FIO")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("IsDeleted")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("PostId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Employees");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Post", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("ChangeDate")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Configuration")
|
||||
.IsRequired()
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
b.Property<bool>("IsActual")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("PostId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PostName")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("PostType")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PostId", "IsActual")
|
||||
.IsUnique()
|
||||
.HasFilter("\"IsActual\" = TRUE");
|
||||
|
||||
b.HasIndex("PostName", "IsActual")
|
||||
.IsUnique()
|
||||
.HasFilter("\"IsActual\" = TRUE");
|
||||
|
||||
b.ToTable("Posts");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Salary", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("EmployeeId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<double>("EmployeeSalary")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<DateTime>("SalaryDate")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("EmployeeId");
|
||||
|
||||
b.ToTable("Salaries");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Sale", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ClientId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<double>("Discount")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<int>("DiscountType")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("EmployeeId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("IsCancel")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<DateTime>("SaleDate")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<double>("Sum")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ClientId");
|
||||
|
||||
b.HasIndex("EmployeeId");
|
||||
|
||||
b.ToTable("Sales");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.SaleTour", b =>
|
||||
{
|
||||
b.Property<string>("SaleId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("TourId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Count")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<double>("Price")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.HasKey("SaleId", "TourId");
|
||||
|
||||
b.HasIndex("TourId");
|
||||
|
||||
b.ToTable("SaleTours");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Tour", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<double>("Price")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<string>("TourCountry")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("TourName")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("TourType")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("TourName")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Tours");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.TourHistory", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("ChangeDate")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<double>("OldPrice")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<string>("TourId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("TourId");
|
||||
|
||||
b.ToTable("TourHistories");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Salary", b =>
|
||||
{
|
||||
b.HasOne("MagicCarpetDatabase.Models.Employee", "Employee")
|
||||
.WithMany("Salaries")
|
||||
.HasForeignKey("EmployeeId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Employee");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Sale", b =>
|
||||
{
|
||||
b.HasOne("MagicCarpetDatabase.Models.Client", "Client")
|
||||
.WithMany("Sales")
|
||||
.HasForeignKey("ClientId")
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
b.HasOne("MagicCarpetDatabase.Models.Employee", "Employee")
|
||||
.WithMany("Sales")
|
||||
.HasForeignKey("EmployeeId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Client");
|
||||
|
||||
b.Navigation("Employee");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.SaleTour", b =>
|
||||
{
|
||||
b.HasOne("MagicCarpetDatabase.Models.Sale", "Sale")
|
||||
.WithMany("SaleTours")
|
||||
.HasForeignKey("SaleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("MagicCarpetDatabase.Models.Tour", "Tour")
|
||||
.WithMany("SaleTours")
|
||||
.HasForeignKey("TourId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Sale");
|
||||
|
||||
b.Navigation("Tour");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.TourHistory", b =>
|
||||
{
|
||||
b.HasOne("MagicCarpetDatabase.Models.Tour", "Tour")
|
||||
.WithMany("TourHistories")
|
||||
.HasForeignKey("TourId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Tour");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Client", b =>
|
||||
{
|
||||
b.Navigation("Sales");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Employee", b =>
|
||||
{
|
||||
b.Navigation("Salaries");
|
||||
|
||||
b.Navigation("Sales");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Sale", b =>
|
||||
{
|
||||
b.Navigation("SaleTours");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Tour", b =>
|
||||
{
|
||||
b.Navigation("SaleTours");
|
||||
|
||||
b.Navigation("TourHistories");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace MagicCarpetDatabase.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class ChangeEmployeeAndPost : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "Salary",
|
||||
table: "Posts");
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "Configuration",
|
||||
table: "Posts",
|
||||
type: "jsonb",
|
||||
nullable: false,
|
||||
defaultValue: "{\"Rate\": 0, \"Type\": \"PostConfiguration\"}");
|
||||
|
||||
migrationBuilder.AddColumn<DateTime>(
|
||||
name: "DateOfDelete",
|
||||
table: "Employees",
|
||||
type: "timestamp with time zone",
|
||||
nullable: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "Configuration",
|
||||
table: "Posts");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "DateOfDelete",
|
||||
table: "Employees");
|
||||
|
||||
migrationBuilder.AddColumn<double>(
|
||||
name: "Salary",
|
||||
table: "Posts",
|
||||
type: "double precision",
|
||||
nullable: false,
|
||||
defaultValue: 0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using MagicCarpetDatabase;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace MagicCarpetDatabase.Migrations
|
||||
{
|
||||
[DbContext(typeof(MagicCarpetDbContext))]
|
||||
partial class MagicCarpetDbContextModelSnapshot : ModelSnapshot
|
||||
{
|
||||
protected override void BuildModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "9.0.3")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Client", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<double>("DiscountSize")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<string>("FIO")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PhoneNumber")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PhoneNumber")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Clients");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Employee", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("BirthDate")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<DateTime?>("DateOfDelete")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Email")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("EmploymentDate")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("FIO")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("IsDeleted")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("PostId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Employees");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Post", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("ChangeDate")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Configuration")
|
||||
.IsRequired()
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
b.Property<bool>("IsActual")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("PostId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PostName")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("PostType")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PostId", "IsActual")
|
||||
.IsUnique()
|
||||
.HasFilter("\"IsActual\" = TRUE");
|
||||
|
||||
b.HasIndex("PostName", "IsActual")
|
||||
.IsUnique()
|
||||
.HasFilter("\"IsActual\" = TRUE");
|
||||
|
||||
b.ToTable("Posts");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Salary", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("EmployeeId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<double>("EmployeeSalary")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<DateTime>("SalaryDate")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("EmployeeId");
|
||||
|
||||
b.ToTable("Salaries");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Sale", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ClientId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<double>("Discount")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<int>("DiscountType")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("EmployeeId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("IsCancel")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<DateTime>("SaleDate")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<double>("Sum")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ClientId");
|
||||
|
||||
b.HasIndex("EmployeeId");
|
||||
|
||||
b.ToTable("Sales");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.SaleTour", b =>
|
||||
{
|
||||
b.Property<string>("SaleId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("TourId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Count")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<double>("Price")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.HasKey("SaleId", "TourId");
|
||||
|
||||
b.HasIndex("TourId");
|
||||
|
||||
b.ToTable("SaleTours");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Tour", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<double>("Price")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<string>("TourCountry")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("TourName")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("TourType")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("TourName")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Tours");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.TourHistory", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("ChangeDate")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<double>("OldPrice")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<string>("TourId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("TourId");
|
||||
|
||||
b.ToTable("TourHistories");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Salary", b =>
|
||||
{
|
||||
b.HasOne("MagicCarpetDatabase.Models.Employee", "Employee")
|
||||
.WithMany("Salaries")
|
||||
.HasForeignKey("EmployeeId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Employee");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Sale", b =>
|
||||
{
|
||||
b.HasOne("MagicCarpetDatabase.Models.Client", "Client")
|
||||
.WithMany("Sales")
|
||||
.HasForeignKey("ClientId")
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
b.HasOne("MagicCarpetDatabase.Models.Employee", "Employee")
|
||||
.WithMany("Sales")
|
||||
.HasForeignKey("EmployeeId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Client");
|
||||
|
||||
b.Navigation("Employee");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.SaleTour", b =>
|
||||
{
|
||||
b.HasOne("MagicCarpetDatabase.Models.Sale", "Sale")
|
||||
.WithMany("SaleTours")
|
||||
.HasForeignKey("SaleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("MagicCarpetDatabase.Models.Tour", "Tour")
|
||||
.WithMany("SaleTours")
|
||||
.HasForeignKey("TourId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Sale");
|
||||
|
||||
b.Navigation("Tour");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.TourHistory", b =>
|
||||
{
|
||||
b.HasOne("MagicCarpetDatabase.Models.Tour", "Tour")
|
||||
.WithMany("TourHistories")
|
||||
.HasForeignKey("TourId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Tour");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Client", b =>
|
||||
{
|
||||
b.Navigation("Sales");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Employee", b =>
|
||||
{
|
||||
b.Navigation("Salaries");
|
||||
|
||||
b.Navigation("Sales");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Sale", b =>
|
||||
{
|
||||
b.Navigation("SaleTours");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MagicCarpetDatabase.Models.Tour", b =>
|
||||
{
|
||||
b.Navigation("SaleTours");
|
||||
|
||||
b.Navigation("TourHistories");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
using AutoMapper;
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using MagicCarpetContracts.Enums;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetDatabase.Models;
|
||||
|
||||
[AutoMap(typeof(AgencyDataModel), ReverseMap = true)]
|
||||
public class Agency
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
public required TourType TourType { get; set; }
|
||||
public required int Count { get; set; }
|
||||
|
||||
[ForeignKey("AgencyId")]
|
||||
public List<TourAgency>? Tours { get; set; }
|
||||
}
|
||||
@@ -18,13 +18,15 @@ public class Employee
|
||||
|
||||
public string Email { get; set; }
|
||||
|
||||
public string PostId { get; set; }
|
||||
public required string PostId { get; set; }
|
||||
|
||||
public DateTime BirthDate { get; set; }
|
||||
|
||||
public DateTime EmploymentDate { get; set; }
|
||||
|
||||
public bool IsDeleted { get; set; }
|
||||
|
||||
public DateTime? DateOfDelete { get; set; }
|
||||
[NotMapped]
|
||||
public Post? Post { get; set; }
|
||||
[ForeignKey("EmployeeId")]
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using MagicCarpetContracts.Enums;
|
||||
using MagicCarpetContracts.Infrastructure.PostConfigurations;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
@@ -14,7 +15,7 @@ public class Post
|
||||
public required string PostId { get; set; }
|
||||
public required string PostName { get; set; }
|
||||
public PostType PostType { get; set; }
|
||||
public double Salary { get; set; }
|
||||
public required PostConfiguration Configuration { get; set; }
|
||||
public bool IsActual { get; set; }
|
||||
public DateTime ChangeDate { get; set; }
|
||||
}
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
using AutoMapper;
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using MagicCarpetContracts.Enums;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetDatabase.Models;
|
||||
|
||||
public class Supplies
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
public required TourType Type { get; set; }
|
||||
public DateTime ProductuionDate { get; set; }
|
||||
public required int Count { get; set; }
|
||||
|
||||
[ForeignKey("SuppliesId")]
|
||||
public List<TourSupplies>? Tours { get; set; }
|
||||
}
|
||||
@@ -1,6 +1,4 @@
|
||||
using AutoMapper;
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using MagicCarpetContracts.Enums;
|
||||
using MagicCarpetContracts.Enums;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
@@ -11,7 +9,6 @@ using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetDatabase.Models;
|
||||
|
||||
[AutoMap(typeof(TourDataModel), ReverseMap = true)]
|
||||
public class Tour
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
@@ -23,8 +20,4 @@ public class Tour
|
||||
public List<SaleTour>? SaleTours { get; set; }
|
||||
[ForeignKey("TourId")]
|
||||
public List<TourHistory>? TourHistories { get; set; }
|
||||
[ForeignKey("SuppliesesId")]
|
||||
public List<TourSupplies>? TourSupplies { get; set; }
|
||||
[ForeignKey("AgenciesId")]
|
||||
public List<TourAgency>? TourAgency { get; set; }
|
||||
}
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
using AutoMapper;
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetDatabase.Models;
|
||||
|
||||
[AutoMap(typeof(TourAgencyDataModel), ReverseMap = true)]
|
||||
public class TourAgency
|
||||
{
|
||||
public required string AgencyId { get; set; }
|
||||
public required string TourId { get; set; }
|
||||
public int Count { get; set; }
|
||||
public Agency? Agencies { get; set; }
|
||||
public Tour? Tours { get; set; }
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
using AutoMapper;
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetDatabase.Models;
|
||||
|
||||
[AutoMap(typeof(TourSuppliesDataModel), ReverseMap = true)]
|
||||
public class TourSupplies
|
||||
{
|
||||
public required string SuppliesId { get; set; }
|
||||
public required string TourId { get; set; }
|
||||
public int Count { get; set; }
|
||||
public Supplies? Supplies { get; set; }
|
||||
public Tour? Tours { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using Microsoft.EntityFrameworkCore.Design;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetDatabase;
|
||||
|
||||
public class SampleContextFactory : IDesignTimeDbContextFactory<MagicCarpetDbContext>
|
||||
{
|
||||
public MagicCarpetDbContext CreateDbContext(string[] args)
|
||||
{
|
||||
return new MagicCarpetDbContext(new DefaultConfigurationDatabase());
|
||||
}
|
||||
}
|
||||
@@ -1,296 +0,0 @@
|
||||
using MagicCarpetBusinessLogic.Implementations;
|
||||
using MagicCarpetContracts.BusinessLogicContracts;
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using MagicCarpetContracts.Enums;
|
||||
using MagicCarpetContracts.Exceptions;
|
||||
using MagicCarpetContracts.StoragesContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetTests.BusinessLogicContractsTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class AgencyBusinessLogicContractTests
|
||||
{
|
||||
private IAgencyBusinessLogicContract _warehouseBusinessLogicContract;
|
||||
private Mock<IAgencyStorageContract> _warehouseStorageContract;
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
_warehouseStorageContract = new Mock<IAgencyStorageContract>();
|
||||
_warehouseBusinessLogicContract = new AgencyBusinessLogicContract(_warehouseStorageContract.Object, new Mock<ILogger>().Object);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
_warehouseStorageContract.Reset();
|
||||
}
|
||||
|
||||
public void GetAllSupplies_ReturnListOfRecords_Test()
|
||||
{
|
||||
// Arrange
|
||||
var listOriginal = new List<AgencyDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), TourType.Beach, 1, []),
|
||||
new(Guid.NewGuid().ToString(), TourType.Beach, 1, []),
|
||||
new(Guid.NewGuid().ToString(), TourType.Beach, 1, []),
|
||||
};
|
||||
_warehouseStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
|
||||
// Act
|
||||
var list = _warehouseBusinessLogicContract.GetAllComponents();
|
||||
// Assert
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.EquivalentTo(listOriginal));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllSupplies_ReturnEmptyList_Test()
|
||||
{
|
||||
// Arrange
|
||||
_warehouseStorageContract.Setup(x => x.GetList()).Returns([]);
|
||||
// Act
|
||||
var list = _warehouseBusinessLogicContract.GetAllComponents();
|
||||
// Assert
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(0));
|
||||
_warehouseStorageContract.Verify(x => x.GetList(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllSupplies_ReturnNull_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
_warehouseStorageContract.Setup(x => x.GetList()).Returns((List<AgencyDataModel>)null);
|
||||
// Act & Assert
|
||||
Assert.That(() => _warehouseBusinessLogicContract.GetAllComponents(), Throws.TypeOf<NullListException>());
|
||||
_warehouseStorageContract.Verify(x => x.GetList(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllSupplies_StorageThrowError_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
_warehouseStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
|
||||
// Act & Assert
|
||||
Assert.That(() => _warehouseBusinessLogicContract.GetAllComponents(), Throws.TypeOf<StorageException>());
|
||||
_warehouseStorageContract.Verify(x => x.GetList(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetSuppliesByData_GetById_ReturnRecord_Test()
|
||||
{
|
||||
// Arrange
|
||||
var id = Guid.NewGuid().ToString();
|
||||
var record = new AgencyDataModel(id, TourType.Beach, 1, []);
|
||||
_warehouseStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
|
||||
// Act
|
||||
var element = _warehouseBusinessLogicContract.GetComponentByData(id);
|
||||
// Assert
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.That(element.Id, Is.EqualTo(id));
|
||||
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetComponentsByData_EmptyData_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _warehouseBusinessLogicContract.GetComponentByData(null), Throws.TypeOf<ArgumentNullException>());
|
||||
Assert.That(() => _warehouseBusinessLogicContract.GetComponentByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
|
||||
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetSuppliesByData_GetById_NotFoundRecord_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
_warehouseStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new ElementNotFoundException(""));
|
||||
// Act & Assert
|
||||
Assert.That(() => _warehouseBusinessLogicContract.GetComponentByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetSuppliesByData_StorageThrowError_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
_warehouseStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
// Act & Assert
|
||||
Assert.That(() => _warehouseBusinessLogicContract.GetComponentByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
|
||||
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertSupplies_CorrectRecord_Test()
|
||||
{
|
||||
// Arrange
|
||||
var record = new AgencyDataModel(Guid.NewGuid().ToString(), TourType.Beach, 1,
|
||||
[new TourAgencyDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
|
||||
_warehouseStorageContract.Setup(x => x.AddElement(It.IsAny<AgencyDataModel>()));
|
||||
// Act
|
||||
_warehouseBusinessLogicContract.InsertComponent(record);
|
||||
// Assert
|
||||
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<AgencyDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertSupplies_RecordWithExistsData_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
_warehouseStorageContract.Setup(x => x.AddElement(It.IsAny<AgencyDataModel>())).Throws(new ElementExistsException("Data", "Data"));
|
||||
// Act & Assert
|
||||
Assert.That(() => _warehouseBusinessLogicContract.InsertComponent(new(Guid.NewGuid().ToString(), TourType.Beach, 1,
|
||||
[new TourAgencyDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
|
||||
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<AgencyDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertSupplies_NullRecord_ThrowException_Test()
|
||||
{
|
||||
// Act & Assert
|
||||
Assert.That(() => _warehouseBusinessLogicContract.InsertComponent(null), Throws.TypeOf<ArgumentNullException>());
|
||||
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<AgencyDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertComponents_InvalidRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _warehouseBusinessLogicContract.InsertComponent(new AgencyDataModel("id", TourType.Beach, 1, [])), Throws.TypeOf<ValidationException>());
|
||||
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<AgencyDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertSupplies_StorageThrowError_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
_warehouseStorageContract.Setup(x => x.AddElement(It.IsAny<AgencyDataModel>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
// Act & Assert
|
||||
Assert.That(() => _warehouseBusinessLogicContract.InsertComponent(new(Guid.NewGuid().ToString(), TourType.Beach, 1,
|
||||
[new TourAgencyDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
|
||||
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<AgencyDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UpdateSupplies_CorrectRecord_Test()
|
||||
{
|
||||
// Arrange
|
||||
var record = new AgencyDataModel(Guid.NewGuid().ToString(), TourType.Beach, 1,
|
||||
[new TourAgencyDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
|
||||
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<AgencyDataModel>()));
|
||||
// Act
|
||||
_warehouseBusinessLogicContract.UpdateComponent(record);
|
||||
// Assert
|
||||
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<AgencyDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UpdateSupplies_RecordWithIncorrectData_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<AgencyDataModel>())).Throws(new ElementNotFoundException(""));
|
||||
// Act & Assert
|
||||
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), TourType.Beach, 1,
|
||||
[new TourAgencyDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementNotFoundException>());
|
||||
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<AgencyDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UpdateSupplies_RecordWithExistsData_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<AgencyDataModel>())).Throws(new ElementExistsException("Data", "Data"));
|
||||
// Act & Assert
|
||||
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), TourType.Beach, 1,
|
||||
[new TourAgencyDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
|
||||
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<AgencyDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UpdateSupplies_NullRecord_ThrowException_Test()
|
||||
{
|
||||
// Act & Assert
|
||||
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(null), Throws.TypeOf<ArgumentNullException>());
|
||||
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<AgencyDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UpdateComponents_InvalidRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(new AgencyDataModel(Guid.NewGuid().ToString(), TourType.Beach, 1, [])), Throws.TypeOf<ValidationException>());
|
||||
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<AgencyDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UpdateSupplies_StorageThrowError_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<AgencyDataModel>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
// Act & Assert
|
||||
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), TourType.Beach, 1,
|
||||
[new TourAgencyDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
|
||||
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<AgencyDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeleteComponents_CorrectRecord_Test()
|
||||
{
|
||||
//Arrange
|
||||
var id = Guid.NewGuid().ToString();
|
||||
var flag = false;
|
||||
_warehouseStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
|
||||
//Act
|
||||
_warehouseBusinessLogicContract.DeleteComponent(id);
|
||||
//Assert
|
||||
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once); Assert.That(flag);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeleteComponents_RecordWithIncorrectId_ThrowException_Test()
|
||||
{
|
||||
//Arrange
|
||||
var id = Guid.NewGuid().ToString();
|
||||
_warehouseStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
|
||||
//Act&Assert
|
||||
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent(Guid.NewGuid().ToString()),
|
||||
Throws.TypeOf<ElementNotFoundException>());
|
||||
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeleteComponents_IdIsNullOrEmpty_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent(null), Throws.TypeOf<ArgumentNullException>());
|
||||
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent(string.Empty), Throws.TypeOf<ArgumentNullException>());
|
||||
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeleteComponents_IdIsNotGuid_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent("id"),
|
||||
Throws.TypeOf<ValidationException>());
|
||||
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeleteComponents_StorageThrowError_ThrowException_Test()
|
||||
{
|
||||
//Arrange
|
||||
_warehouseStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent(Guid.NewGuid().ToString()),
|
||||
Throws.TypeOf<StorageException>());
|
||||
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using MagicCarpetContracts.Enums;
|
||||
using MagicCarpetContracts.Exceptions;
|
||||
using MagicCarpetContracts.Infrastructure.PostConfigurations;
|
||||
using MagicCarpetContracts.StoragesContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
@@ -38,9 +39,9 @@ internal class PostBusinessLogicContractTests
|
||||
//Arrange
|
||||
var listOriginal = new List<PostDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(),"name 1", PostType.Manager, 10),
|
||||
new(Guid.NewGuid().ToString(), "name 2", PostType.Manager, 10),
|
||||
new(Guid.NewGuid().ToString(), "name 3", PostType.Manager, 10),
|
||||
new(Guid.NewGuid().ToString(),"name 1", PostType.TravelAgent, new PostConfiguration() { Rate = 10 }),
|
||||
new(Guid.NewGuid().ToString(), "name 2", PostType.TravelAgent, new PostConfiguration() { Rate = 10 }),
|
||||
new(Guid.NewGuid().ToString(), "name 3", PostType.TravelAgent, new PostConfiguration() { Rate = 10 }),
|
||||
};
|
||||
_postStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -94,8 +95,8 @@ internal class PostBusinessLogicContractTests
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
var listOriginal = new List<PostDataModel>()
|
||||
{
|
||||
new(postId, "name 1", PostType.Manager, 10),
|
||||
new(postId, "name 2", PostType.Manager, 10)
|
||||
new(postId, "name 1", PostType.TravelAgent, new PostConfiguration() { Rate = 10 }),
|
||||
new(postId, "name 2", PostType.TravelAgent, new PostConfiguration() { Rate = 10 })
|
||||
};
|
||||
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -159,7 +160,7 @@ internal class PostBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var id = Guid.NewGuid().ToString();
|
||||
var record = new PostDataModel(id, "name", PostType.Manager, 10);
|
||||
var record = new PostDataModel(id, "name", PostType.TravelAgent, new PostConfiguration() { Rate = 10 });
|
||||
_postStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
|
||||
//Act
|
||||
var element = _postBusinessLogicContract.GetPostByData(id);
|
||||
@@ -174,7 +175,7 @@ internal class PostBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var postName = "name";
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.Manager, 10);
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.TravelAgent, new PostConfiguration() { Rate = 10 });
|
||||
_postStorageContract.Setup(x => x.GetElementByName(postName)).Returns(record);
|
||||
//Act
|
||||
var element = _postBusinessLogicContract.GetPostByData(postName);
|
||||
@@ -230,11 +231,11 @@ internal class PostBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var flag = false;
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 10);
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new PostConfiguration() { Rate = 10 });
|
||||
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>()))
|
||||
.Callback((PostDataModel x) =>
|
||||
{
|
||||
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary;
|
||||
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.ConfigurationModel.Rate == record.ConfigurationModel.Rate;
|
||||
});
|
||||
//Act
|
||||
_postBusinessLogicContract.InsertPost(record);
|
||||
@@ -249,7 +250,7 @@ internal class PostBusinessLogicContractTests
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Manager, 10)), Throws.TypeOf<ElementExistsException>());
|
||||
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementExistsException>());
|
||||
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -265,7 +266,7 @@ internal class PostBusinessLogicContractTests
|
||||
public void InsertPost_InvalidRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Manager, 10)), Throws.TypeOf<ValidationException>());
|
||||
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.TravelAgent, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ValidationException>());
|
||||
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
@@ -275,7 +276,7 @@ internal class PostBusinessLogicContractTests
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Manager, 10)), Throws.TypeOf<StorageException>());
|
||||
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<StorageException>());
|
||||
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -284,11 +285,11 @@ internal class PostBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var flag = false;
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 10);
|
||||
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new PostConfiguration() { Rate = 10 });
|
||||
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>()))
|
||||
.Callback((PostDataModel x) =>
|
||||
{
|
||||
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary;
|
||||
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.ConfigurationModel.Rate == record.ConfigurationModel.Rate;
|
||||
});
|
||||
//Act
|
||||
_postBusinessLogicContract.UpdatePost(record);
|
||||
@@ -303,7 +304,7 @@ internal class PostBusinessLogicContractTests
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementNotFoundException(""));
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Manager, 10)), Throws.TypeOf<ElementNotFoundException>());
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementNotFoundException>());
|
||||
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -313,7 +314,7 @@ internal class PostBusinessLogicContractTests
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.Manager, 10)), Throws.TypeOf<ElementExistsException>());
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.TravelAgent, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementExistsException>());
|
||||
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -329,7 +330,7 @@ internal class PostBusinessLogicContractTests
|
||||
public void UpdatePost_InvalidRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Manager, 10)), Throws.TypeOf<ValidationException>());
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.TravelAgent, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ValidationException>());
|
||||
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
@@ -339,7 +340,7 @@ internal class PostBusinessLogicContractTests
|
||||
//Arrange
|
||||
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Manager, 10)), Throws.TypeOf<StorageException>());
|
||||
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<StorageException>());
|
||||
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,480 @@
|
||||
using MagicCarpetBusinessLogic.Implementations;
|
||||
using MagicCarpetBusinessLogic.OfficePackage;
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using MagicCarpetContracts.Enums;
|
||||
using MagicCarpetContracts.Exceptions;
|
||||
using MagicCarpetContracts.StoragesContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetTests.BusinessLogicContractsTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class ReportContractTests
|
||||
{
|
||||
private ReportContract _reportContract;
|
||||
private Mock<ISaleStorageContract> _saleStorageContract;
|
||||
private Mock<ITourStorageContract> _tourStorageContract;
|
||||
private Mock<ISalaryStorageContract> _salaryStorageContract;
|
||||
private Mock<BaseWordBuilder> _baseWordBuilder;
|
||||
private Mock<BaseExcelBuilder> _baseExcelBuilder;
|
||||
private Mock<BasePdfBuilder> _basePdfBuilder;
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
_saleStorageContract = new Mock<ISaleStorageContract>();
|
||||
_tourStorageContract = new Mock<ITourStorageContract>();
|
||||
_salaryStorageContract = new Mock<ISalaryStorageContract>();
|
||||
_baseWordBuilder = new Mock<BaseWordBuilder>();
|
||||
_baseExcelBuilder = new Mock<BaseExcelBuilder>();
|
||||
_basePdfBuilder = new Mock<BasePdfBuilder>();
|
||||
_reportContract = new ReportContract(_tourStorageContract.Object, _salaryStorageContract.Object, _saleStorageContract.Object,
|
||||
_baseWordBuilder.Object, _baseExcelBuilder.Object, _basePdfBuilder.Object, new Mock<ILogger>().Object);
|
||||
}
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_saleStorageContract.Reset();
|
||||
_salaryStorageContract.Reset();
|
||||
_tourStorageContract.Reset();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetDataHistoriesByTour_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var TourId1 = Guid.NewGuid().ToString();
|
||||
var TourId2 = Guid.NewGuid().ToString();
|
||||
|
||||
var Tour1 = new TourDataModel(TourId1, "name1","test1", 10.5, TourType.Beach);
|
||||
var Tour2 = new TourDataModel(TourId1, "name2", "test1", 10.5, TourType.Beach);
|
||||
|
||||
_tourStorageContract.Setup(x => x.GetHistoriesListAsync(It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.FromResult(new List<TourHistoryDataModel>()
|
||||
{
|
||||
new(TourId1, 22, DateTime.UtcNow, Tour1),
|
||||
new(TourId2, 21, DateTime.UtcNow, Tour2),
|
||||
new(TourId1, 33, DateTime.UtcNow, Tour1),
|
||||
new(TourId1, 32, DateTime.UtcNow, Tour1),
|
||||
new(TourId2, 65, DateTime.UtcNow, Tour2)
|
||||
}));
|
||||
|
||||
//Act
|
||||
var data = await _reportContract.GetDataToursHistoryAsync(CancellationToken.None);
|
||||
|
||||
//Assert
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data.First(x => x.TourName == Tour1.TourName).Histories, Has.Count.EqualTo(3));
|
||||
Assert.That(data.First(x => x.TourName == Tour2.TourName).Histories, Has.Count.EqualTo(2));
|
||||
});
|
||||
_tourStorageContract.Verify(x => x.GetHistoriesListAsync(It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetDataHistoriesByTour_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
_tourStorageContract.Setup(x =>
|
||||
x.GetHistoriesListAsync(It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new List<TourHistoryDataModel>());
|
||||
|
||||
//Act
|
||||
var data = await _reportContract.GetDataToursHistoryAsync(CancellationToken.None);
|
||||
|
||||
//Assert
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
_tourStorageContract.Verify(x =>
|
||||
x.GetHistoriesListAsync(It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetDataHistoriesByTour_WhenStorageThrowError_ShouldFail_Test()
|
||||
{
|
||||
//Arrange
|
||||
_tourStorageContract.Setup(x =>
|
||||
x.GetHistoriesListAsync(It.IsAny<CancellationToken>()))
|
||||
.ThrowsAsync(new StorageException(new InvalidOperationException()));
|
||||
|
||||
//Act & Assert
|
||||
Assert.That(async () => await
|
||||
_reportContract.GetDataToursHistoryAsync(CancellationToken.None),
|
||||
Throws.TypeOf<StorageException>());
|
||||
|
||||
_tourStorageContract.Verify(x =>
|
||||
x.GetHistoriesListAsync(It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CreateDocumentHistoriesByTour_ShouldSuccess_Test()
|
||||
{
|
||||
// Arrange
|
||||
var TourId1 = Guid.NewGuid().ToString();
|
||||
var TourId2 = Guid.NewGuid().ToString();
|
||||
|
||||
var Tour1 = new TourDataModel(TourId1, "name1","test1", 10.5, TourType.Beach);
|
||||
var Tour2 = new TourDataModel(TourId1, "name2","test1", 10.5, TourType.Beach);
|
||||
|
||||
var histories = new List<TourHistoryDataModel>()
|
||||
{
|
||||
new(TourId1, 22, DateTime.UtcNow, Tour1),
|
||||
new(TourId1, 33, DateTime.UtcNow, Tour1),
|
||||
new(TourId1, 32, DateTime.UtcNow, Tour1),
|
||||
new(TourId2, 21, DateTime.UtcNow, Tour2),
|
||||
new(TourId2, 65, DateTime.UtcNow, Tour2)
|
||||
};
|
||||
|
||||
_tourStorageContract.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.CreateDocumentToursHistoryAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
_tourStorageContract.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(() =>
|
||||
{
|
||||
// 1 заголовок + 2 тура (name1 и name2) + 5 записей истории
|
||||
Assert.That(countRows, Is.EqualTo(8));
|
||||
|
||||
Assert.That(firstRow, Has.Length.EqualTo(3));
|
||||
Assert.That(secondRow, Has.Length.EqualTo(3));
|
||||
|
||||
Assert.That(firstRow[0], Is.EqualTo("Название тура"));
|
||||
Assert.That(firstRow[1], Is.EqualTo("Старая цена"));
|
||||
|
||||
Assert.That(secondRow[0], Is.EqualTo("name1"));
|
||||
Assert.That(secondRow[1], Is.EqualTo(""));
|
||||
});
|
||||
}
|
||||
|
||||
[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 SaleTourDataModel("",
|
||||
Guid.NewGuid().ToString(), 10, 10)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.None, false, [new SaleTourDataModel("",
|
||||
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()));
|
||||
//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 Tour1 = new TourDataModel(Guid.NewGuid().ToString(), "name 1","test1", 10.5, TourType.Beach);
|
||||
var Tour2 = new TourDataModel(Guid.NewGuid().ToString(), "name 2","test1", 10.5, TourType.Beach);
|
||||
_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 SaleTourDataModel("", Tour1.Id, 10, 10, Tour1), new SaleTourDataModel("", Tour2.Id, 10, 10, Tour2)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.RegularCustomer, false, [new SaleTourDataModel("", Tour2.Id, 10, 10, Tour2)])
|
||||
}));
|
||||
_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));
|
||||
});
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(firstRow[0], Is.EqualTo("Сотрудник"));
|
||||
Assert.That(firstRow[1], Is.EqualTo("Дата"));
|
||||
Assert.That(firstRow[2], Is.EqualTo("Сумма"));
|
||||
Assert.That(firstRow[3], Is.EqualTo("Скидка"));
|
||||
Assert.That(firstRow[4], Is.EqualTo("Товар"));
|
||||
Assert.That(firstRow[5], Is.EqualTo("Кол-во"));
|
||||
});
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(secondRow[0], Is.Empty);
|
||||
Assert.That(secondRow[1], Is.Not.Empty);
|
||||
Assert.That(secondRow[2], Is.EqualTo(200.ToString("N2")));
|
||||
Assert.That(secondRow[3], Is.EqualTo(100.ToString("N2")));
|
||||
Assert.That(secondRow[4], Is.Empty);
|
||||
Assert.That(secondRow[5], Is.Empty);
|
||||
});
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(thirdRow[0], Is.Empty);
|
||||
Assert.That(thirdRow[1], Is.Empty);
|
||||
Assert.That(thirdRow[2], Is.Empty);
|
||||
Assert.That(thirdRow[3], Is.Empty);
|
||||
Assert.That(thirdRow[4], Is.EqualTo(Tour1.TourName));
|
||||
Assert.That(thirdRow[5], Is.EqualTo(10.ToString("N2")));
|
||||
});
|
||||
_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()));
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,9 @@
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using MagicCarpetContracts.Enums;
|
||||
using MagicCarpetContracts.Exceptions;
|
||||
using MagicCarpetContracts.Infrastructure.PostConfigurations;
|
||||
using MagicCarpetContracts.StoragesContracts;
|
||||
using MagicCarpetTests.Infrastructure;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
using System;
|
||||
@@ -10,6 +12,7 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using static System.Runtime.InteropServices.JavaScript.JSType;
|
||||
|
||||
namespace MagicCarpetTests.BusinessLogicContractsTests;
|
||||
|
||||
@@ -21,6 +24,7 @@ internal class SalaryBusinessLogicContractTests
|
||||
private Mock<ISaleStorageContract> _saleStorageContract;
|
||||
private Mock<IPostStorageContract> _postStorageContract;
|
||||
private Mock<IEmployeeStorageContract> _employeeStorageContract;
|
||||
private readonly ConfigurationSalaryTest _salaryConfigurationTest = new();
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
@@ -30,7 +34,7 @@ internal class SalaryBusinessLogicContractTests
|
||||
_postStorageContract = new Mock<IPostStorageContract>();
|
||||
_employeeStorageContract = new Mock<IEmployeeStorageContract>();
|
||||
_salaryBusinessLogicContract = new SalaryBusinessLogicContract(_salaryStorageContract.Object,
|
||||
_saleStorageContract.Object, _postStorageContract.Object, _employeeStorageContract.Object, new Mock<ILogger>().Object);
|
||||
_saleStorageContract.Object, _postStorageContract.Object, _employeeStorageContract.Object, new Mock<ILogger>().Object, _salaryConfigurationTest);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
@@ -191,16 +195,14 @@ internal class SalaryBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var employeeId = Guid.NewGuid().ToString();
|
||||
var saleSum = 1.2 * 5;
|
||||
var postSalary = 2000.0;
|
||||
var rate = 2000.0;
|
||||
_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, [new SaleTourDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, postSalary));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new PostConfiguration() { Rate = rate }));
|
||||
_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", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
.Returns([new EmployeeDataModel(employeeId, "Test", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
var sum = 0.0;
|
||||
var expectedSum = postSalary + saleSum * 0.1;
|
||||
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
|
||||
.Callback((SalaryDataModel x) =>
|
||||
{
|
||||
@@ -209,7 +211,7 @@ internal class SalaryBusinessLogicContractTests
|
||||
//Act
|
||||
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
|
||||
//Assert
|
||||
Assert.That(sum, Is.EqualTo(expectedSum));
|
||||
Assert.That(sum, Is.EqualTo(rate));
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -220,9 +222,9 @@ internal class SalaryBusinessLogicContractTests
|
||||
var employee2Id = Guid.NewGuid().ToString();
|
||||
var employee3Id = Guid.NewGuid().ToString();
|
||||
var list = new List<EmployeeDataModel>() {
|
||||
new(employee1Id, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
|
||||
new(employee2Id, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
|
||||
new(employee3Id, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)
|
||||
new(employee1Id, "Test", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
|
||||
new(employee2Id, "Test", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
|
||||
new(employee3Id, "Test", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)
|
||||
};
|
||||
_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(), employee1Id, null, DiscountType.None, false, []),
|
||||
@@ -231,7 +233,7 @@ internal class SalaryBusinessLogicContractTests
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), employee3Id, null, DiscountType.None, false, []),
|
||||
new SaleDataModel(Guid.NewGuid().ToString(), employee3Id, null, DiscountType.None, false, [])]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, 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(list);
|
||||
//Act
|
||||
@@ -244,16 +246,15 @@ internal class SalaryBusinessLogicContractTests
|
||||
public void CalculateSalaryByMounth_WithoutSalesByEmployee_Test()
|
||||
{
|
||||
//Arrange
|
||||
var postSalary = 2000.0;
|
||||
var rate = 2000.0;
|
||||
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([]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, postSalary));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new PostConfiguration() { Rate = rate }));
|
||||
_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", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
.Returns([new EmployeeDataModel(employeeId, "Test", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
var sum = 0.0;
|
||||
var expectedSum = postSalary;
|
||||
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
|
||||
.Callback((SalaryDataModel x) =>
|
||||
{
|
||||
@@ -262,7 +263,7 @@ internal class SalaryBusinessLogicContractTests
|
||||
//Act
|
||||
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
|
||||
//Assert
|
||||
Assert.That(sum, Is.EqualTo(expectedSum));
|
||||
Assert.That(sum, Is.EqualTo(rate));
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -271,9 +272,9 @@ internal class SalaryBusinessLogicContractTests
|
||||
//Arrange
|
||||
var employeeId = Guid.NewGuid().ToString();
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, 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", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
.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>());
|
||||
}
|
||||
@@ -299,7 +300,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>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new PostConfiguration() { Rate = 100 }));
|
||||
//Act&Assert
|
||||
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
|
||||
}
|
||||
@@ -312,9 +313,9 @@ internal class SalaryBusinessLogicContractTests
|
||||
_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()));
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, 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", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
.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<StorageException>());
|
||||
}
|
||||
@@ -329,7 +330,7 @@ internal class SalaryBusinessLogicContractTests
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.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", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
|
||||
.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<StorageException>());
|
||||
}
|
||||
@@ -342,10 +343,71 @@ 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>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000));
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, 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()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
|
||||
}
|
||||
[Test]
|
||||
public void CalculateSalaryByMountht_WithTravelAgentPostConfiguration_CalculateSalary_Test()
|
||||
{
|
||||
//Arrange
|
||||
var employeeId = Guid.NewGuid().ToString();
|
||||
var rate = 2000.0;
|
||||
var percent = 0.1;
|
||||
var bonus = 0.5;
|
||||
var sales = new List<SaleDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), employeeId, null, DiscountType.None, false, [new SaleTourDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]),
|
||||
new(Guid.NewGuid().ToString(), employeeId, null, DiscountType.None, false, [new SaleTourDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]),
|
||||
new(Guid.NewGuid().ToString(), employeeId, null, DiscountType.None, false, [new SaleTourDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5000, 12)])
|
||||
};
|
||||
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(sales);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new TravelAgentPostConfiguration() { Rate = rate, SalePercent = percent, BonusForExtraSales = bonus }));
|
||||
_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)]);
|
||||
var sum = 0.0;
|
||||
var expectedSum = rate + percent * (sales.Sum(x => x.Sum) / sales.Count) + sales.Where(x => x.Sum > _salaryConfigurationTest.ExtraSaleSum).Sum(x => x.Sum) * bonus;
|
||||
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
|
||||
.Callback((SalaryDataModel x) =>
|
||||
{
|
||||
sum = x.Salary;
|
||||
});
|
||||
//Act
|
||||
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
|
||||
//Assert
|
||||
Assert.That(sum, Is.EqualTo(expectedSum));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CalculateSalaryByMountht_WithChiefPostConfiguration_CalculateSalary_Test()
|
||||
{
|
||||
//Arrange
|
||||
var employeeId = Guid.NewGuid().ToString();
|
||||
var rate = 2000.0;
|
||||
var trend = 3;
|
||||
var bonus = 100;
|
||||
_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, [new SaleTourDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])]);
|
||||
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
|
||||
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new ChiefPostConfiguration() { Rate = rate, PersonalCountTrendPremium = bonus }));
|
||||
_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)]);
|
||||
_employeeStorageContract.Setup(x => x.GetEmployeeTrend(It.IsAny<DateTime>(), It.IsAny<DateTime>()))
|
||||
.Returns(trend);
|
||||
var sum = 0.0;
|
||||
var expectedSum = rate + trend * bonus;
|
||||
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
|
||||
.Callback((SalaryDataModel x) =>
|
||||
{
|
||||
sum = x.Salary;
|
||||
});
|
||||
//Act
|
||||
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
|
||||
//Assert
|
||||
Assert.That(sum, Is.EqualTo(expectedSum));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,22 +18,18 @@ internal class SaleBusinessLogicContractTests
|
||||
{
|
||||
private SaleBusinessLogicContract _saleBusinessLogicContract;
|
||||
private Mock<ISaleStorageContract> _saleStorageContract;
|
||||
private Mock<IAgencyStorageContract> _agencyStorageContract;
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
_saleStorageContract = new Mock<ISaleStorageContract>();
|
||||
_agencyStorageContract = new Mock<IAgencyStorageContract>();
|
||||
_saleBusinessLogicContract = new SaleBusinessLogicContract(_saleStorageContract.Object,
|
||||
_agencyStorageContract.Object, new Mock<ILogger>().Object);
|
||||
_saleBusinessLogicContract = new SaleBusinessLogicContract(_saleStorageContract.Object, new Mock<ILogger>().Object);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
_saleStorageContract.Reset();
|
||||
_agencyStorageContract.Reset();
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -400,7 +396,6 @@ internal class SaleBusinessLogicContractTests
|
||||
var flag = false;
|
||||
var record = new SaleDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), DiscountType.None,
|
||||
false, [new SaleTourDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]);
|
||||
_agencyStorageContract.Setup(x => x.CheckComponents(It.IsAny<SaleDataModel>())).Returns(true);
|
||||
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>()))
|
||||
.Callback((SaleDataModel x) =>
|
||||
{
|
||||
@@ -414,7 +409,6 @@ internal class SaleBusinessLogicContractTests
|
||||
//Act
|
||||
_saleBusinessLogicContract.InsertSale(record);
|
||||
//Assert
|
||||
_agencyStorageContract.Verify(x => x.CheckComponents(It.IsAny<SaleDataModel>()), Times.Once);
|
||||
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
|
||||
Assert.That(flag);
|
||||
}
|
||||
@@ -423,13 +417,11 @@ internal class SaleBusinessLogicContractTests
|
||||
public void InsertSale_RecordWithExistsData_ThrowException_Test()
|
||||
{
|
||||
//Arrange
|
||||
_agencyStorageContract.Setup(x => x.CheckComponents(It.IsAny<SaleDataModel>())).Returns(true);
|
||||
_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 SaleTourDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])), Throws.TypeOf<ElementExistsException>());
|
||||
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
|
||||
_agencyStorageContract.Verify(x => x.CheckComponents(It.IsAny<SaleDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -452,26 +444,13 @@ internal class SaleBusinessLogicContractTests
|
||||
public void InsertSale_StorageThrowError_ThrowException_Test()
|
||||
{
|
||||
//Arrange
|
||||
_agencyStorageContract.Setup(x => x.CheckComponents(It.IsAny<SaleDataModel>())).Returns(true);
|
||||
_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 SaleTourDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])), Throws.TypeOf<StorageException>());
|
||||
_agencyStorageContract.Verify(x => x.CheckComponents(It.IsAny<SaleDataModel>()), Times.Once);
|
||||
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertSale_InsufficientError_ThrowException_Test()
|
||||
{
|
||||
//Arrange
|
||||
_agencyStorageContract.Setup(x => x.CheckComponents(It.IsAny<SaleDataModel>())).Returns(false);
|
||||
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
|
||||
Guid.NewGuid().ToString(), DiscountType.None, false, [new SaleTourDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])), Throws.TypeOf<InsufficientException>());
|
||||
//Act&Assert
|
||||
_agencyStorageContract.Verify(x => x.CheckComponents(It.IsAny<SaleDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CancelSale_CorrectRecord_Test()
|
||||
{
|
||||
|
||||
@@ -1,242 +0,0 @@
|
||||
using MagicCarpetBusinessLogic.Implementations;
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using MagicCarpetContracts.Enums;
|
||||
using MagicCarpetContracts.Exceptions;
|
||||
using MagicCarpetContracts.StoragesContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetTests.BusinessLogicContractsTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class SuppliesBusinessLogicContractTests
|
||||
{
|
||||
private SuppliesBusinessLogicContract _suppliesBusinessLogicContract;
|
||||
private Mock<ISuppliesStorageContract> _suppliesStorageContract;
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
_suppliesStorageContract = new Mock<ISuppliesStorageContract>();
|
||||
_suppliesBusinessLogicContract = new SuppliesBusinessLogicContract(_suppliesStorageContract.Object, new Mock<ILogger>().Object);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
_suppliesStorageContract.Reset();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllSupplies_ReturnListOfRecords_Test()
|
||||
{
|
||||
// Arrange
|
||||
var listOriginal = new List<SuppliesDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1, []),
|
||||
new(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1, []),
|
||||
new(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1, []),
|
||||
};
|
||||
_suppliesStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>())).Returns(listOriginal);
|
||||
// Act
|
||||
var list = _suppliesBusinessLogicContract.GetAllComponents();
|
||||
// Assert
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.EquivalentTo(listOriginal));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllSupplies_ReturnEmptyList_Test()
|
||||
{
|
||||
// Arrange
|
||||
_suppliesStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>())).Returns([]);
|
||||
// Act
|
||||
var list = _suppliesBusinessLogicContract.GetAllComponents();
|
||||
// Assert
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(0));
|
||||
_suppliesStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllSupplies_ReturnNull_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
_suppliesStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>())).Returns((List<SuppliesDataModel>)null);
|
||||
// Act & Assert
|
||||
Assert.That(() => _suppliesBusinessLogicContract.GetAllComponents(), Throws.TypeOf<NullListException>());
|
||||
_suppliesStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllSupplies_StorageThrowError_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
_suppliesStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
// Act & Assert
|
||||
Assert.That(() => _suppliesBusinessLogicContract.GetAllComponents(), Throws.TypeOf<StorageException>());
|
||||
_suppliesStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetSuppliesByData_GetById_ReturnRecord_Test()
|
||||
{
|
||||
// Arrange
|
||||
var id = Guid.NewGuid().ToString();
|
||||
var record = new SuppliesDataModel(id,TourType.Beach, DateTime.Now, 1, []);
|
||||
_suppliesStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
|
||||
// Act
|
||||
var element = _suppliesBusinessLogicContract.GetComponentByData(id);
|
||||
// Assert
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.That(element.Id, Is.EqualTo(id));
|
||||
_suppliesStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetComponentsByData_EmptyData_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _suppliesBusinessLogicContract.GetComponentByData(null), Throws.TypeOf<ArgumentNullException>());
|
||||
Assert.That(() => _suppliesBusinessLogicContract.GetComponentByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
|
||||
_suppliesStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetSuppliesByData_GetById_NotFoundRecord_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
_suppliesStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new ElementNotFoundException(""));
|
||||
// Act & Assert
|
||||
Assert.That(() => _suppliesBusinessLogicContract.GetComponentByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
_suppliesStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetSuppliesByData_StorageThrowError_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
_suppliesStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
// Act & Assert
|
||||
Assert.That(() => _suppliesBusinessLogicContract.GetComponentByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
|
||||
_suppliesStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertSupplies_CorrectRecord_Test()
|
||||
{
|
||||
// Arrange
|
||||
var record = new SuppliesDataModel(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1,
|
||||
[new TourSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
|
||||
_suppliesStorageContract.Setup(x => x.AddElement(It.IsAny<SuppliesDataModel>()));
|
||||
// Act
|
||||
_suppliesBusinessLogicContract.InsertComponent(record);
|
||||
// Assert
|
||||
_suppliesStorageContract.Verify(x => x.AddElement(It.IsAny<SuppliesDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertSupplies_RecordWithExistsData_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
_suppliesStorageContract.Setup(x => x.AddElement(It.IsAny<SuppliesDataModel>())).Throws(new ElementExistsException("Data", "Data"));
|
||||
// Act & Assert
|
||||
Assert.That(() => _suppliesBusinessLogicContract.InsertComponent(new(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1,
|
||||
[new TourSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
|
||||
_suppliesStorageContract.Verify(x => x.AddElement(It.IsAny<SuppliesDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertSupplies_NullRecord_ThrowException_Test()
|
||||
{
|
||||
// Act & Assert
|
||||
Assert.That(() => _suppliesBusinessLogicContract.InsertComponent(null), Throws.TypeOf<ArgumentNullException>());
|
||||
_suppliesStorageContract.Verify(x => x.AddElement(It.IsAny<SuppliesDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertComponents_InvalidRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _suppliesBusinessLogicContract.InsertComponent(new SuppliesDataModel("id", TourType.Beach, DateTime.UtcNow, 1, [])), Throws.TypeOf<ValidationException>());
|
||||
_suppliesStorageContract.Verify(x => x.AddElement(It.IsAny<SuppliesDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertSupplies_StorageThrowError_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
_suppliesStorageContract.Setup(x => x.AddElement(It.IsAny<SuppliesDataModel>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
// Act & Assert
|
||||
Assert.That(() => _suppliesBusinessLogicContract.InsertComponent(new(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1,
|
||||
[new TourSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
|
||||
_suppliesStorageContract.Verify(x => x.AddElement(It.IsAny<SuppliesDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UpdateSupplies_CorrectRecord_Test()
|
||||
{
|
||||
// Arrange
|
||||
var record = new SuppliesDataModel(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1,
|
||||
[new TourSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
|
||||
_suppliesStorageContract.Setup(x => x.UpdElement(It.IsAny<SuppliesDataModel>()));
|
||||
// Act
|
||||
_suppliesBusinessLogicContract.UpdateComponent(record);
|
||||
// Assert
|
||||
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UpdateSupplies_RecordWithIncorrectData_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
_suppliesStorageContract.Setup(x => x.UpdElement(It.IsAny<SuppliesDataModel>())).Throws(new ElementNotFoundException(""));
|
||||
// Act & Assert
|
||||
Assert.That(() => _suppliesBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1,
|
||||
[new TourSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementNotFoundException>());
|
||||
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UpdateSupplies_RecordWithExistsData_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
_suppliesStorageContract.Setup(x => x.UpdElement(It.IsAny<SuppliesDataModel>())).Throws(new ElementExistsException("Data", "Data"));
|
||||
// Act & Assert
|
||||
Assert.That(() => _suppliesBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1,
|
||||
[new TourSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
|
||||
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UpdateSupplies_NullRecord_ThrowException_Test()
|
||||
{
|
||||
// Act & Assert
|
||||
Assert.That(() => _suppliesBusinessLogicContract.UpdateComponent(null), Throws.TypeOf<ArgumentNullException>());
|
||||
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UpdateComponents_InvalidRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _suppliesBusinessLogicContract.UpdateComponent(new SuppliesDataModel(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1, [])), Throws.TypeOf<ValidationException>());
|
||||
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UpdateSupplies_StorageThrowError_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
_suppliesStorageContract.Setup(x => x.UpdElement(It.IsAny<SuppliesDataModel>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
// Act & Assert
|
||||
Assert.That(() => _suppliesBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1,
|
||||
[new TourSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
|
||||
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Once);
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ using MagicCarpetContracts.DataModels;
|
||||
using MagicCarpetContracts.Enums;
|
||||
using MagicCarpetContracts.Exceptions;
|
||||
using MagicCarpetContracts.StoragesContracts;
|
||||
using MagicCarpetTests.DataModelTests;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
using System;
|
||||
@@ -155,7 +154,7 @@ internal class TourBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var id = Guid.NewGuid().ToString();
|
||||
var record = new TourDataModel(id, "name", "country", 10, TourType.Ski);
|
||||
var record = new TourDataModel(id, "name","country", 10, TourType.Ski);
|
||||
_tourStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
|
||||
//Act
|
||||
var element = _tourBusinessLogicContract.GetTourByData(id);
|
||||
@@ -184,7 +183,7 @@ internal class TourBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var country = "country";
|
||||
var record = new TourDataModel(Guid.NewGuid().ToString(), "name", country, 10, TourType.Ski);
|
||||
var record = new TourDataModel(Guid.NewGuid().ToString(), "name", country, 10, TourType.Ski);
|
||||
_tourStorageContract.Setup(x => x.GetElementByName(country)).Returns(record);
|
||||
//Act
|
||||
var element = _tourBusinessLogicContract.GetTourByData(country);
|
||||
@@ -249,7 +248,7 @@ internal class TourBusinessLogicContractTests
|
||||
_tourStorageContract.Setup(x => x.AddElement(It.IsAny<TourDataModel>()))
|
||||
.Callback((TourDataModel x) =>
|
||||
{
|
||||
flag = x.Id == record.Id && x.TourName == record.TourName && x.TourCountry == record.TourCountry
|
||||
flag = x.Id == record.Id && x.TourName == record.TourName && x.TourCountry == record.TourCountry
|
||||
&& x.Price == record.Price && x.TourType == record.TourType;
|
||||
});
|
||||
//Act
|
||||
@@ -289,18 +288,10 @@ internal class TourBusinessLogicContractTests
|
||||
public void InsertTour_StorageThrowError_ThrowException_Test()
|
||||
{
|
||||
//Arrange
|
||||
Assert.That(() => _tourBusinessLogicContract.InsertTour(new TourDataModel(Guid.NewGuid().ToString(), "name","country", 10, TourType.Ski)), Throws.TypeOf<InsufficientException>());
|
||||
_tourStorageContract.Setup(x => x.AddElement(It.IsAny<TourDataModel>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
_tourStorageContract.Verify(x => x.UpdElement(It.IsAny<TourDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertTour_InsufficientError_ThrowException_Test()
|
||||
{
|
||||
//Arrange
|
||||
Assert.That(() => _tourBusinessLogicContract.InsertTour(new TourDataModel(Guid.NewGuid().ToString(), "name", "country", 10, TourType.Ski)),Throws.TypeOf<InsufficientException>());
|
||||
//Act&Assert
|
||||
_tourStorageContract.Verify(x => x.UpdElement(It.IsAny<TourDataModel>()), Times.Never);
|
||||
Assert.That(() => _tourBusinessLogicContract.InsertTour(new(Guid.NewGuid().ToString(), "name", "country", 10, TourType.Ski)), Throws.TypeOf<StorageException>());
|
||||
_tourStorageContract.Verify(x => x.AddElement(It.IsAny<TourDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -338,7 +329,7 @@ internal class TourBusinessLogicContractTests
|
||||
//Arrange
|
||||
_tourStorageContract.Setup(x => x.UpdElement(It.IsAny<TourDataModel>())).Throws(new ElementExistsException("Data", "Data"));
|
||||
//Act&Assert
|
||||
Assert.That(() => _tourBusinessLogicContract.UpdateTour(new(Guid.NewGuid().ToString(), "name", "country", 10, TourType.Ski)), Throws.TypeOf <ElementExistsException>());
|
||||
Assert.That(() => _tourBusinessLogicContract.UpdateTour(new(Guid.NewGuid().ToString(), "name", "country", 10, TourType.Ski)), Throws.TypeOf<ElementExistsException>());
|
||||
_tourStorageContract.Verify(x => x.UpdElement(It.IsAny<TourDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using MagicCarpetContracts.Enums;
|
||||
using MagicCarpetContracts.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetTests.DataModelTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class AgencyDataModelTests
|
||||
{
|
||||
[Test]
|
||||
public void IdIsNullOrEmptyTest()
|
||||
{
|
||||
var model = CreateDataModel(null, TourType.Beach, 1, CreateSubDataModel());
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
model = CreateDataModel(string.Empty, TourType.Beach, 1, CreateSubDataModel());
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void IdIsNotGuidTest()
|
||||
{
|
||||
var model = CreateDataModel("id", TourType.Beach, 1, CreateSubDataModel());
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TypeIsNoneTest()
|
||||
{
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), TourType.None, 1, CreateSubDataModel());
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CountIsLessOrZeroTest()
|
||||
{
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), TourType.None, 0, CreateSubDataModel());
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
|
||||
model = CreateDataModel(Guid.NewGuid().ToString(), TourType.None, -1, CreateSubDataModel());
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
[Test]
|
||||
public void ToursIsNullOrEmptyTest()
|
||||
{
|
||||
var sale = CreateDataModel(Guid.NewGuid().ToString(), TourType.Beach, 1, null);
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
|
||||
sale = CreateDataModel(Guid.NewGuid().ToString(), TourType.Beach, 1, []);
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AllFieldsIsCorrectTest()
|
||||
{
|
||||
var id = Guid.NewGuid().ToString();
|
||||
var type = TourType.Beach;
|
||||
var count = 1;
|
||||
var tours = CreateSubDataModel();
|
||||
var model = CreateDataModel(id, type, count, tours);
|
||||
Assert.DoesNotThrow(() => model.Validate());
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(model.Id, Is.EqualTo(id));
|
||||
Assert.That(model.TourType, Is.EqualTo(type));
|
||||
Assert.That(model.Count, Is.EqualTo(count));
|
||||
Assert.That(model.Tours, Is.EqualTo(tours));
|
||||
});
|
||||
}
|
||||
|
||||
private static AgencyDataModel CreateDataModel(string? id, TourType type, int count, List<TourAgencyDataModel> tours)
|
||||
=> new AgencyDataModel(id, type, count, tours);
|
||||
private static List<TourAgencyDataModel> CreateSubDataModel()
|
||||
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)];
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using MagicCarpetContracts.Enums;
|
||||
using MagicCarpetContracts.Exceptions;
|
||||
using MagicCarpetContracts.Infrastructure.PostConfigurations;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@@ -14,41 +15,48 @@ internal class PostDataModelTests
|
||||
[Test]
|
||||
public void IdIsNullOrEmptyTest()
|
||||
{
|
||||
var post = CreateDataModel(null, "name", PostType.Manager, 10);
|
||||
var post = CreateDataModel(null, "name", PostType.TravelAgent, new PostConfiguration() { Rate = 10 });
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
post = CreateDataModel(string.Empty, "name", PostType.Manager, 10);
|
||||
post = CreateDataModel(string.Empty, "name", PostType.TravelAgent, new PostConfiguration() { Rate = 10 });
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void IdIsNotGuidTest()
|
||||
{
|
||||
var post = CreateDataModel("id", "name", PostType.Manager, 10);
|
||||
var post = CreateDataModel("id", "name", PostType.TravelAgent, new PostConfiguration() { Rate = 10 });
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PostNameIsEmptyTest()
|
||||
{
|
||||
var manufacturer = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Manager, 10);
|
||||
var manufacturer = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.TravelAgent, new PostConfiguration() { Rate = 10 });
|
||||
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
|
||||
manufacturer = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Manager, 10);
|
||||
manufacturer = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.TravelAgent, new PostConfiguration() { Rate = 10 });
|
||||
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PostTypeIsNoneTest()
|
||||
{
|
||||
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.None, 10);
|
||||
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.None, new PostConfiguration() { Rate = 10 });
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SalaryIsLessOrZeroTest()
|
||||
public void ConfigurationModelIsNullTest()
|
||||
{
|
||||
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 0);
|
||||
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, null);
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, -10);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RateIsLessOrZeroTest()
|
||||
{
|
||||
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new PostConfiguration() { Rate = 0 });
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new PostConfiguration() { Rate = -10 });
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
@@ -58,18 +66,18 @@ internal class PostDataModelTests
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
var postName = "name";
|
||||
var postType = PostType.Manager;
|
||||
var salary = 10;
|
||||
var post = CreateDataModel(postId, postName, postType, salary);
|
||||
var configuration = new PostConfiguration() { Rate = 10 };
|
||||
var post = CreateDataModel(postId, postName, postType, configuration);
|
||||
Assert.That(() => post.Validate(), Throws.Nothing);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(post.Id, Is.EqualTo(postId));
|
||||
Assert.That(post.PostName, Is.EqualTo(postName));
|
||||
Assert.That(post.PostType, Is.EqualTo(postType));
|
||||
Assert.That(post.Salary, Is.EqualTo(salary));
|
||||
Assert.That(post.ConfigurationModel.Rate, Is.EqualTo(configuration.Rate));
|
||||
});
|
||||
}
|
||||
|
||||
private static PostDataModel CreateDataModel(string? id, string? postName, PostType postType, double salary) =>
|
||||
new(id, postName, postType, salary);
|
||||
private static PostDataModel CreateDataModel(string? id, string? postName, PostType postType, PostConfiguration configuration) =>
|
||||
new(id, postName, postType, configuration);
|
||||
}
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using MagicCarpetContracts.Enums;
|
||||
using MagicCarpetContracts.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetTests.DataModelTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class SuppliesDataModelTests
|
||||
{
|
||||
[Test]
|
||||
public void IdIsNullOrEmptyTest()
|
||||
{
|
||||
var model = CreateDataModel(null, TourType.Beach, DateTime.Now, 1, CreateSubDataModel());
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
model = CreateDataModel(string.Empty, TourType.Beach, DateTime.Now, 1, CreateSubDataModel());
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void IdIsNotGuidTest()
|
||||
{
|
||||
var model = CreateDataModel("id", TourType.Beach, DateTime.Now, 1, CreateSubDataModel());
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TypeIsNoneTest()
|
||||
{
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), TourType.None, DateTime.Now, 1, CreateSubDataModel());
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CountIsLessOrZeroTest()
|
||||
{
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), TourType.None, DateTime.Now, 0, CreateSubDataModel());
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
|
||||
model = CreateDataModel(Guid.NewGuid().ToString(), TourType.None, DateTime.Now, -1, CreateSubDataModel());
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
[Test]
|
||||
public void ToursIsNullOrEmptyTest()
|
||||
{
|
||||
var sale = CreateDataModel(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1, null);
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
sale = CreateDataModel(Guid.NewGuid().ToString(), TourType.Beach, DateTime.Now, 1, []);
|
||||
Assert.That(() => sale.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AllFieldsIsCorrectTest()
|
||||
{
|
||||
var id = Guid.NewGuid().ToString();
|
||||
var type = TourType.Beach;
|
||||
var date = DateTime.Now;
|
||||
var count = 1;
|
||||
var tours = CreateSubDataModel();
|
||||
var model = CreateDataModel(id, type, date, count, tours);
|
||||
Assert.DoesNotThrow(() => model.Validate());
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(model.Id, Is.EqualTo(id));
|
||||
Assert.That(model.TourType, Is.EqualTo(type));
|
||||
Assert.That(model.ProductuionDate, Is.EqualTo(date));
|
||||
Assert.That(model.Count, Is.EqualTo(count));
|
||||
Assert.That(model.Tours, Is.EqualTo(tours));
|
||||
});
|
||||
}
|
||||
|
||||
private static SuppliesDataModel CreateDataModel(string? id, TourType type, DateTime date, int count, List<TourSuppliesDataModel> tours)
|
||||
=> new(id, type, date, count, tours);
|
||||
private static List<TourSuppliesDataModel> CreateSubDataModel()
|
||||
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)];
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using MagicCarpetContracts.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetTests.DataModelTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class TourAgencyDataModelTests
|
||||
{
|
||||
[Test]
|
||||
public void AgencyIdIsNullOrEmptyTest()
|
||||
{
|
||||
var model = CreateDataModel(null, Guid.NewGuid().ToString(), 1);
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
|
||||
model = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 1);
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AgencyIdIsNotGuidTest()
|
||||
{
|
||||
var model = CreateDataModel("id", Guid.NewGuid().ToString(), 1);
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TourIdIsNullOrEmptyTest()
|
||||
{
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), null, 1);
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
|
||||
model = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, 1);
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TourIdIsNotGuidTest()
|
||||
{
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), "id", 1);
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CountIsLessOrZeroTest()
|
||||
{
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0);
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
model = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -1);
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AllFieldsIsCorrectTest()
|
||||
{
|
||||
var agencyId = Guid.NewGuid().ToString();
|
||||
var tourId = Guid.NewGuid().ToString();
|
||||
var count = 1;
|
||||
var model = CreateDataModel(agencyId, tourId, count);
|
||||
Assert.That(() => model.Validate(), Throws.Nothing);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(model.AgencyId, Is.EqualTo(agencyId));
|
||||
Assert.That(model.TourId, Is.EqualTo(tourId));
|
||||
Assert.That(model.Count, Is.EqualTo(count));
|
||||
});
|
||||
}
|
||||
|
||||
private static TourAgencyDataModel CreateDataModel(string? agencyId, string? tourId, int count)
|
||||
=> new(agencyId, tourId, count);
|
||||
}
|
||||
@@ -3,7 +3,6 @@ using MagicCarpetContracts.Enums;
|
||||
using MagicCarpetContracts.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
@@ -15,17 +14,17 @@ internal class TourDataModelTests
|
||||
[Test]
|
||||
public void IdIsNullOrEmptyTest()
|
||||
{
|
||||
var tour = CreateDataModel(null, "name", "country", 10.5, TourType.Beach);
|
||||
Assert.That(() => tour.Validate(), Throws.TypeOf<ValidationException>());
|
||||
tour = CreateDataModel(string.Empty, "name", "country", 10.5, TourType.Beach);
|
||||
Assert.That(() => tour.Validate(), Throws.TypeOf<ValidationException>());
|
||||
var cocktail = CreateDataModel(null, "name", "country", 10.5, TourType.Beach);
|
||||
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
|
||||
cocktail = CreateDataModel(string.Empty, "name", "country", 10.5, TourType.Beach);
|
||||
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void IdIsNotGuidTest()
|
||||
{
|
||||
var tour = CreateDataModel("id", "name", "country", 10.5, TourType.Beach);
|
||||
Assert.That(() => tour.Validate(), Throws.TypeOf<ValidationException>());
|
||||
var cocktail = CreateDataModel("id", "name", "country", 10.5, TourType.Beach);
|
||||
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -47,17 +46,17 @@ internal class TourDataModelTests
|
||||
[Test]
|
||||
public void PriceIsLessOrZeroTest()
|
||||
{
|
||||
var tour = CreateDataModel(Guid.NewGuid().ToString(), null, null, 0, TourType.Beach);
|
||||
Assert.That(() => tour.Validate(), Throws.TypeOf<ValidationException>());
|
||||
tour = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, string.Empty, -10.5, TourType.Beach);
|
||||
Assert.That(() => tour.Validate(), Throws.TypeOf<ValidationException>());
|
||||
var cocktail = CreateDataModel(Guid.NewGuid().ToString(), null, null, 0, TourType.Beach);
|
||||
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
|
||||
cocktail = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, string.Empty, -10.5, TourType.Beach);
|
||||
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TourTypeIsNoneTest()
|
||||
{
|
||||
var tour = CreateDataModel(Guid.NewGuid().ToString(), null, null, 0, TourType.Beach);
|
||||
Assert.That(() => tour.Validate(), Throws.TypeOf<ValidationException>());
|
||||
var cocktail = CreateDataModel(Guid.NewGuid().ToString(), null, null, 0, TourType.Beach);
|
||||
Assert.That(() => cocktail.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -68,8 +67,6 @@ internal class TourDataModelTests
|
||||
var tourCountry = "country";
|
||||
var price = 10.5;
|
||||
var tourType = TourType.Ski;
|
||||
var supplies = CreateSuppliesDataModel();
|
||||
var agency = CreateAgencyDataModel();
|
||||
var tour = CreateDataModel(tourId, tourName, tourCountry, price, tourType);
|
||||
Assert.That(() => tour.Validate(), Throws.Nothing);
|
||||
Assert.Multiple(() =>
|
||||
@@ -82,11 +79,6 @@ internal class TourDataModelTests
|
||||
});
|
||||
}
|
||||
|
||||
private static TourDataModel CreateDataModel(string? id, string? tourName, string? countryName, double price, TourType tourType) =>
|
||||
private static TourDataModel CreateDataModel(string? id, string? tourName, string? countryName,double price, TourType tourType) =>
|
||||
new(id, tourName, countryName,price, tourType);
|
||||
private static List<TourSuppliesDataModel> CreateSuppliesDataModel()
|
||||
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)];
|
||||
|
||||
private static List<TourAgencyDataModel> CreateAgencyDataModel()
|
||||
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)];
|
||||
}
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using MagicCarpetContracts.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetTests.DataModelTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class TourSuppliesDataModelTests
|
||||
{
|
||||
[Test]
|
||||
public void SuppliesIdIsNullOrEmptyTest()
|
||||
{
|
||||
var model = CreateDataModel(null, Guid.NewGuid().ToString(), 1);
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
|
||||
model = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), 1);
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SuppliesIdIsNotGuidTest()
|
||||
{
|
||||
var model = CreateDataModel("id", Guid.NewGuid().ToString(), 1);
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TourIdIsNullOrEmptyTest()
|
||||
{
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), null, 1);
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
|
||||
model = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, 1);
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TourIdIsNotGuidTest()
|
||||
{
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), "id", 1);
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CountIsLessOrZeroTest()
|
||||
{
|
||||
var model = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 0);
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
model = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), -1);
|
||||
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AllFieldsIsCorrectTest()
|
||||
{
|
||||
var suppliesId = Guid.NewGuid().ToString();
|
||||
var tourId = Guid.NewGuid().ToString();
|
||||
var count = 1;
|
||||
var model = CreateDataModel(suppliesId, tourId, count);
|
||||
Assert.That(() => model.Validate(), Throws.Nothing);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(model.SuppliesId, Is.EqualTo(suppliesId));
|
||||
Assert.That(model.TourId, Is.EqualTo(tourId));
|
||||
Assert.That(model.Count, Is.EqualTo(count));
|
||||
});
|
||||
}
|
||||
|
||||
private static TourSuppliesDataModel CreateDataModel(string? suppliesId, string? tourId, int count)
|
||||
=> new(suppliesId, tourId, count);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using MagicCarpetContracts.Infrastructure;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetTests.Infrastructure;
|
||||
|
||||
class ConfigurationSalaryTest : IConfigurationSalary
|
||||
{
|
||||
public double ExtraSaleSum => 10;
|
||||
public int MaxConcurrentThreads => 4;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using MagicCarpetContracts.Enums;
|
||||
using MagicCarpetContracts.Infrastructure.PostConfigurations;
|
||||
using MagicCarpetDatabase;
|
||||
using MagicCarpetDatabase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
@@ -20,9 +21,9 @@ internal static class MagicCarpetDbContextExtensions
|
||||
return client;
|
||||
}
|
||||
|
||||
public static Post InsertPostToDatabaseAndReturn(this MagicCarpetDbContext dbContext, string? id = null, string postName = "test", PostType postType = PostType.Manager, double salary = 10, bool isActual = true, DateTime? changeDate = null)
|
||||
public static Post InsertPostToDatabaseAndReturn(this MagicCarpetDbContext dbContext, string? id = null, string postName = "test", PostType postType = PostType.TravelAgent, PostConfiguration? config = null, bool isActual = true, DateTime? changeDate = null)
|
||||
{
|
||||
var post = new Post() { Id = Guid.NewGuid().ToString(), PostId = id ?? Guid.NewGuid().ToString(), PostName = postName, PostType = postType, Salary = salary, IsActual = isActual, ChangeDate = changeDate ?? DateTime.UtcNow };
|
||||
var post = new Post() { Id = Guid.NewGuid().ToString(), PostId = id ?? Guid.NewGuid().ToString(), PostName = postName, PostType = postType, Configuration = config ?? new PostConfiguration() { Rate = 100 }, IsActual = isActual, ChangeDate = changeDate ?? DateTime.UtcNow };
|
||||
dbContext.Posts.Add(post);
|
||||
dbContext.SaveChanges();
|
||||
return post;
|
||||
@@ -67,44 +68,14 @@ internal static class MagicCarpetDbContextExtensions
|
||||
return sale;
|
||||
}
|
||||
|
||||
public static Employee InsertEmployeeToDatabaseAndReturn(this MagicCarpetDbContext dbContext, string? id = null, string fio = "test", string email = "abc@gmail.com", string? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false)
|
||||
public static Employee InsertEmployeeToDatabaseAndReturn(this MagicCarpetDbContext dbContext, string? id = null, string fio = "test", string email = "abc@gmail.com", string? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false, DateTime? dateDelete = null)
|
||||
{
|
||||
var employee = new Employee() { Id = id ?? Guid.NewGuid().ToString(), FIO = fio, Email = email, PostId = postId ?? Guid.NewGuid().ToString(), BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-20), EmploymentDate = employmentDate ?? DateTime.UtcNow, IsDeleted = isDeleted };
|
||||
var employee = new Employee() { Id = id ?? Guid.NewGuid().ToString(), FIO = fio, Email = email, PostId = postId ?? Guid.NewGuid().ToString(), BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-20), EmploymentDate = employmentDate ?? DateTime.UtcNow, IsDeleted = isDeleted, DateOfDelete = dateDelete };
|
||||
dbContext.Employees.Add(employee);
|
||||
dbContext.SaveChanges();
|
||||
return employee;
|
||||
}
|
||||
|
||||
public static Agency InsertAgencyToDatabaseAndReturn(this MagicCarpetDbContext dbContext, string? id = null, TourType tourType = TourType.Beach, int count = 20, List<(string, int)>? tours = null)
|
||||
{
|
||||
var agency = new Agency() { Id = id ?? Guid.NewGuid().ToString(), TourType = tourType, Count = count, Tours = [] };
|
||||
if (tours is not null)
|
||||
{
|
||||
foreach (var elem in tours)
|
||||
{
|
||||
agency.Tours.Add(new TourAgency { AgencyId = agency.Id, TourId = elem.Item1, Count = elem.Item2 });
|
||||
}
|
||||
}
|
||||
dbContext.Agencies.Add(agency);
|
||||
dbContext.SaveChanges();
|
||||
return agency;
|
||||
}
|
||||
|
||||
public static Supplies InsertSuppliesToDatabaseAndReturn(this MagicCarpetDbContext dbContext, string? id = null, TourType type = TourType.Beach, int count = 20, DateTime? date = null, List<(string, int)>? tours = null)
|
||||
{
|
||||
var supply = new Supplies() { Id = id ?? Guid.NewGuid().ToString(), Type = type, Count = count, ProductuionDate = date ?? DateTime.UtcNow, Tours = [] };
|
||||
if (tours is not null)
|
||||
{
|
||||
foreach (var elem in tours)
|
||||
{
|
||||
supply.Tours.Add(new TourSupplies { SuppliesId = supply.Id, TourId = elem.Item1, Count = elem.Item2 });
|
||||
}
|
||||
}
|
||||
dbContext.Supplieses.Add(supply);
|
||||
dbContext.SaveChanges();
|
||||
return supply;
|
||||
}
|
||||
|
||||
public static Client? GetClientFromDatabase(this MagicCarpetDbContext dbContext, string id) => dbContext.Clients.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
public static Post? GetPostFromDatabaseByPostId(this MagicCarpetDbContext dbContext, string id) => dbContext.Posts.FirstOrDefault(x => x.PostId == id && x.IsActual);
|
||||
@@ -120,8 +91,6 @@ internal static class MagicCarpetDbContextExtensions
|
||||
public static Sale[] GetSalesByClientId(this MagicCarpetDbContext dbContext, string? clientId) => [.. dbContext.Sales.Include(x => x.SaleTours).Where(x => x.ClientId == clientId)];
|
||||
|
||||
public static Employee? GetEmployeeFromDatabaseById(this MagicCarpetDbContext dbContext, string id) => dbContext.Employees.FirstOrDefault(x => x.Id == id);
|
||||
public static Agency? GetAgencyFromDatabaseById(this MagicCarpetDbContext dbContext, string id) => dbContext.Agencies.Include(x => x.Tours).FirstOrDefault(x => x.Id == id);
|
||||
public static Supplies? GetSuppliesFromDatabaseById(this MagicCarpetDbContext dbContext, string id) => dbContext.Supplieses.Include(x => x.Tours).FirstOrDefault(x => x.Id == id);
|
||||
|
||||
public static void RemoveClientsFromDatabase(this MagicCarpetDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Clients\" CASCADE;");
|
||||
|
||||
@@ -135,8 +104,5 @@ internal static class MagicCarpetDbContextExtensions
|
||||
|
||||
public static void RemoveEmployeesFromDatabase(this MagicCarpetDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Employees\" CASCADE;");
|
||||
|
||||
public static void RemoveAgenciesFromDatabase(this MagicCarpetDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Agencies\" CASCADE;");
|
||||
public static void RemoveSuppliesFromDatabase(this MagicCarpetDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Supplieses\" CASCADE;");
|
||||
|
||||
private static void ExecuteSqlRaw(this MagicCarpetDbContext dbContext, string command) => dbContext.Database.ExecuteSqlRaw(command);
|
||||
}
|
||||
@@ -1,215 +0,0 @@
|
||||
using MagicCarpetContracts.Exceptions;
|
||||
using MagicCarpetDatabase.Implementations;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using MagicCarpetDatabase.Models;
|
||||
using MagicCarpetContracts.Enums;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MagicCarpetContracts.DataModels;
|
||||
|
||||
namespace MagicCarpetTests.StoragesContractsTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class AgencyStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
private AgencyStorageContract _agencyStorageContract;
|
||||
private Tour _tour;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_agencyStorageContract = new AgencyStorageContract(MagicCarpetDbContext);
|
||||
_tour = InsertTourToDatabaseAndReturn(Guid.NewGuid().ToString(), "name", TourType.Sightseeing);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
MagicCarpetDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Agencies\" CASCADE;");
|
||||
MagicCarpetDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Tours\" CASCADE;");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var agency = InsertAgencyToDatabaseAndReturn(Guid.NewGuid().ToString(), TourType.Sightseeing, 5);
|
||||
InsertAgencyToDatabaseAndReturn(Guid.NewGuid().ToString(), TourType.Sightseeing, 5);
|
||||
InsertAgencyToDatabaseAndReturn(Guid.NewGuid().ToString(), TourType.Sightseeing, 5);
|
||||
var list = _agencyStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
AssertElement(list.First(), agency);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenNoRecords_Test()
|
||||
{
|
||||
var list = _agencyStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var agency = InsertAgencyToDatabaseAndReturn(Guid.NewGuid().ToString(), TourType.Sightseeing, 5);
|
||||
var result = _agencyStorageContract.GetElementById(agency.Id);
|
||||
AssertElement(result, agency);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
Assert.That(() => _agencyStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenValidData_Test()
|
||||
{
|
||||
var agency = CreateModel(Guid.NewGuid().ToString(), TourType.Sightseeing, 5, [_tour.Id]);
|
||||
_agencyStorageContract.AddElement(agency);
|
||||
var result = GetAgencyFromDatabaseById(agency.Id);
|
||||
AssertElement(result, agency);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
|
||||
{
|
||||
var agency = CreateModel(Guid.NewGuid().ToString(), TourType.Sightseeing, 5, [_tour.Id]);
|
||||
InsertAgencyToDatabaseAndReturn(agency.Id, TourType.Sightseeing, 5, [(_tour.Id, 3)]);
|
||||
Assert.That(() => _agencyStorageContract.AddElement(agency), Throws.TypeOf<StorageException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenNoHaveTour_Test()
|
||||
{
|
||||
var agency = CreateModel(Guid.NewGuid().ToString(), TourType.Sightseeing, 0, [_tour.Id]);
|
||||
InsertAgencyToDatabaseAndReturn(agency.Id, TourType.Sightseeing, 5, [(_tour.Id, 3)]);
|
||||
Assert.That(() => _agencyStorageContract.AddElement(agency), Throws.TypeOf<StorageException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenValidData_Test()
|
||||
{
|
||||
var agency = CreateModel(Guid.NewGuid().ToString(), TourType.Sightseeing, 5, [_tour.Id]);
|
||||
InsertAgencyToDatabaseAndReturn(agency.Id, TourType.Ski, 10, null);
|
||||
_agencyStorageContract.UpdElement(agency);
|
||||
var result = GetAgencyFromDatabaseById(agency.Id);
|
||||
AssertElement(result, agency);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
var agency = CreateModel(Guid.NewGuid().ToString(), TourType.Sightseeing, 5, [_tour.Id]);
|
||||
Assert.That(() => _agencyStorageContract.UpdElement(agency), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenRecordExists_Test()
|
||||
{
|
||||
var agency = InsertAgencyToDatabaseAndReturn(Guid.NewGuid().ToString(), TourType.Sightseeing, 5);
|
||||
_agencyStorageContract.DelElement(agency.Id);
|
||||
var result = GetAgencyFromDatabaseById(agency.Id);
|
||||
Assert.That(result, Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenRecordDoesNotExist_ThrowsElementNotFoundException()
|
||||
{
|
||||
Assert.That(() => _agencyStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private Tour InsertTourToDatabaseAndReturn(string id, string name, TourType type)
|
||||
{
|
||||
var tour = new Tour { Id = id, TourName = name, TourType = type };
|
||||
MagicCarpetDbContext.Tours.Add(tour);
|
||||
MagicCarpetDbContext.SaveChanges();
|
||||
return tour;
|
||||
}
|
||||
|
||||
private Agency InsertAgencyToDatabaseAndReturn(string id, TourType type, int count, List<(string, int)>? tours = null)
|
||||
{
|
||||
var agency = new Agency { Id = id, TourType = type, Count = count, Tours = [] };
|
||||
if (tours is not null)
|
||||
{
|
||||
foreach (var elem in tours)
|
||||
{
|
||||
agency.Tours.Add(new TourAgency { AgencyId = agency.Id, TourId = elem.Item1, Count = elem.Item2 });
|
||||
}
|
||||
}
|
||||
MagicCarpetDbContext.Agencies.Add(agency);
|
||||
MagicCarpetDbContext.SaveChanges();
|
||||
return agency;
|
||||
}
|
||||
|
||||
private static void AssertElement(AgencyDataModel? actual, Agency expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.TourType, Is.EqualTo(expected.TourType));
|
||||
Assert.That(actual.Count, Is.EqualTo(expected.Count));
|
||||
});
|
||||
if (expected.Tours is not null)
|
||||
{
|
||||
Assert.That(actual.Tours, Is.Not.Null);
|
||||
Assert.That(actual.Tours, Has.Count.EqualTo(expected.Tours.Count));
|
||||
for (int i = 0; i < actual.Tours.Count; ++i)
|
||||
{
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Tours[i].TourId, Is.EqualTo(expected.Tours[i].TourId));
|
||||
Assert.That(actual.Tours[i].Count, Is.EqualTo(expected.Tours[i].Count));
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.That(actual.Tours, Is.Null);
|
||||
}
|
||||
}
|
||||
|
||||
private static void AssertElement(Agency? actual, AgencyDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.TourType, Is.EqualTo(expected.TourType));
|
||||
Assert.That(actual.Count, Is.EqualTo(expected.Count));
|
||||
});
|
||||
if (expected.Tours is not null)
|
||||
{
|
||||
Assert.That(actual.Tours, Is.Not.Null);
|
||||
Assert.That(actual.Tours, Has.Count.EqualTo(expected.Tours.Count));
|
||||
for (int i = 0; i < actual.Tours.Count; ++i)
|
||||
{
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Tours[i].TourId, Is.EqualTo(expected.Tours[i].TourId));
|
||||
Assert.That(actual.Tours[i].Count, Is.EqualTo(expected.Tours[i].Count));
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.That(actual.Tours, Is.Null);
|
||||
}
|
||||
}
|
||||
|
||||
private static AgencyDataModel CreateModel(string id, TourType type, int count, List<string> toursIds)
|
||||
{
|
||||
var tours = toursIds.Select(x => new TourAgencyDataModel(id, x, 1)).ToList();
|
||||
return new(id, type, count, tours);
|
||||
}
|
||||
|
||||
private Agency? GetAgencyFromDatabaseById(string id)
|
||||
{
|
||||
return MagicCarpetDbContext.Agencies.FirstOrDefault(x => x.Id == id);
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetTests.StoragesContractsTests;
|
||||
namespace MagicCarpetTests.StoragesContracts;
|
||||
|
||||
internal abstract class BaseStorageContractTest
|
||||
{
|
||||
|
||||
@@ -11,7 +11,7 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetTests.StoragesContractsTests;
|
||||
namespace MagicCarpetTests.StoragesContracts;
|
||||
|
||||
[TestFixture]
|
||||
internal class ClientStorageContractTests : BaseStorageContractTest
|
||||
|
||||
@@ -10,7 +10,7 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetTests.StoragesContractsTests;
|
||||
namespace MagicCarpetTests.StoragesContracts;
|
||||
|
||||
[TestFixture]
|
||||
class EmployeeStorageContractTests : BaseStorageContractTest
|
||||
@@ -188,6 +188,43 @@ class EmployeeStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(() => _employeeStorageContract.DelElement(employee.Id), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetEmployeeTrend_WhenNoNewAndDeletedEmployees_Test()
|
||||
{
|
||||
var startDate = DateTime.UtcNow.AddDays(-5);
|
||||
var endDate = DateTime.UtcNow.AddDays(-3);
|
||||
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-10));
|
||||
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-10), isDeleted: true, dateDelete: DateTime.UtcNow.AddDays(-9));
|
||||
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-10), isDeleted: true, dateDelete: DateTime.UtcNow.AddDays(-1));
|
||||
var count = _employeeStorageContract.GetEmployeeTrend(startDate, endDate);
|
||||
Assert.That(count, Is.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetEmployeeTrend_WhenHaveNewAndNoDeletedEmployees_Test()
|
||||
{
|
||||
var startDate = DateTime.UtcNow.AddDays(-5);
|
||||
var endDate = DateTime.UtcNow.AddDays(-3);
|
||||
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-10));
|
||||
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-4));
|
||||
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
var count = _employeeStorageContract.GetEmployeeTrend(startDate, endDate);
|
||||
Assert.That(count, Is.EqualTo(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetEmployeeTrend_WhenNoNewAndHaveDeletedEmployees_Test()
|
||||
{
|
||||
var startDate = DateTime.UtcNow.AddDays(-5);
|
||||
var endDate = DateTime.UtcNow.AddDays(-3);
|
||||
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-10), isDeleted: true, dateDelete: DateTime.UtcNow.AddDays(-9));
|
||||
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-10), isDeleted: true, dateDelete: DateTime.UtcNow.AddDays(-4));
|
||||
MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-10), isDeleted: true, dateDelete: DateTime.UtcNow.AddDays(-1));
|
||||
var count = _employeeStorageContract.GetEmployeeTrend(startDate, endDate);
|
||||
Assert.That(count, Is.EqualTo(-1));
|
||||
}
|
||||
|
||||
|
||||
private static void AssertElement(EmployeeDataModel? actual, Employee expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
@@ -218,6 +255,7 @@ class EmployeeStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(actual.BirthDate, Is.EqualTo(expected.BirthDate));
|
||||
Assert.That(actual.EmploymentDate, Is.EqualTo(expected.EmploymentDate));
|
||||
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
|
||||
Assert.That(actual.DateOfDelete.HasValue, Is.EqualTo(expected.IsDeleted));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using MagicCarpetContracts.Enums;
|
||||
using MagicCarpetContracts.Exceptions;
|
||||
using MagicCarpetContracts.Infrastructure.PostConfigurations;
|
||||
using MagicCarpetDatabase.Implementations;
|
||||
using MagicCarpetDatabase.Models;
|
||||
using MagicCarpetTests.Infrastructure;
|
||||
using MagicCarpetTests.StoragesContracts;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetTests.StoragesContracts;
|
||||
[TestFixture]
|
||||
internal class PostStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
private PostStorageContract _postStorageContract;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_postStorageContract = new PostStorageContract(MagicCarpetDbContext);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
MagicCarpetDbContext.RemovePostsFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var post = MagicCarpetDbContext.InsertPostToDatabaseAndReturn(postName: "name 1");
|
||||
MagicCarpetDbContext.InsertPostToDatabaseAndReturn(postName: "name 2");
|
||||
MagicCarpetDbContext.InsertPostToDatabaseAndReturn(postName: "name 3");
|
||||
var list = _postStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
AssertElement(list.First(x => x.Id == post.PostId), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenNoRecords_Test()
|
||||
{
|
||||
var list = _postStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenDifferentConfigTypes_Test()
|
||||
{
|
||||
var postSimple = MagicCarpetDbContext.InsertPostToDatabaseAndReturn(postName: "name 1");
|
||||
var postBuilder = MagicCarpetDbContext.InsertPostToDatabaseAndReturn(postName: "name 2", config: new TravelAgentPostConfiguration() { SalePercent = 500 });
|
||||
var postLoader = MagicCarpetDbContext.InsertPostToDatabaseAndReturn(postName: "name 3", config: new ChiefPostConfiguration() { PersonalCountTrendPremium = 20 });
|
||||
var list = _postStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
AssertElement(list.First(x => x.Id == postSimple.PostId), postSimple);
|
||||
AssertElement(list.First(x => x.Id == postBuilder.PostId), postBuilder);
|
||||
AssertElement(list.First(x => x.Id == postLoader.PostId), postLoader);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetPostWithHistory_WhenHaveRecords_Test()
|
||||
{
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
MagicCarpetDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
|
||||
MagicCarpetDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
|
||||
MagicCarpetDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
|
||||
var list = _postStorageContract.GetPostWithHistory(postId);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetPostWithHistory_WhenNoRecords_Test()
|
||||
{
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
MagicCarpetDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
|
||||
MagicCarpetDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
|
||||
MagicCarpetDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
|
||||
var list = _postStorageContract.GetPostWithHistory(Guid.NewGuid().ToString());
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var post = MagicCarpetDbContext.InsertPostToDatabaseAndReturn();
|
||||
AssertElement(_postStorageContract.GetElementById(post.PostId), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
MagicCarpetDbContext.InsertPostToDatabaseAndReturn();
|
||||
Assert.That(() => _postStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var post = MagicCarpetDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
Assert.That(() => _postStorageContract.GetElementById(post.PostId), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenTrySearchById_Test()
|
||||
{
|
||||
var post = MagicCarpetDbContext.InsertPostToDatabaseAndReturn();
|
||||
Assert.That(() => _postStorageContract.GetElementById(post.Id), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenHaveRecord_Test()
|
||||
{
|
||||
var post = MagicCarpetDbContext.InsertPostToDatabaseAndReturn();
|
||||
AssertElement(_postStorageContract.GetElementByName(post.PostName), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenNoRecord_Test()
|
||||
{
|
||||
MagicCarpetDbContext.InsertPostToDatabaseAndReturn();
|
||||
Assert.That(() => _postStorageContract.GetElementByName("name"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var post = MagicCarpetDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
Assert.That(() => _postStorageContract.GetElementById(post.PostName), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString());
|
||||
_postStorageContract.AddElement(post);
|
||||
AssertElement(MagicCarpetDbContext.GetPostFromDatabaseByPostId(post.Id), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), "name unique");
|
||||
MagicCarpetDbContext.InsertPostToDatabaseAndReturn(postName: post.PostName, isActual: true);
|
||||
Assert.That(() => _postStorageContract.AddElement(post), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSamePostId_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString());
|
||||
MagicCarpetDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: true);
|
||||
Assert.That(() => _postStorageContract.AddElement(post), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WithTravelAgentPostConfiguration_Test()
|
||||
{
|
||||
var salePercent = 10;
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), config: new TravelAgentPostConfiguration() { SalePercent = salePercent });
|
||||
_postStorageContract.AddElement(post);
|
||||
var element = MagicCarpetDbContext.GetPostFromDatabaseByPostId(post.Id);
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(TravelAgentPostConfiguration).Name));
|
||||
Assert.That((element.Configuration as TravelAgentPostConfiguration)!.SalePercent, Is.EqualTo(salePercent));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WithChiefPostConfiguration_Test()
|
||||
{
|
||||
var trendPremium = 20;
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), config: new ChiefPostConfiguration() { PersonalCountTrendPremium = trendPremium });
|
||||
_postStorageContract.AddElement(post);
|
||||
var element = MagicCarpetDbContext.GetPostFromDatabaseByPostId(post.Id);
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(ChiefPostConfiguration).Name));
|
||||
Assert.That((element.Configuration as ChiefPostConfiguration)!.PersonalCountTrendPremium, Is.EqualTo(trendPremium));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString());
|
||||
MagicCarpetDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: true);
|
||||
_postStorageContract.UpdElement(post);
|
||||
var posts = MagicCarpetDbContext.GetPostsFromDatabaseByPostId(post.Id);
|
||||
Assert.That(posts, Is.Not.Null);
|
||||
Assert.That(posts, Has.Length.EqualTo(2));
|
||||
AssertElement(posts[0], CreateModel(post.Id));
|
||||
AssertElement(posts[^1], CreateModel(post.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _postStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), "New Name");
|
||||
MagicCarpetDbContext.InsertPostToDatabaseAndReturn(post.Id, postName: "name");
|
||||
MagicCarpetDbContext.InsertPostToDatabaseAndReturn(postName: post.PostName);
|
||||
Assert.That(() => _postStorageContract.UpdElement(post), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString());
|
||||
MagicCarpetDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: false);
|
||||
Assert.That(() => _postStorageContract.UpdElement(post), Throws.TypeOf<ElementDeletedException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WithTravelAgentPostConfiguration_Test()
|
||||
{
|
||||
var post = MagicCarpetDbContext.InsertPostToDatabaseAndReturn();
|
||||
var salePercent = 10;
|
||||
_postStorageContract.UpdElement(CreateModel(post.PostId, config: new TravelAgentPostConfiguration() { SalePercent = salePercent }));
|
||||
var element = MagicCarpetDbContext.GetPostFromDatabaseByPostId(post.PostId);
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(TravelAgentPostConfiguration).Name));
|
||||
Assert.That((element.Configuration as TravelAgentPostConfiguration)!.SalePercent, Is.EqualTo(salePercent));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WithChiefPostConfiguration_Test()
|
||||
{
|
||||
var post = MagicCarpetDbContext.InsertPostToDatabaseAndReturn();
|
||||
var trendPremium = 20;
|
||||
_postStorageContract.UpdElement(CreateModel(post.PostId, config: new ChiefPostConfiguration() { PersonalCountTrendPremium = trendPremium }));
|
||||
var element = MagicCarpetDbContext.GetPostFromDatabaseByPostId(post.PostId);
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(ChiefPostConfiguration).Name));
|
||||
Assert.That((element.Configuration as ChiefPostConfiguration)!.PersonalCountTrendPremium, Is.EqualTo(trendPremium));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var post = MagicCarpetDbContext.InsertPostToDatabaseAndReturn(isActual: true);
|
||||
_postStorageContract.DelElement(post.PostId);
|
||||
Assert.That(MagicCarpetDbContext.GetPostFromDatabaseByPostId(post.PostId), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _postStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var post = MagicCarpetDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
Assert.That(() => _postStorageContract.DelElement(post.PostId), Throws.TypeOf<ElementDeletedException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_ResElement_Test()
|
||||
{
|
||||
var post = MagicCarpetDbContext.InsertPostToDatabaseAndReturn(isActual: false);
|
||||
_postStorageContract.ResElement(post.PostId);
|
||||
var element = MagicCarpetDbContext.GetPostFromDatabaseByPostId(post.PostId);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.That(element!.IsActual);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_ResElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _postStorageContract.ResElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_ResElement_WhenRecordNotWasDeleted_Test()
|
||||
{
|
||||
var post = MagicCarpetDbContext.InsertPostToDatabaseAndReturn(isActual: true);
|
||||
Assert.That(() => _postStorageContract.ResElement(post.PostId), Throws.Nothing);
|
||||
}
|
||||
|
||||
private static void AssertElement(PostDataModel? actual, Post expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.PostId));
|
||||
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
|
||||
Assert.That(actual.PostType, Is.EqualTo(expected.PostType));
|
||||
Assert.That(actual.ConfigurationModel.Rate, Is.EqualTo(expected.Configuration.Rate));
|
||||
});
|
||||
}
|
||||
|
||||
private static PostDataModel CreateModel(string postId, string postName = "test", PostType postType = PostType.TravelAgent, PostConfiguration? config = null)
|
||||
=> new(postId, postName, postType, config ?? new PostConfiguration() { Rate = 100 });
|
||||
|
||||
private static void AssertElement(Post? actual, PostDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.PostId, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
|
||||
Assert.That(actual.PostType, Is.EqualTo(expected.PostType));
|
||||
Assert.That(actual.Configuration.Rate, Is.EqualTo(expected.ConfigurationModel.Rate));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetTests.StoragesContractsTests;
|
||||
namespace MagicCarpetTests.StoragesContracts;
|
||||
|
||||
[TestFixture]
|
||||
internal class SalaryStorageContractTests : BaseStorageContractTest
|
||||
|
||||
@@ -12,12 +12,12 @@ using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using static NUnit.Framework.Internal.OSPlatform;
|
||||
|
||||
namespace MagicCarpetTests.StoragesContractsTests;
|
||||
namespace MagicCarpetTests.StoragesContracts;
|
||||
|
||||
[TestFixture]
|
||||
internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
private SaleStorageContract _saleStorageContract;
|
||||
private SaleStorageContract _saletStorageContract;
|
||||
private Client _client;
|
||||
private Employee _employee;
|
||||
private Tour _tour;
|
||||
@@ -25,7 +25,7 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_saleStorageContract = new SaleStorageContract(MagicCarpetDbContext);
|
||||
_saletStorageContract = new SaleStorageContract(MagicCarpetDbContext);
|
||||
_client = MagicCarpetDbContext.InsertClientToDatabaseAndReturn();
|
||||
_employee = MagicCarpetDbContext.InsertEmployeeToDatabaseAndReturn();
|
||||
_tour = MagicCarpetDbContext.InsertTourToDatabaseAndReturn();
|
||||
@@ -46,7 +46,7 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
var sale = MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1, 1.2)]);
|
||||
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 5, 1.2)]);
|
||||
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, null, tours: [(_tour.Id, 10, 1.2)]);
|
||||
var list = _saleStorageContract.GetList();
|
||||
var list = _saletStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
AssertElement(list.First(x => x.Id == sale.Id), sale);
|
||||
@@ -55,7 +55,7 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_GetList_WhenNoRecords_Test()
|
||||
{
|
||||
var list = _saleStorageContract.GetList();
|
||||
var list = _saletStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
@@ -67,7 +67,7 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), tours: [(_tour.Id, 1, 1.2)]);
|
||||
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), tours: [(_tour.Id, 1, 1.2)]);
|
||||
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(3), tours: [(_tour.Id, 1, 1.2)]);
|
||||
var list = _saleStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1));
|
||||
var list = _saletStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
}
|
||||
@@ -79,7 +79,7 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1, 1.2)]);
|
||||
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1, 1.2)]);
|
||||
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(employee.Id, null, tours: [(_tour.Id, 1, 1.2)]);
|
||||
var list = _saleStorageContract.GetList(employeeId: _employee.Id);
|
||||
var list = _saletStorageContract.GetList(employeeId: _employee.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
Assert.That(list.All(x => x.EmployeeId == _employee.Id));
|
||||
@@ -93,7 +93,7 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1, 1.2)]);
|
||||
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, client.Id, tours: [(_tour.Id, 1, 1.2)]);
|
||||
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, null, tours: [(_tour.Id, 1, 1.2)]);
|
||||
var list = _saleStorageContract.GetList(clientId: _client.Id);
|
||||
var list = _saletStorageContract.GetList(clientId: _client.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
Assert.That(list.All(x => x.ClientId == _client.Id));
|
||||
@@ -107,7 +107,7 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1, 1.2), (tour.Id, 4, 1.2)]);
|
||||
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, null, tours: [(tour.Id, 1, 1.2)]);
|
||||
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, null, tours: [(tour.Id, 1, 1.2), (_tour.Id, 1, 1.2)]);
|
||||
var list = _saleStorageContract.GetList(tourId: _tour.Id);
|
||||
var list = _saletStorageContract.GetList(tourId: _tour.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
Assert.That(list.All(x => x.Tours!.Any(y => y.TourId == _tour.Id)));
|
||||
@@ -126,7 +126,7 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, client.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), tours: [(_tour.Id, 1, 1.2)]);
|
||||
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), tours: [(tour.Id, 1, 1.2)]);
|
||||
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(employee.Id, null, saleDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), tours: [(_tour.Id, 1, 1.2)]);
|
||||
var list = _saleStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1), employeeId: _employee.Id, clientId: _client.Id, tourId: tour.Id);
|
||||
var list = _saletStorageContract.GetList(startDate: DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1), employeeId: _employee.Id, clientId: _client.Id, tourId: tour.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(1));
|
||||
}
|
||||
@@ -135,28 +135,28 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var sale = MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1, 1.2)]);
|
||||
AssertElement(_saleStorageContract.GetElementById(sale.Id), sale);
|
||||
AssertElement(_saletStorageContract.GetElementById(sale.Id), sale);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1, 1.2)]);
|
||||
Assert.That(() => _saleStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
Assert.That(() => _saletStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenRecordHasCanceled_Test()
|
||||
{
|
||||
var sale = MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1, 1.2)], isCancel: true);
|
||||
AssertElement(_saleStorageContract.GetElementById(sale.Id), sale);
|
||||
AssertElement(_saletStorageContract.GetElementById(sale.Id), sale);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var sale = CreateModel(Guid.NewGuid().ToString(), _employee.Id, _client.Id, DiscountType.RegularCustomer, false, [_tour.Id]);
|
||||
_saleStorageContract.AddElement(sale);
|
||||
_saletStorageContract.AddElement(sale);
|
||||
AssertElement(MagicCarpetDbContext.GetSaleFromDatabaseById(sale.Id), sale);
|
||||
}
|
||||
|
||||
@@ -164,7 +164,7 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
public void Try_AddElement_WhenIsDeletedIsTrue_Test()
|
||||
{
|
||||
var sale = CreateModel(Guid.NewGuid().ToString(), _employee.Id, _client.Id, DiscountType.RegularCustomer, true, [_tour.Id]);
|
||||
Assert.That(() => _saleStorageContract.AddElement(sale), Throws.Nothing);
|
||||
Assert.That(() => _saletStorageContract.AddElement(sale), Throws.Nothing);
|
||||
AssertElement(MagicCarpetDbContext.GetSaleFromDatabaseById(sale.Id), CreateModel(sale.Id, _employee.Id, _client.Id, DiscountType.RegularCustomer, false, [_tour.Id]));
|
||||
}
|
||||
|
||||
@@ -172,7 +172,7 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var sale = MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1, 1.2)], isCancel: false);
|
||||
_saleStorageContract.DelElement(sale.Id);
|
||||
_saletStorageContract.DelElement(sale.Id);
|
||||
var element = MagicCarpetDbContext.GetSaleFromDatabaseById(sale.Id);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
@@ -184,53 +184,14 @@ internal class SaleStorageContractTests : BaseStorageContractTest
|
||||
[Test]
|
||||
public void Try_DelElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _saleStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
Assert.That(() => _saletStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenRecordWasCanceled_Test()
|
||||
{
|
||||
var sale = InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1)], isCancel: true);
|
||||
Assert.That(() => _saleStorageContract.DelElement(sale.Id), Throws.TypeOf<ElementDeletedException>());
|
||||
}
|
||||
|
||||
private Client InsertClientToDatabaseAndReturn(string fio = "test", string phoneNumber = "+7-777-777-77-77")
|
||||
{
|
||||
var client = new Client() { Id = Guid.NewGuid().ToString(), FIO = fio, PhoneNumber = phoneNumber, DiscountSize = 10 };
|
||||
MagicCarpetDbContext.Clients.Add(client);
|
||||
MagicCarpetDbContext.SaveChanges();
|
||||
return client;
|
||||
}
|
||||
|
||||
private Employee InsertEmployeeToDatabaseAndReturn(string fio = "test", string employeeEmail = "abc@gmail.com")
|
||||
{
|
||||
var employee = new Employee() { Id = Guid.NewGuid().ToString(), FIO = fio, Email = employeeEmail, PostId = Guid.NewGuid().ToString() };
|
||||
MagicCarpetDbContext.Employees.Add(employee);
|
||||
MagicCarpetDbContext.SaveChanges();
|
||||
return employee;
|
||||
}
|
||||
|
||||
private Tour InsertTourToDatabaseAndReturn(string tourName = "test", TourType tourType = TourType.Sightseeing, double price = 1)
|
||||
{
|
||||
var tour = new Tour() { Id = Guid.NewGuid().ToString(), TourName = tourName, TourType = tourType, Price = price };
|
||||
MagicCarpetDbContext.Tours.Add(tour);
|
||||
MagicCarpetDbContext.SaveChanges();
|
||||
return tour;
|
||||
}
|
||||
|
||||
private Sale InsertSaleToDatabaseAndReturn(string employeeId, string? clientId, DateTime? saleDate = null, double sum = 1, DiscountType discountType = DiscountType.OnSale, double discount = 0, bool isCancel = false, List<(string, int)>? tours = null)
|
||||
{
|
||||
var sale = new Sale() { EmployeeId = employeeId, ClientId = clientId, SaleDate = saleDate ?? DateTime.UtcNow, Sum = sum, DiscountType = discountType, Discount = discount, IsCancel = isCancel, SaleTours = [] };
|
||||
if (tours is not null)
|
||||
{
|
||||
foreach (var elem in tours)
|
||||
{
|
||||
sale.SaleTours.Add(new SaleTour { TourId = elem.Item1, SaleId = sale.Id, Count = elem.Item2 });
|
||||
}
|
||||
}
|
||||
MagicCarpetDbContext.Sales.Add(sale);
|
||||
MagicCarpetDbContext.SaveChanges();
|
||||
return sale;
|
||||
var sale = MagicCarpetDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, tours: [(_tour.Id, 1, 1.2)], isCancel: true);
|
||||
Assert.That(() => _saletStorageContract.DelElement(sale.Id), Throws.TypeOf<ElementDeletedException>());
|
||||
}
|
||||
|
||||
private static void AssertElement(SaleDataModel? actual, Sale expected)
|
||||
|
||||
@@ -1,191 +0,0 @@
|
||||
using MagicCarpetContracts.DataModels;
|
||||
using MagicCarpetContracts.Enums;
|
||||
using MagicCarpetContracts.Exceptions;
|
||||
using MagicCarpetDatabase.Implementations;
|
||||
using MagicCarpetDatabase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MagicCarpetTests.StoragesContractsTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class SuppliesStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
private SuppliesStorageContract _suppliesStorageContract;
|
||||
private Tour _tour;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_suppliesStorageContract = new SuppliesStorageContract(MagicCarpetDbContext);
|
||||
_tour = InsertTourToDatabaseAndReturn();
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
MagicCarpetDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Supplieses\" CASCADE;");
|
||||
MagicCarpetDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Tours\" CASCADE;");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var supply = InsertSupplyToDatabaseAndReturn(Guid.NewGuid().ToString(), TourType.Ski, 5);
|
||||
InsertSupplyToDatabaseAndReturn(Guid.NewGuid().ToString(), TourType.Ski, 5);
|
||||
InsertSupplyToDatabaseAndReturn(Guid.NewGuid().ToString(), TourType.Ski, 5);
|
||||
var list = _suppliesStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
AssertElement(list.First(), supply);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenNoRecords_Test()
|
||||
{
|
||||
var list = _suppliesStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var supply = InsertSupplyToDatabaseAndReturn(Guid.NewGuid().ToString(), TourType.Ski, 5);
|
||||
AssertElement(_suppliesStorageContract.GetElementById(supply.Id), supply);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
Assert.That(() => _suppliesStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var supply = CreateModel(Guid.NewGuid().ToString(), TourType.Ski, 5, [_tour.Id]);
|
||||
_suppliesStorageContract.AddElement(supply);
|
||||
AssertElement(GetSupplyFromDatabaseById(supply.Id), supply);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
|
||||
{
|
||||
var supply = CreateModel(Guid.NewGuid().ToString(), TourType.Ski, 5, [_tour.Id]);
|
||||
InsertSupplyToDatabaseAndReturn(supply.Id, TourType.Ski, 5, [(_tour.Id, 3)]);
|
||||
Assert.That(() => _suppliesStorageContract.AddElement(supply), Throws.TypeOf<StorageException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var supply = CreateModel(Guid.NewGuid().ToString(), TourType.Ski, 5, [_tour.Id]);
|
||||
InsertSupplyToDatabaseAndReturn(supply.Id, TourType.Ski, 5, null);
|
||||
_suppliesStorageContract.UpdElement(supply);
|
||||
AssertElement(GetSupplyFromDatabaseById(supply.Id), supply);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _suppliesStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString(), TourType.Ski, 5, [_tour.Id])), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private Tour InsertTourToDatabaseAndReturn()
|
||||
{
|
||||
var tour = new Tour { Id = Guid.NewGuid().ToString(), TourName = "Test Tour", TourType = TourType.Ski };
|
||||
MagicCarpetDbContext.Tours.Add(tour);
|
||||
MagicCarpetDbContext.SaveChanges();
|
||||
return tour;
|
||||
}
|
||||
|
||||
private Supplies InsertSupplyToDatabaseAndReturn(string id, TourType type, int count, List<(string, int)>? tours = null)
|
||||
{
|
||||
var supply = new Supplies { Id = id, Type = type, ProductuionDate = DateTime.UtcNow, Count = count, Tours = [] };
|
||||
if (tours is not null)
|
||||
{
|
||||
foreach (var elem in tours)
|
||||
{
|
||||
supply.Tours.Add(new TourSupplies { SuppliesId = supply.Id, TourId = elem.Item1, Count = elem.Item2 });
|
||||
}
|
||||
}
|
||||
MagicCarpetDbContext.Supplieses.Add(supply);
|
||||
MagicCarpetDbContext.SaveChanges();
|
||||
return supply;
|
||||
}
|
||||
|
||||
private static void AssertElement(SuppliesDataModel? actual, Supplies expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.TourType, Is.EqualTo(expected.Type));
|
||||
Assert.That(actual.ProductuionDate, Is.EqualTo(expected.ProductuionDate));
|
||||
Assert.That(actual.Count, Is.EqualTo(expected.Count));
|
||||
});
|
||||
if (expected.Tours is not null)
|
||||
{
|
||||
Assert.That(actual.Tours, Is.Not.Null);
|
||||
Assert.That(actual.Tours, Has.Count.EqualTo(expected.Tours.Count));
|
||||
for (int i = 0; i < actual.Tours.Count; ++i)
|
||||
{
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Tours[i].TourId, Is.EqualTo(expected.Tours[i].TourId));
|
||||
Assert.That(actual.Tours[i].Count, Is.EqualTo(expected.Tours[i].Count));
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.That(actual.Tours, Is.Null);
|
||||
}
|
||||
}
|
||||
|
||||
private static void AssertElement(Supplies? actual, SuppliesDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.Type, Is.EqualTo(expected.TourType));
|
||||
Assert.That(actual.ProductuionDate, Is.EqualTo(expected.ProductuionDate));
|
||||
Assert.That(actual.Count, Is.EqualTo(expected.Count));
|
||||
});
|
||||
if (expected.Tours is not null)
|
||||
{
|
||||
Assert.That(actual.Tours, Is.Not.Null);
|
||||
Assert.That(actual.Tours, Has.Count.EqualTo(expected.Tours.Count));
|
||||
for (int i = 0; i < actual.Tours.Count; ++i)
|
||||
{
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Tours[i].TourId, Is.EqualTo(expected.Tours[i].TourId));
|
||||
Assert.That(actual.Tours[i].Count, Is.EqualTo(expected.Tours[i].Count));
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.That(actual.Tours, Is.Null);
|
||||
}
|
||||
}
|
||||
|
||||
private static SuppliesDataModel CreateModel(string id, TourType type, int count, List<string> toursIds)
|
||||
{
|
||||
var tours = toursIds.Select(x => new TourSuppliesDataModel(id, x, 1)).ToList();
|
||||
return new(id, type, DateTime.UtcNow, count, tours);
|
||||
}
|
||||
|
||||
|
||||
private Supplies? GetSupplyFromDatabaseById(string id)
|
||||
{
|
||||
return MagicCarpetDbContext.Supplieses.FirstOrDefault(x => x.Id == id);
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using static NUnit.Framework.Internal.OSPlatform;
|
||||
|
||||
namespace MagicCarpetTests.StoragesContractsTests;
|
||||
namespace MagicCarpetTests.StoragesContracts;
|
||||
|
||||
[TestFixture]
|
||||
internal class TourStorageContractTests : BaseStorageContractTest
|
||||
@@ -166,23 +166,6 @@ internal class TourStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
Assert.That(() => _tourStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private Tour InsertTourToDatabaseAndReturn(string id, string tourName = "test", string tourCountry = "country", TourType tourType = TourType.Beach, double price = 1)
|
||||
{
|
||||
var tour = new Tour() { Id = id, TourName = tourName, TourCountry = tourCountry, TourType = tourType, Price = price };
|
||||
MagicCarpetDbContext.Tours.Add(tour);
|
||||
MagicCarpetDbContext.SaveChanges();
|
||||
return tour;
|
||||
}
|
||||
|
||||
private TourHistory InsertTourHistoryToDatabaseAndReturn(string tourId, double price, DateTime changeDate)
|
||||
{
|
||||
var tourHistory = new TourHistory() { Id = Guid.NewGuid().ToString(), TourId = tourId, OldPrice = price, ChangeDate = changeDate };
|
||||
MagicCarpetDbContext.TourHistories.Add(tourHistory);
|
||||
MagicCarpetDbContext.SaveChanges();
|
||||
return tourHistory;
|
||||
}
|
||||
|
||||
private static void AssertElement(TourDataModel? actual, Tour expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user