8 Commits
lab-4 ... lab-6

Author SHA1 Message Date
8fa02a428f lab5 ready 2025-04-25 01:55:16 +04:00
00a8846f33 some fix 2025-04-15 15:20:49 +04:00
c692f50d0d migration 2025-04-15 00:56:59 +04:00
e7dcfd6f30 fix 2025-04-15 00:49:00 +04:00
a3e1230e5c lab5 fix 2025-04-14 23:31:11 +04:00
8f5c38d239 lab5-ready 2025-04-14 23:25:14 +04:00
dbc3fb8394 Merge branch 'refs/heads/lab-4' into lab-5 2025-04-14 22:48:14 +04:00
6b7212a13d edit 2025-04-14 22:38:00 +04:00
77 changed files with 4015 additions and 264 deletions

View File

@@ -11,7 +11,9 @@
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="3.3.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.2" />
<PackageReference Include="PDFsharp-MigraDoc" Version="6.2.0-preview-3" />
</ItemGroup>
<ItemGroup>

View File

@@ -10,6 +10,7 @@ using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using CandyHouseContracts.BusinessLogicContracts;
namespace CandyHouseBusinessLogic.Implementations;

View File

@@ -0,0 +1,165 @@
using CandyHouseBusinessLogic.OfficePackage;
using CandyHouseContracts.BusinessLogicContracts;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Extensions;
using CandyHouseContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
namespace CandyHouseBusinessLogic.Implementations;
internal class ReportContract(
IProductStorageContract productStorageContract,
ISaleStorageContract saleStorageContract,
IClientDiscountStorageContract clientDiscountStorageContract,
BaseWordBuilder baseWordBuilder,
BaseExcelBuilder baseExcelBuilder,
BasePdfBuilder basePdfBuilder,
ILogger logger) : IReportContract
{
private readonly IProductStorageContract _productStorageContract = productStorageContract;
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
private readonly IClientDiscountStorageContract _clientDiscountStorageContract = clientDiscountStorageContract;
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 async Task<Stream> CreateDocumentProductHistoryPricesAsync(CancellationToken ct)
{
_logger.LogInformation("Create report ProductHistoryPrices");
var data = await GetDataByHistoryPricesAsync(ct);
return _baseWordBuilder
.AddHeader("История цен на продукцию")
.AddParagraph($"Сформировано на дату {DateTime.UtcNow}")
.AddTable([3000, 5000, 4000],
[
.. new List<string[]>() { documentHeader }.Union([
.. data.SelectMany(x =>
(new List<string[]>() { new string[] { x.ProductName, "", "" } }).Union(x.Prices.Select(y =>
new string[] { "", y.Split(" (")[0], y.Split(" (")[1].TrimEnd(')') })))
])
])
.Build();
}
public async Task<Stream> CreateDocumentSalesByPeriodAsync(DateTime dateStart, DateTime dateFinish,
CancellationToken ct)
{
_logger.LogInformation("Create report SalesByPeriod from {dateStart} to {dateFinish}", dateStart, dateFinish);
var data = await GetDataBySalesAsync(dateStart, dateFinish, ct) ??
throw new InvalidOperationException("No found data");
return _baseExcelBuilder
.AddHeader("Продажи за период", 0, 6)
.AddParagraph($"c {dateStart.ToShortDateString()} по {dateFinish.ToShortDateString()}", 2)
.AddTable([10, 10, 10, 10, 10, 10],
[
.. new List<string[]>() { tableHeader }.Union(data.SelectMany(x =>
(new List<string[]>()
{
new string[]
{
x.SaleDate.ToShortDateString(), x.Sum.ToString("N2"), x.Discount.ToString("N2"),
x.EmployeeFIO, "", ""
}
}).Union(x.Products!.Select(y => new string[]
{ "", "", "", "", y.ProductName, y.Count.ToString("N2") })).ToArray())).Union([
["Всего", data.Sum(x => x.Sum).ToString("N2"), data.Sum(x => x.Discount).ToString("N2"), "", "", ""]
])
])
.Build();
}
public async Task<Stream> CreateDocumentClientDiscountByPeriodAsync(DateTime dateStart, DateTime dateFinish,
CancellationToken ct)
{
_logger.LogInformation("Create report ClientDiscountByPeriod from {dateStart} to {dateFinish}", dateStart,
dateFinish);
var data = await GetDataByClientDiscountAsync(dateStart, dateFinish, ct) ??
throw new InvalidOperationException("No found data");
return _basePdfBuilder
.AddHeader("Скидочная ведомость")
.AddParagraph($"за период с {dateStart.ToShortDateString()} по {dateFinish.ToShortDateString()}")
.AddPieChart("Начисления", [.. data.Select(x => (x.ClientFIO, x.TotalDiscount))])
.Build();
}
public Task<List<ProductHistoryPricesDataModel>> GetDataProductHistoryPricesAsync(CancellationToken ct)
{
_logger.LogInformation("Get data ProductHistoryPrices");
return GetDataByHistoryPricesAsync(ct);
}
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<ClientDiscountByPeriodDataModel>> GetDataClientDiscountByPeriodAsync(DateTime dateStart,
DateTime dateFinish, CancellationToken ct)
{
_logger.LogInformation("Get data ClientDiscountByPeriod from {dateStart} to {dateFinish}", dateStart,
dateFinish);
return GetDataByClientDiscountAsync(dateStart, dateFinish, ct);
}
private async Task<List<ProductHistoryPricesDataModel>> GetDataByHistoryPricesAsync(CancellationToken ct) =>
[
.. (await _productStorageContract.GetListAsync(ct))
.Select(async product => new
{
ProductName = product.ProductName,
History = await Task.Run(() => _productStorageContract.GetHistoryByProductId(product.Id))
}).Select(t => t.Result).Select(x => new ProductHistoryPricesDataModel
{
ProductName = x.ProductName,
Prices =
[
.. x.History.OrderByDescending(h => h.ChangeDate)
.Select(h => $"{h.OldPrice:N2} ({h.ChangeDate:dd.MM.yyyy})")
]
})
];
private 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)];
}
private async Task<List<ClientDiscountByPeriodDataModel>> GetDataByClientDiscountAsync(DateTime dateStart,
DateTime dateFinish, CancellationToken ct)
{
if (dateStart.IsDateNotOlder(dateFinish))
{
throw new IncorrectDatesException(dateStart, dateFinish);
}
return
[
.. (await _clientDiscountStorageContract.GetListAsync(dateStart, dateFinish, ct)).GroupBy(x => x.ClientFIO)
.Select(x => new ClientDiscountByPeriodDataModel
{
ClientFIO = x.Key, TotalDiscount = x.Sum(y => y.DiscountAmount),
FromPeriod = x.Min(y => y.DiscountDate), ToPeriod = x.Max(y => y.DiscountDate)
}).OrderBy(x => x.ClientFIO)
];
}
}

View File

@@ -2,6 +2,8 @@
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Extensions;
using CandyHouseContracts.Infrastructure;
using CandyHouseContracts.Infrastructure.PostConfigurations;
using CandyHouseContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System;
@@ -12,13 +14,15 @@ using System.Threading.Tasks;
namespace CandyHouseBusinessLogic.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,
ManagerPostConfiguration cpc => CalculateSalaryForSuperManager(sales, startDate, finishDate, cpc),
BakerPostConfiguration 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 CalculateSalaryForSuperManager(List<SaleDataModel> sales, DateTime startDate, DateTime finishDate, ManagerPostConfiguration 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, BakerPostConfiguration 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;
}
}
}

View File

@@ -48,7 +48,7 @@ public class SaleBusinessLogicContract(ISaleStorageContract saleStorageContract,
public List<SaleDataModel> GetAllSalesByClientByPeriod(string clientId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {buyerId}, {fromDate}, {toDate}", clientId, fromDate, toDate);
_logger.LogInformation("GetAllSales params: {clientId}, {fromDate}, {toDate}", clientId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,18 @@
using CandyHouseContracts.AdapterContracts.OperationResponses;
namespace CandyHouseContracts.AdapterContracts;
public interface IReportAdapter
{
Task<ReportOperationResponse> GetDataProductHistoryPricesAsync(CancellationToken ct);
Task<ReportOperationResponse> GetDataSaleByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<ReportOperationResponse> GetDataClientDiscountByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<ReportOperationResponse> CreateDocumentProductHistoryPricesAsync(CancellationToken ct);
Task<ReportOperationResponse> CreateDocumentSalesByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<ReportOperationResponse> CreateDocumentClientDiscountByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
}

View File

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

View File

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

View File

@@ -1,11 +1,6 @@
using CandyHouseContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.BuisnessLogicContracts;
namespace CandyHouseContracts.BusinessLogicContracts;
public interface IProductBusinessLogicContract
{

View File

@@ -0,0 +1,19 @@
using CandyHouseContracts.DataModels;
namespace CandyHouseContracts.BusinessLogicContracts;
public interface IReportContract
{
Task<List<ProductHistoryPricesDataModel>> GetDataProductHistoryPricesAsync(CancellationToken ct);
Task<List<SaleDataModel>> GetDataSaleByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<List<ClientDiscountByPeriodDataModel>> GetDataClientDiscountByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<Stream> CreateDocumentProductHistoryPricesAsync(CancellationToken ct);
Task<Stream> CreateDocumentSalesByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<Stream> CreateDocumentClientDiscountByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
}

View File

@@ -0,0 +1,12 @@
namespace CandyHouseContracts.DataModels;
public class ClientDiscountByPeriodDataModel
{
public required string ClientFIO { get; set; }
public double TotalDiscount { get; set; }
public DateTime FromPeriod { get; set; }
public DateTime ToPeriod { get; set; }
}

View File

@@ -0,0 +1,35 @@
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Extensions;
using CandyHouseContracts.Infrastructure;
namespace CandyHouseContracts.DataModels;
public class ClientDiscountDataModel(string clientId, DateTime discountDate, double discountAmount) : IValidation
{
private readonly ClientDataModel? _client;
public string ClientId { get; private set; } = clientId;
public DateTime DiscountDate { get; private set; } = discountDate;
public double DiscountAmount { get; private set; } = discountAmount;
public string ClientFIO => _client?.FIO ?? string.Empty;
public ClientDiscountDataModel(string clientId, DateTime discountDate, double discountAmount, ClientDataModel client) : this(clientId, discountDate, discountAmount)
{
_client = client;
}
public void Validate()
{
if (ClientId.IsEmpty())
throw new ValidationException("Field ClientId is empty");
if (!ClientId.IsGuid())
throw new ValidationException("The value in the field ClientId is not a unique identifier");
if (DiscountAmount < 0)
throw new ValidationException("Field DiscountAmount in the field is less than 0");
}
}

View File

@@ -58,7 +58,7 @@ public class EmployeeDataModel(string id, string fio, string email, string postI
if (!PostId.IsGuid())
throw new ValidationException("The value in the field PostId is not a unique identifier");
if (BirthDate.Date > DateTime.Now.AddYears(-18).Date)
if (BirthDate.Date > DateTime.UtcNow.AddYears(-18).Date)
throw new ValidationException($"Only adults can be hired (BirthDate = {BirthDate.ToShortDateString()})");
if (EmploymentDate.Date < BirthDate.Date)

View File

@@ -2,6 +2,10 @@
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Extensions;
using CandyHouseContracts.Infrastructure;
using CandyHouseContracts.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 CandyHouseContracts.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(ManagerPostConfiguration) => JsonConvert.DeserializeObject<ManagerPostConfiguration>(configurationJson)!,
nameof(BakerPostConfiguration) => JsonConvert.DeserializeObject<BakerPostConfiguration>(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");
}
}

View File

@@ -0,0 +1,8 @@
namespace CandyHouseContracts.DataModels;
public class ProductHistoryPricesDataModel
{
public required string ProductName { get; set; }
public required List<string> Prices { get; set; }
}

View File

@@ -98,7 +98,7 @@ public class SaleDataModel : IValidation
throw new ValidationException("The value in the field EmployeeId is not a unique identifier");
if (!ClientId?.IsGuid() ?? !ClientId?.IsEmpty() ?? false)
throw new ValidationException("The value in the field BuyerId is not a unique identifier");
throw new ValidationException("The value in the field EmploeerId is not a unique identifier");
if (Sum <= 0)
throw new ValidationException("Field Sum is less than or equal to 0");

View File

@@ -10,6 +10,6 @@ public enum PostType
{
None = 0,
Manager = 1,
TravelAgent = 2,
Сhief = 3,
SuperManager = 2,
Baker = 3,
}

View File

@@ -0,0 +1,8 @@
namespace CandyHouseContracts.Infrastructure;
public interface IConfigurationSalary
{
double ExtraSaleSum { get; }
int MaxConcurrentThreads { get; }
}

View File

@@ -14,6 +14,8 @@ public class OperationResponse
protected HttpStatusCode StatusCode { get; set; }
protected object? Result { get; set; }
protected string? FileName { get; set; }
public IActionResult GetResponse(HttpRequest request, HttpResponse response)
{
@@ -26,13 +28,23 @@ public class OperationResponse
{
return new StatusCodeResult((int)StatusCode);
}
if (Result is Stream stream)
{
return new FileStreamResult(stream, "application/octet-stream")
{
FileDownloadName = FileName
};
}
return new ObjectResult(Result);
}
protected static TResult OK<TResult, TData>(TData data) where TResult : OperationResponse,
new() => new() { StatusCode = HttpStatusCode.OK, Result = data };
protected static TResult OK<TResult, TData>(TData data, string fileName) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.OK, Result = data, FileName = fileName };
protected static TResult NoContent<TResult>() where TResult : OperationResponse,
new() => new() { StatusCode = HttpStatusCode.NoContent };

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,12 @@
using CandyHouseContracts.DataModels;
namespace CandyHouseContracts.StoragesContracts;
public interface IClientDiscountStorageContract
{
List<ClientDiscountDataModel> GetList(DateTime startDate, DateTime endDate, string? clientId = null);
Task<List<ClientDiscountDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct);
void AddElement(ClientDiscountDataModel clientDiscountDataModel);
}

View File

@@ -23,4 +23,6 @@ public interface IEmployeeStorageContract
void UpdElement(EmployeeDataModel employeeDataModel);
void DelElement(string id);
int GetEmployeeTrend(DateTime fromPeriod, DateTime toPeriod);
}

View File

@@ -16,4 +16,5 @@ public interface IProductStorageContract
void AddElement(ProductDataModel productDataModel);
void UpdElement(ProductDataModel productDataModel);
void DelElement(string id);
Task<List<ProductDataModel>> GetListAsync(CancellationToken ct);
}

View File

@@ -17,4 +17,6 @@ public interface ISaleStorageContract
void AddElement(SaleDataModel saleDataModel);
void DelElement(string id);
Task<List<SaleDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct);
}

View File

@@ -0,0 +1,12 @@
namespace CandyHouseContracts.ViewModels;
public class ClientDiscountByPeriodViewModel
{
public required string ClientFIO { get; set; }
public double TotalDiscount { get; set; }
public DateTime FromPeriod { get; set; }
public DateTime ToPeriod { get; set; }
}

View File

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

View File

@@ -0,0 +1,8 @@
namespace CandyHouseContracts.ViewModels;
public class ProductHistoryPricesViewModel
{
public required string ProductName { get; set; }
public required List<string> Prices { get; set; }
}

View File

@@ -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>

View File

@@ -1,11 +1,10 @@
using CandyHouseContracts.Infrastructure;
using CandyHouseContracts.Infrastructure.PostConfigurations;
using CandyHouseDatabase.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace CandyHouseDatabase;
@@ -43,6 +42,12 @@ public class CandyHouseDbContext(IConfigurationDatabase configurationDatabase) :
.HasFilter($"\"{nameof(Post.IsActual)}\" = TRUE");
modelBuilder.Entity<SaleProduct>().HasKey(x => new { x.SaleId, x.ProductId });
modelBuilder.Entity<Post>()
.Property(x => x.Configuration)
.HasColumnType("jsonb")
.HasConversion(
x => SerializePostConfiguration(x),
x => DeserialzePostConfiguration(x));
}
public DbSet<Client> Clients { get; set; }
@@ -58,6 +63,14 @@ public class CandyHouseDbContext(IConfigurationDatabase configurationDatabase) :
public DbSet<Sale> Sales { get; set; }
public DbSet<SaleProduct> SaleProducts { get; set; }
public DbSet<ClientDiscount> ClientDiscounts { get; set; }
public DbSet<Employee> Employees { 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(ManagerPostConfiguration) => JsonConvert.DeserializeObject<ManagerPostConfiguration>(jsonString)!,
nameof(BakerPostConfiguration) => JsonConvert.DeserializeObject<BakerPostConfiguration>(jsonString)!,
_ => JsonConvert.DeserializeObject<PostConfiguration>(jsonString)!,
};
}

View File

@@ -0,0 +1,8 @@
using CandyHouseContracts.Infrastructure;
namespace CandyHouseDatabase;
class DefaultConfigurationDatabase : IConfigurationDatabase
{
public string ConnectionString => "";
}

View File

@@ -0,0 +1,79 @@
using AutoMapper;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.StoragesContracts;
using CandyHouseDatabase.Models;
using Microsoft.EntityFrameworkCore;
namespace CandyHouseDatabase.Implementations;
public class ClientDiscountStorageContract : IClientDiscountStorageContract
{
private readonly CandyHouseDbContext _dbContext;
private readonly Mapper _mapper;
public ClientDiscountStorageContract(CandyHouseDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Client, ClientDataModel>();
cfg.CreateMap<ClientDiscount, ClientDiscountDataModel>();
cfg.CreateMap<ClientDiscountDataModel, ClientDiscount>();
});
_mapper = new Mapper(config);
}
public List<ClientDiscountDataModel> GetList(DateTime startDate, DateTime endDate, string? clientId = null)
{
try
{
var query = _dbContext.ClientDiscounts.Include(x => x.Client).Where(x => x.DiscountDate >= startDate && x.DiscountDate <= endDate);
if (clientId is not null)
{
query = query.Where(x => x.ClientId == clientId);
}
return [.. query.Select(x => _mapper.Map<ClientDiscountDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public async Task<List<ClientDiscountDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct)
{
try
{
// Ensure dates are converted to UTC before comparison
var startDateUtc = startDate.ToUniversalTime();
var endDateUtc = endDate.ToUniversalTime();
return [.. await _dbContext.ClientDiscounts
.Include(x => x.Client)
.Where(x => x.DiscountDate >= startDateUtc && x.DiscountDate <= endDateUtc) // Use UTC dates
.Select(x => _mapper.Map<ClientDiscountDataModel>(x))
.ToListAsync(ct)];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(ClientDiscountDataModel clientDiscountDataModel)
{
try
{
_dbContext.ClientDiscounts.Add(_mapper.Map<ClientDiscount>(clientDiscountDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
}

View File

@@ -157,6 +157,21 @@ public class EmployeeStorageContract : IEmployeeStorageContract
}
}
public int GetEmployeeTrend(DateTime fromPeriod, DateTime toPeriod)
{
try
{
var countEmployeesOnBegining = _dbContext.Employees.Count(x => x.EmploymentDate < fromPeriod && (!x.IsDeleted || x.DateOfDelete > fromPeriod));
var countEmployeesOnEnding = _dbContext.Employees.Count(x => x.EmploymentDate < toPeriod && (!x.IsDeleted || x.DateOfDelete > toPeriod));
return countEmployeesOnEnding - countEmployeesOnBegining;
}
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)

View File

@@ -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);
}
@@ -93,12 +95,18 @@ public class PostStorageContract : IPostStorageContract
_dbContext.Posts.Add(_mapper.Map<Post>(postDataModel));
_dbContext.SaveChanges();
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
catch (DbUpdateException ex) when (ex.InnerException is PostgresException
{
ConstraintName: "IX_Posts_PostName_IsActual"
})
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostName", postDataModel.PostName);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostId_IsActual" })
catch (DbUpdateException ex) when (ex.InnerException is PostgresException
{
ConstraintName: "IX_Posts_PostId_IsActual"
})
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostId", postDataModel.Id);
@@ -122,6 +130,7 @@ public class PostStorageContract : IPostStorageContract
{
throw new ElementDeletedException(postDataModel.Id);
}
element.IsActual = false;
_dbContext.SaveChanges();
var newElement = _mapper.Map<Post>(postDataModel);
@@ -135,7 +144,10 @@ public class PostStorageContract : IPostStorageContract
throw;
}
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
catch (DbUpdateException ex) when (ex.InnerException is PostgresException
{
ConstraintName: "IX_Posts_PostName_IsActual"
})
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostName", postDataModel.PostName);
@@ -161,6 +173,7 @@ public class PostStorageContract : IPostStorageContract
{
throw new ElementDeletedException(id);
}
element.IsActual = false;
_dbContext.SaveChanges();
}
@@ -188,4 +201,4 @@ public class PostStorageContract : IPostStorageContract
private Post? GetPostById(string id) => _dbContext.Posts.Where(x => x.PostId == id)
.OrderByDescending(x => x.ChangeDate).FirstOrDefault();
}
}

View File

@@ -43,6 +43,19 @@ public class ProductStorageContract : IProductStorageContract
}
}
public async Task<List<ProductDataModel>> GetListAsync(CancellationToken ct)
{
try
{
return [.. await _dbContext.Products.Select(x => _mapper.Map<ProductDataModel>(x)).ToListAsync(ct)];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public List<ProductHistoryDataModel> GetHistoryByProductId(string productId)
{
try

View File

@@ -27,7 +27,7 @@ public class SaleStorageContract : ISaleStorageContract
cfg.CreateMap<Employee, EmployeeDataModel>();
cfg.CreateMap<SaleProduct, SaleProductDataModel>();
cfg.CreateMap<SaleProductDataModel, SaleProduct>()
.ForMember(x => x.Product, x => x.Ignore());
.ForMember(x => x.Product, x => x.Ignore());
cfg.CreateMap<Sale, SaleDataModel>();
cfg.CreateMap<SaleDataModel, Sale>()
.ForMember(x => x.IsCancel, x => x.MapFrom(src => false))
@@ -38,7 +38,8 @@ public class SaleStorageContract : ISaleStorageContract
_mapper = new Mapper(config);
}
public List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? employeeId = null, string? clientId = null, string? productId = null)
public List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? employeeId = null,
string? clientId = null, string? productId = null)
{
try
{
@@ -49,9 +50,11 @@ public class SaleStorageContract : ISaleStorageContract
.ThenInclude(d => d.Product)
.AsQueryable();
if (startDate.HasValue)
query = query.Where(x => x.SaleDate >= DateTime.SpecifyKind(startDate ?? DateTime.UtcNow, DateTimeKind.Utc));
query = query.Where(x =>
x.SaleDate >= DateTime.SpecifyKind(startDate ?? DateTime.UtcNow, DateTimeKind.Utc));
if (endDate.HasValue)
query = query.Where(x => x.SaleDate <= DateTime.SpecifyKind(endDate ?? DateTime.UtcNow, DateTimeKind.Utc));
query = query.Where(x =>
x.SaleDate <= DateTime.SpecifyKind(endDate ?? DateTime.UtcNow, DateTimeKind.Utc));
if (employeeId != null)
query = query.Where(x => x.EmployeeId == employeeId);
if (clientId != null)
@@ -104,6 +107,7 @@ public class SaleStorageContract : ISaleStorageContract
{
throw new ElementDeletedException(id);
}
element.IsCancel = true;
_dbContext.SaveChanges();
}
@@ -119,5 +123,30 @@ public class SaleStorageContract : ISaleStorageContract
}
}
private Sale? GetSaleById(string id) => _dbContext.Sales.Include(x => x.Client).Include(x => x.Employee).Include(x => x.SaleProducts)!.ThenInclude(x => x.Product).FirstOrDefault(x => x.Id == id);
}
public async Task<List<SaleDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct)
{
try
{
// Ensure dates are converted to UTC before comparison
var startDateUtc = startDate.ToUniversalTime();
var endDateUtc = endDate.ToUniversalTime();
return
[
.. await _dbContext.Sales.Include(x => x.Employee).Include(x => x.SaleProducts)!
.ThenInclude(x => x.Product)
.Where(x => x.SaleDate >= startDateUtc && x.SaleDate < endDateUtc) // Use UTC dates
.Select(x => _mapper.Map<SaleDataModel>(x)).ToListAsync(ct)
];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Sale? GetSaleById(string id) =>
_dbContext.Sales.Include(x => x.Client).Include(x => x.Employee).Include(x => x.SaleProducts)!
.ThenInclude(x => x.Product).FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,337 @@
// <auto-generated />
using System;
using CandyHouseDatabase;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace CandyHouseDataBase.Migrations
{
[DbContext(typeof(CandyHouseDbContext))]
[Migration("20250414205534_InitialCreate")]
partial class InitialCreate
{
/// <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("CandyHouseDatabase.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("CandyHouseDatabase.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("CandyHouseDatabase.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("CandyHouseDatabase.Models.Product", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<double>("Price")
.HasColumnType("double precision");
b.Property<string>("ProductDescription")
.HasColumnType("text");
b.Property<string>("ProductName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("ProductType")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ProductName")
.IsUnique();
b.ToTable("Products");
});
modelBuilder.Entity("CandyHouseDatabase.Models.ProductHistory", 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>("ProductId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ProductId");
b.ToTable("ProductHistories");
});
modelBuilder.Entity("CandyHouseDatabase.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("CandyHouseDatabase.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("CandyHouseDatabase.Models.SaleProduct", b =>
{
b.Property<string>("SaleId")
.HasColumnType("text");
b.Property<string>("ProductId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("SaleId", "ProductId");
b.HasIndex("ProductId");
b.ToTable("SaleProducts");
});
modelBuilder.Entity("CandyHouseDatabase.Models.ProductHistory", b =>
{
b.HasOne("CandyHouseDatabase.Models.Product", "Product")
.WithMany("ProductHistories")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
});
modelBuilder.Entity("CandyHouseDatabase.Models.Salary", b =>
{
b.HasOne("CandyHouseDatabase.Models.Employee", "Employee")
.WithMany("Salaries")
.HasForeignKey("EmployeeId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Employee");
});
modelBuilder.Entity("CandyHouseDatabase.Models.Sale", b =>
{
b.HasOne("CandyHouseDatabase.Models.Client", "Client")
.WithMany("Sales")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("CandyHouseDatabase.Models.Employee", "Employee")
.WithMany("Sales")
.HasForeignKey("EmployeeId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Client");
b.Navigation("Employee");
});
modelBuilder.Entity("CandyHouseDatabase.Models.SaleProduct", b =>
{
b.HasOne("CandyHouseDatabase.Models.Product", "Product")
.WithMany("SaleProducts")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CandyHouseDatabase.Models.Sale", "Sale")
.WithMany("SaleProducts")
.HasForeignKey("SaleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
b.Navigation("Sale");
});
modelBuilder.Entity("CandyHouseDatabase.Models.Client", b =>
{
b.Navigation("Sales");
});
modelBuilder.Entity("CandyHouseDatabase.Models.Employee", b =>
{
b.Navigation("Salaries");
b.Navigation("Sales");
});
modelBuilder.Entity("CandyHouseDatabase.Models.Product", b =>
{
b.Navigation("ProductHistories");
b.Navigation("SaleProducts");
});
modelBuilder.Entity("CandyHouseDatabase.Models.Sale", b =>
{
b.Navigation("SaleProducts");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,254 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace CandyHouseDataBase.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : 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),
DateOfDelete = table.Column<DateTime>(type: "timestamp with time zone", nullable: true)
},
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),
Configuration = table.Column<string>(type: "jsonb", 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: "Products",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
ProductName = table.Column<string>(type: "text", nullable: false),
ProductDescription = table.Column<string>(type: "text", nullable: true),
Price = table.Column<double>(type: "double precision", nullable: false),
ProductType = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Products", 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: "ProductHistories",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
ProductId = 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_ProductHistories", x => x.Id);
table.ForeignKey(
name: "FK_ProductHistories_Products_ProductId",
column: x => x.ProductId,
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "SaleProducts",
columns: table => new
{
SaleId = table.Column<string>(type: "text", nullable: false),
ProductId = 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_SaleProducts", x => new { x.SaleId, x.ProductId });
table.ForeignKey(
name: "FK_SaleProducts_Products_ProductId",
column: x => x.ProductId,
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_SaleProducts_Sales_SaleId",
column: x => x.SaleId,
principalTable: "Sales",
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_ProductHistories_ProductId",
table: "ProductHistories",
column: "ProductId");
migrationBuilder.CreateIndex(
name: "IX_Products_ProductName",
table: "Products",
column: "ProductName",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Salaries_EmployeeId",
table: "Salaries",
column: "EmployeeId");
migrationBuilder.CreateIndex(
name: "IX_SaleProducts_ProductId",
table: "SaleProducts",
column: "ProductId");
migrationBuilder.CreateIndex(
name: "IX_Sales_ClientId",
table: "Sales",
column: "ClientId");
migrationBuilder.CreateIndex(
name: "IX_Sales_EmployeeId",
table: "Sales",
column: "EmployeeId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Posts");
migrationBuilder.DropTable(
name: "ProductHistories");
migrationBuilder.DropTable(
name: "Salaries");
migrationBuilder.DropTable(
name: "SaleProducts");
migrationBuilder.DropTable(
name: "Products");
migrationBuilder.DropTable(
name: "Sales");
migrationBuilder.DropTable(
name: "Clients");
migrationBuilder.DropTable(
name: "Employees");
}
}
}

View File

@@ -0,0 +1,334 @@
// <auto-generated />
using System;
using CandyHouseDatabase;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace CandyHouseDataBase.Migrations
{
[DbContext(typeof(CandyHouseDbContext))]
partial class CandyHouseDbContextModelSnapshot : 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("CandyHouseDatabase.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("CandyHouseDatabase.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("CandyHouseDatabase.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("CandyHouseDatabase.Models.Product", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<double>("Price")
.HasColumnType("double precision");
b.Property<string>("ProductDescription")
.HasColumnType("text");
b.Property<string>("ProductName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("ProductType")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ProductName")
.IsUnique();
b.ToTable("Products");
});
modelBuilder.Entity("CandyHouseDatabase.Models.ProductHistory", 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>("ProductId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ProductId");
b.ToTable("ProductHistories");
});
modelBuilder.Entity("CandyHouseDatabase.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("CandyHouseDatabase.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("CandyHouseDatabase.Models.SaleProduct", b =>
{
b.Property<string>("SaleId")
.HasColumnType("text");
b.Property<string>("ProductId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("SaleId", "ProductId");
b.HasIndex("ProductId");
b.ToTable("SaleProducts");
});
modelBuilder.Entity("CandyHouseDatabase.Models.ProductHistory", b =>
{
b.HasOne("CandyHouseDatabase.Models.Product", "Product")
.WithMany("ProductHistories")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
});
modelBuilder.Entity("CandyHouseDatabase.Models.Salary", b =>
{
b.HasOne("CandyHouseDatabase.Models.Employee", "Employee")
.WithMany("Salaries")
.HasForeignKey("EmployeeId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Employee");
});
modelBuilder.Entity("CandyHouseDatabase.Models.Sale", b =>
{
b.HasOne("CandyHouseDatabase.Models.Client", "Client")
.WithMany("Sales")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("CandyHouseDatabase.Models.Employee", "Employee")
.WithMany("Sales")
.HasForeignKey("EmployeeId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Client");
b.Navigation("Employee");
});
modelBuilder.Entity("CandyHouseDatabase.Models.SaleProduct", b =>
{
b.HasOne("CandyHouseDatabase.Models.Product", "Product")
.WithMany("SaleProducts")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CandyHouseDatabase.Models.Sale", "Sale")
.WithMany("SaleProducts")
.HasForeignKey("SaleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
b.Navigation("Sale");
});
modelBuilder.Entity("CandyHouseDatabase.Models.Client", b =>
{
b.Navigation("Sales");
});
modelBuilder.Entity("CandyHouseDatabase.Models.Employee", b =>
{
b.Navigation("Salaries");
b.Navigation("Sales");
});
modelBuilder.Entity("CandyHouseDatabase.Models.Product", b =>
{
b.Navigation("ProductHistories");
b.Navigation("SaleProducts");
});
modelBuilder.Entity("CandyHouseDatabase.Models.Sale", b =>
{
b.Navigation("SaleProducts");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,14 @@
namespace CandyHouseDatabase.Models;
public class ClientDiscount
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string ClientId { get; set; }
public DateTime DiscountDate { get; set; }
public double DiscountAmount { get; set; }
public Client? Client { get; set; }
}

View File

@@ -18,22 +18,22 @@ 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; }
[NotMapped]
public Post? Post { get; set; }
[ForeignKey("EmployeeId")]
public List<Salary>? Salaries { get; set; }
[ForeignKey("EmployeeId")]
public List<Sale>? Sales { get; set; }
public DateTime? DateOfDelete { get; set; }
[NotMapped] public Post? Post { get; set; }
[ForeignKey("EmployeeId")] public List<Salary>? Salaries { get; set; }
[ForeignKey("EmployeeId")] public List<Sale>? Sales { get; set; }
public Employee AddPost(Post? post)
{
Post = post;
return this;
}
}
}

View File

@@ -1,10 +1,5 @@
using CandyHouseContracts.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CandyHouseContracts.Infrastructure.PostConfigurations;
namespace CandyHouseDatabase.Models;
@@ -14,7 +9,8 @@ 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; }
}

View File

@@ -0,0 +1,11 @@
using Microsoft.EntityFrameworkCore.Design;
namespace CandyHouseDatabase;
public class SampleContextFactory : IDesignTimeDbContextFactory<CandyHouseDbContext>
{
public CandyHouseDbContext CreateDbContext(string[] args)
{
return new CandyHouseDbContext(new DefaultConfigurationDatabase());
}
}

View File

@@ -0,0 +1,210 @@
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseDatabase.Implementations;
using CandyHouseDatabase.Models;
using CandyHouseTests.Infrastructure;
using CandyHouseTests.StoragesContracts;
namespace CandyHouseTests.BusinessLogicContractsTests;
[TestFixture]
internal class ClientStorageContractTests : BaseStorageContractTest
{
private ClientStorageContract _clientStorageContract;
[SetUp]
public void SetUp()
{
_clientStorageContract = new ClientStorageContract(CandyHouseDbContext);
}
[TearDown]
public void TearDown()
{
CandyHouseDbContext.RemoveSalesFromDatabase();
CandyHouseDbContext.RemoveEmployeesFromDatabase();
CandyHouseDbContext.RemoveClientsFromDatabase();
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var client = CandyHouseDbContext.InsertClientToDatabaseAndReturn(phoneNumber: "+5-555-555-55-55");
CandyHouseDbContext.InsertClientToDatabaseAndReturn(phoneNumber: "+6-666-666-66-66");
CandyHouseDbContext.InsertClientToDatabaseAndReturn(phoneNumber: "+7-777-777-77-77");
var list = _clientStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(x => x.Id == client.Id), client);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _clientStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_WhenDifferentConfigTypes_Test()
{
var clientBasic = CandyHouseDbContext.InsertClientToDatabaseAndReturn(phoneNumber: "+5-555-555-55-55");
var clientSilver =
CandyHouseDbContext.InsertClientToDatabaseAndReturn(phoneNumber: "+6-666-666-66-66", discountSize: 10);
var clientGolden =
CandyHouseDbContext.InsertClientToDatabaseAndReturn(phoneNumber: "+7-777-777-77-77", discountSize: 20);
var list = _clientStorageContract.GetList();
Assert.That(list, Is.Not.Null);
AssertElement(list.First(x => x.Id == clientBasic.Id), clientBasic);
AssertElement(list.First(x => x.Id == clientSilver.Id), clientSilver);
AssertElement(list.First(x => x.Id == clientGolden.Id), clientGolden);
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var client = CandyHouseDbContext.InsertClientToDatabaseAndReturn();
AssertElement(_clientStorageContract.GetElementById(client.Id), client);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
CandyHouseDbContext.InsertClientToDatabaseAndReturn();
Assert.That(() => _clientStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementByFIO_WhenHaveRecord_Test()
{
var client = CandyHouseDbContext.InsertClientToDatabaseAndReturn();
AssertElement(_clientStorageContract.GetElementByFIO(client.FIO), client);
}
[Test]
public void Try_GetElementByFIO_WhenNoRecord_Test()
{
CandyHouseDbContext.InsertClientToDatabaseAndReturn();
Assert.That(() => _clientStorageContract.GetElementByFIO("New Fio"), Is.Null);
}
[Test]
public void Try_GetElementByPhoneNumber_WhenHaveRecord_Test()
{
var client = CandyHouseDbContext.InsertClientToDatabaseAndReturn();
AssertElement(_clientStorageContract.GetElementByPhoneNumber(client.PhoneNumber), client);
}
[Test]
public void Try_GetElementByPhoneNumber_WhenNoRecord_Test()
{
CandyHouseDbContext.InsertClientToDatabaseAndReturn();
Assert.That(() => _clientStorageContract.GetElementByPhoneNumber("+8-888-888-88-88"), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var client = CreateModel(Guid.NewGuid().ToString());
_clientStorageContract.AddElement(client);
AssertElement(CandyHouseDbContext.GetClientFromDatabase(client.Id), client);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
{
var client = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55", 10);
CandyHouseDbContext.InsertClientToDatabaseAndReturn(client.Id);
Assert.That(() => _clientStorageContract.AddElement(client), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSamePhoneNumber_Test()
{
var client = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55", 10);
CandyHouseDbContext.InsertClientToDatabaseAndReturn(phoneNumber: client.PhoneNumber);
Assert.That(() => _clientStorageContract.AddElement(client), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_Test()
{
var client = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55", 10);
CandyHouseDbContext.InsertClientToDatabaseAndReturn(client.Id);
_clientStorageContract.UpdElement(client);
AssertElement(CandyHouseDbContext.GetClientFromDatabase(client.Id), client);
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _clientStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())),
Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_Test()
{
var client = CandyHouseDbContext.InsertClientToDatabaseAndReturn();
_clientStorageContract.DelElement(client.Id);
Assert.That(CandyHouseDbContext.GetClientFromDatabase(client.Id), Is.Null);
}
[Test]
public void Try_DelElement_WhenHaveSalesByThisClient_Test()
{
var client = CandyHouseDbContext.InsertClientToDatabaseAndReturn();
var worker = CandyHouseDbContext.InsertEmployeeToDatabaseAndReturn();
CandyHouseDbContext.InsertSaleToDatabaseAndReturn(worker.Id, client.Id);
CandyHouseDbContext.InsertSaleToDatabaseAndReturn(worker.Id, client.Id);
var salesBeforeDelete = CandyHouseDbContext.GetSalesByClientId(client.Id);
_clientStorageContract.DelElement(client.Id);
var element = CandyHouseDbContext.GetClientFromDatabase(client.Id);
var salesAfterDelete = CandyHouseDbContext.GetSalesByClientId(client.Id);
var salesNoClients = CandyHouseDbContext.GetSalesByClientId(null);
Assert.Multiple(() =>
{
Assert.That(element, Is.Null);
Assert.That(salesBeforeDelete, Has.Length.EqualTo(2));
Assert.That(salesAfterDelete, Is.Empty);
Assert.That(salesNoClients, Has.Length.EqualTo(2));
});
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _clientStorageContract.DelElement(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
}
private static void AssertElement(ClientDataModel? actual, Client expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
Assert.That(actual.PhoneNumber, Is.EqualTo(expected.PhoneNumber));
Assert.That(actual.DiscountSize, Is.EqualTo(expected.DiscountSize));
});
}
private static ClientDataModel CreateModel(string id, string fio = "test", string phoneNumber = "+7-777-777-77-77",
double discountSize = 10)
=> new(id, fio, phoneNumber, discountSize);
private static void AssertElement(Client? actual, ClientDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
Assert.That(actual.PhoneNumber, Is.EqualTo(expected.PhoneNumber));
Assert.That(actual.DiscountSize, Is.EqualTo(expected.DiscountSize));
});
}
}

View File

@@ -37,9 +37,9 @@ internal class EmployeeBusinessLogicContractTests
//Arrange
var listOriginal = new List<EmployeeDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 1", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false),
new(Guid.NewGuid().ToString(), "fio 2", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, true),
new(Guid.NewGuid().ToString(), "fio 3", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false),
};
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
@@ -101,9 +101,9 @@ internal class EmployeeBusinessLogicContractTests
var postId = Guid.NewGuid().ToString();
var listOriginal = new List<EmployeeDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 1", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false),
new(Guid.NewGuid().ToString(), "fio 2", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, true),
new(Guid.NewGuid().ToString(), "fio 3", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false),
};
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
@@ -182,9 +182,9 @@ internal class EmployeeBusinessLogicContractTests
var date = DateTime.UtcNow;
var listOriginal = new List<EmployeeDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 1", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false),
new(Guid.NewGuid().ToString(), "fio 2", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, true),
new(Guid.NewGuid().ToString(), "fio 3", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false),
};
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
@@ -258,9 +258,9 @@ internal class EmployeeBusinessLogicContractTests
var date = DateTime.UtcNow;
var listOriginal = new List<EmployeeDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 1", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false),
new(Guid.NewGuid().ToString(), "fio 2", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, true),
new(Guid.NewGuid().ToString(), "fio 3", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false),
};
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
@@ -332,7 +332,7 @@ internal class EmployeeBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new EmployeeDataModel(id, "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false);
var record = new EmployeeDataModel(id, "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false);
_employeeStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _employeeBusinessLogicContract.GetEmployeeByData(id);
@@ -347,7 +347,7 @@ internal class EmployeeBusinessLogicContractTests
{
//Arrange
var fio = "fio";
var record = new EmployeeDataModel(Guid.NewGuid().ToString(), fio, "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false);
var record = new EmployeeDataModel(Guid.NewGuid().ToString(), fio, "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false);
_employeeStorageContract.Setup(x => x.GetElementByFIO(fio)).Returns(record);
//Act
var element = _employeeBusinessLogicContract.GetEmployeeByData(fio);
@@ -362,7 +362,7 @@ internal class EmployeeBusinessLogicContractTests
{
//Arrange
var email = "123@gmail.com";
var record = new EmployeeDataModel(Guid.NewGuid().ToString(), "fio", email, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false);
var record = new EmployeeDataModel(Guid.NewGuid().ToString(), "fio", email, Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false);
_employeeStorageContract.Setup(x => x.GetElementByEmail(email)).Returns(record);
//Act
var element = _employeeBusinessLogicContract.GetEmployeeByData(email);
@@ -427,7 +427,7 @@ internal class EmployeeBusinessLogicContractTests
{
//Arrange
var flag = false;
var record = new EmployeeDataModel(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false);
var record = new EmployeeDataModel(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false);
_employeeStorageContract.Setup(x => x.AddElement(It.IsAny<EmployeeDataModel>()))
.Callback((EmployeeDataModel x) =>
{
@@ -447,7 +447,7 @@ internal class EmployeeBusinessLogicContractTests
//Arrange
_employeeStorageContract.Setup(x => x.AddElement(It.IsAny<EmployeeDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.InsertEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementExistsException>());
Assert.That(() => _employeeBusinessLogicContract.InsertEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false)), Throws.TypeOf<ElementExistsException>());
_employeeStorageContract.Verify(x => x.AddElement(It.IsAny<EmployeeDataModel>()), Times.Once);
}
@@ -463,7 +463,7 @@ internal class EmployeeBusinessLogicContractTests
public void InsertEmployee_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.InsertEmployee(new EmployeeDataModel("id", "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ValidationException>());
Assert.That(() => _employeeBusinessLogicContract.InsertEmployee(new EmployeeDataModel("id", "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false)), Throws.TypeOf<ValidationException>());
_employeeStorageContract.Verify(x => x.AddElement(It.IsAny<EmployeeDataModel>()), Times.Never);
}
@@ -473,7 +473,7 @@ internal class EmployeeBusinessLogicContractTests
//Arrange
_employeeStorageContract.Setup(x => x.AddElement(It.IsAny<EmployeeDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.InsertEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>());
Assert.That(() => _employeeBusinessLogicContract.InsertEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false)), Throws.TypeOf<StorageException>());
_employeeStorageContract.Verify(x => x.AddElement(It.IsAny<EmployeeDataModel>()), Times.Once);
}
@@ -482,7 +482,7 @@ internal class EmployeeBusinessLogicContractTests
{
//Arrange
var flag = false;
var record = new EmployeeDataModel(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false);
var record = new EmployeeDataModel(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false);
_employeeStorageContract.Setup(x => x.UpdElement(It.IsAny<EmployeeDataModel>()))
.Callback((EmployeeDataModel x) =>
{
@@ -502,7 +502,7 @@ internal class EmployeeBusinessLogicContractTests
//Arrange
_employeeStorageContract.Setup(x => x.UpdElement(It.IsAny<EmployeeDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.UpdateEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementNotFoundException>());
Assert.That(() => _employeeBusinessLogicContract.UpdateEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false)), Throws.TypeOf<ElementNotFoundException>());
_employeeStorageContract.Verify(x => x.UpdElement(It.IsAny<EmployeeDataModel>()), Times.Once);
}
@@ -518,7 +518,7 @@ internal class EmployeeBusinessLogicContractTests
public void UpdateEmployee_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.UpdateEmployee(new EmployeeDataModel("id", "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ValidationException>());
Assert.That(() => _employeeBusinessLogicContract.UpdateEmployee(new EmployeeDataModel("id", "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false)), Throws.TypeOf<ValidationException>());
_employeeStorageContract.Verify(x => x.UpdElement(It.IsAny<EmployeeDataModel>()), Times.Never);
}
@@ -528,7 +528,7 @@ internal class EmployeeBusinessLogicContractTests
//Arrange
_employeeStorageContract.Setup(x => x.UpdElement(It.IsAny<EmployeeDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.UpdateEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>());
Assert.That(() => _employeeBusinessLogicContract.UpdateEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false)), Throws.TypeOf<StorageException>());
_employeeStorageContract.Verify(x => x.UpdElement(It.IsAny<EmployeeDataModel>()), Times.Once);
}

View File

@@ -2,6 +2,7 @@
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Infrastructure.PostConfigurations;
using CandyHouseContracts.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.SuperManager, new PostConfiguration() { Rate = 10 }),
new(Guid.NewGuid().ToString(), "name 2", PostType.SuperManager, new PostConfiguration() { Rate = 10 }),
new(Guid.NewGuid().ToString(), "name 3", PostType.SuperManager, 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.SuperManager, new PostConfiguration() { Rate = 10 }),
new(postId, "name 2", PostType.SuperManager, 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.SuperManager, 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.SuperManager, 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.SuperManager, 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.SuperManager, 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.SuperManager, 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.SuperManager, 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.SuperManager, 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.SuperManager, 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.SuperManager, 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.SuperManager, 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.SuperManager, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}

View File

@@ -0,0 +1,446 @@
using CandyHouseBusinessLogic.Implementations;
using CandyHouseBusinessLogic.OfficePackage;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
namespace CandyHouseTests.BusinessLogicContractsTests;
[TestFixture]
internal class ReportContractTests
{
private ReportContract _reportContract;
private Mock<IProductStorageContract> _productStorageContract;
private Mock<ISaleStorageContract> _saleStorageContract;
private Mock<IClientDiscountStorageContract> _clientDiscountStorageContract;
private Mock<BaseWordBuilder> _baseWordBuilder;
private Mock<BaseExcelBuilder> _baseExcelBuilder;
private Mock<BasePdfBuilder> _basePdfBuilder;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_productStorageContract = new Mock<IProductStorageContract>();
_saleStorageContract = new Mock<ISaleStorageContract>();
_clientDiscountStorageContract = new Mock<IClientDiscountStorageContract>();
_baseWordBuilder = new Mock<BaseWordBuilder>();
_baseExcelBuilder = new Mock<BaseExcelBuilder>();
_basePdfBuilder = new Mock<BasePdfBuilder>();
_reportContract = new ReportContract(_productStorageContract.Object, _saleStorageContract.Object,
_clientDiscountStorageContract.Object, _baseWordBuilder.Object, _baseExcelBuilder.Object,
_basePdfBuilder.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_productStorageContract.Reset();
_saleStorageContract.Reset();
_clientDiscountStorageContract.Reset();
}
[Test]
public async Task GetDataProductHistoryPrices_ShouldSuccess_Test()
{
//Arrange
var product1 =
new ProductDataModel(Guid.NewGuid().ToString(), "Product 1", "descrption 1", 10, ProductType.Cake);
var product2 =
new ProductDataModel(Guid.NewGuid().ToString(), "Product 2", "desription 2", 20, ProductType.Cake);
_productStorageContract.Setup(x => x.GetListAsync(It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(new List<ProductDataModel> { product1, product2 }));
_productStorageContract.Setup(x => x.GetHistoryByProductId(product1.Id)).Returns(
new List<ProductHistoryDataModel>
{
new(product1.Id, 15, DateTime.UtcNow.AddDays(-2), product1),
new(product1.Id, 12, DateTime.UtcNow.AddDays(-1), product1)
});
_productStorageContract.Setup(x => x.GetHistoryByProductId(product2.Id)).Returns(
new List<ProductHistoryDataModel>
{
new(product2.Id, 25, DateTime.UtcNow.AddDays(-3), product2),
new(product2.Id, 22, DateTime.UtcNow.AddDays(-2), product2),
new(product2.Id, 18, DateTime.UtcNow.AddDays(-1), product2)
});
//Act
var data = await _reportContract.GetDataProductHistoryPricesAsync(CancellationToken.None);
//Assert
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(2));
Assert.Multiple(() =>
{
Assert.That(data.First(x => x.ProductName == product1.ProductName).Prices, Has.Count.EqualTo(2));
Assert.That(data.First(x => x.ProductName == product2.ProductName).Prices, Has.Count.EqualTo(3));
});
_productStorageContract.Verify(x => x.GetListAsync(It.IsAny<CancellationToken>()), Times.Once);
_productStorageContract.Verify(x => x.GetHistoryByProductId(product1.Id), Times.Once);
_productStorageContract.Verify(x => x.GetHistoryByProductId(product2.Id), Times.Once);
}
[Test]
public async Task GetDataProductHistoryPrices_WhenNoRecords_ShouldSuccess_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetListAsync(It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(new List<ProductDataModel>()));
//Act
var data = await _reportContract.GetDataProductHistoryPricesAsync(CancellationToken.None);
//Assert
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(0));
_productStorageContract.Verify(x => x.GetListAsync(It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public void GetDataProductHistoryPrices_WhenStorageThrowError_ShouldFail_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetListAsync(It.IsAny<CancellationToken>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(async () => await _reportContract.GetDataProductHistoryPricesAsync(CancellationToken.None),
Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.GetListAsync(It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public async Task GetDataSalesByPeriod_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(), null, DiscountType.RegularCustomer, false,
[new SaleProductDataModel("", Guid.NewGuid().ToString(), 10, 10)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.RegularCustomer, false,
[new SaleProductDataModel("", Guid.NewGuid().ToString(), 10, 10)])
}));
//Act
var data = await _reportContract.GetDataSaleByPeriodAsync(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 GetDataSalesByPeriod_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.GetDataSaleByPeriodAsync(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 GetDataSalesByPeriod_WhenIncorrectDates_ShouldFail_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(async () => await _reportContract.GetDataSaleByPeriodAsync(date, date, CancellationToken.None),
Throws.TypeOf<IncorrectDatesException>());
Assert.That(
async () => await _reportContract.GetDataSaleByPeriodAsync(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.GetDataSaleByPeriodAsync(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 GetDataClientDiscountByPeriod_ShouldSuccess_Test()
{
//Arrange
var startDate = DateTime.UtcNow.AddDays(-20);
var endDate = DateTime.UtcNow.AddDays(5);
var client1 = new ClientDataModel(Guid.NewGuid().ToString(), "fio 1", "+7-111-111-11-13", 0.1d);
var client2 = new ClientDataModel(Guid.NewGuid().ToString(), "fio 2", "+7-111-111-11-15", 0.1d);
_clientDiscountStorageContract
.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(new List<ClientDiscountDataModel>()
{
new(client1.Id, DateTime.UtcNow.AddDays(-10), 100, client1),
new(client1.Id, endDate, 1000, client1),
new(client1.Id, startDate, 1000, client1),
new(client2.Id, DateTime.UtcNow.AddDays(-10), 100, client2),
new(client2.Id, DateTime.UtcNow.AddDays(-5), 200, client2)
}));
//Act
var data = await _reportContract.GetDataClientDiscountByPeriodAsync(DateTime.UtcNow.AddDays(-1),
DateTime.UtcNow, CancellationToken.None);
//Assert
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(2));
var client1Discount = data.First(x => x.ClientFIO == client1.FIO);
Assert.That(client1Discount, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(client1Discount.TotalDiscount, Is.EqualTo(2100));
Assert.That(client1Discount.FromPeriod, Is.EqualTo(startDate));
Assert.That(client1Discount.ToPeriod, Is.EqualTo(endDate));
});
var client2Discount = data.First(x => x.ClientFIO == client2.FIO);
Assert.That(client2Discount, Is.Not.Null);
Assert.That(client2Discount.TotalDiscount, Is.EqualTo(300));
_clientDiscountStorageContract.Verify(
x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public async Task GetDataClientDiscountByPeriod_WhenNoRecords_ShouldSuccess_Test()
{
//Arrange
_clientDiscountStorageContract
.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(new List<ClientDiscountDataModel>()));
//Act
var data = await _reportContract.GetDataClientDiscountByPeriodAsync(DateTime.UtcNow.AddDays(-1),
DateTime.UtcNow, CancellationToken.None);
//Assert
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(0));
_clientDiscountStorageContract.Verify(
x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public void GetDataClientDiscountByPeriod_WhenIncorrectDates_ShouldFail_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(
async () => await _reportContract.GetDataClientDiscountByPeriodAsync(date, date, CancellationToken.None),
Throws.TypeOf<IncorrectDatesException>());
Assert.That(
async () => await _reportContract.GetDataClientDiscountByPeriodAsync(date, DateTime.UtcNow.AddDays(-1),
CancellationToken.None), Throws.TypeOf<IncorrectDatesException>());
}
[Test]
public void GetDataClientDiscountByPeriod_WhenStorageThrowError_ShouldFail_Test()
{
//Arrange
_clientDiscountStorageContract
.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.GetDataClientDiscountByPeriodAsync(DateTime.UtcNow.AddDays(-1),
DateTime.UtcNow, CancellationToken.None), Throws.TypeOf<StorageException>());
_clientDiscountStorageContract.Verify(
x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public async Task CreateDocumentProductHistoryPrices_ShouldSuccess_Test()
{
//Arrange
var product1 = new ProductDataModel(Guid.NewGuid().ToString(), "Product 1", "description Product 1", 10,
ProductType.Cake);
var product2 = new ProductDataModel(Guid.NewGuid().ToString(), "Product 2", "description Product 2", 20,
ProductType.Cake);
_productStorageContract.Setup(x => x.GetListAsync(It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(new List<ProductDataModel> { product1, product2 }));
_productStorageContract.Setup(x => x.GetHistoryByProductId(product1.Id)).Returns(
new List<ProductHistoryDataModel>
{
new(product1.Id, 15, DateTime.UtcNow.AddDays(-2), product1),
new(product1.Id, 12, DateTime.UtcNow.AddDays(-1), product1)
});
_productStorageContract.Setup(x => x.GetHistoryByProductId(product2.Id)).Returns(
new List<ProductHistoryDataModel>
{
new(product2.Id, 25, DateTime.UtcNow.AddDays(-3), product2)
});
_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 = [];
string[] thirdRow = [];
_baseWordBuilder.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(_baseWordBuilder.Object);
//Act
var result = await _reportContract.CreateDocumentProductHistoryPricesAsync(CancellationToken.None);
//Assert
_productStorageContract.Verify(x => x.GetListAsync(It.IsAny<CancellationToken>()), Times.Once);
_baseWordBuilder.Verify(x => x.AddHeader(It.IsAny<string>()), Times.Once);
_baseWordBuilder.Verify(x => x.AddParagraph(It.IsAny<string>()), Times.Once);
_baseWordBuilder.Verify(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>()), Times.Once);
_baseWordBuilder.Verify(x => x.Build(), Times.Once);
Assert.Multiple(() =>
{
Assert.That(countRows, Is.EqualTo(6));
Assert.That(firstRow, Has.Length.EqualTo(3));
Assert.That(secondRow, Has.Length.EqualTo(3));
Assert.That(thirdRow, Has.Length.EqualTo(3));
});
Assert.Multiple(() =>
{
Assert.That(firstRow[0], Is.EqualTo("Продукт"));
Assert.That(firstRow[1], Is.EqualTo("Цена"));
Assert.That(firstRow[2], Is.EqualTo("Дата"));
Assert.That(secondRow[0], Is.EqualTo(product1.ProductName));
Assert.That(secondRow[1], Is.Empty);
Assert.That(secondRow[2], Is.Empty);
Assert.That(thirdRow[0], Is.Empty);
Assert.That(thirdRow[1], Is.EqualTo(12.ToString("N2")));
Assert.That(thirdRow[2], Is.EqualTo(DateTime.UtcNow.AddDays(-1).ToString("dd.MM.yyyy")));
});
}
[Test]
public async Task CreateDocumentSalesByPeriod_ShouldSuccess_Test()
{
var porduct1 =
new ProductDataModel(Guid.NewGuid().ToString(), "name 1", "description 1", 10, ProductType.Candy);
var porduct2 =
new ProductDataModel(Guid.NewGuid().ToString(), "name 2", "description 2", 10, ProductType.Candy);
_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 SaleProductDataModel("", porduct1.Id, 10, 10, porduct1),
new SaleProductDataModel("", porduct2.Id, 10, 10, porduct2)
]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.RegularCustomer, false,
[new SaleProductDataModel("", porduct2.Id, 10, 10, porduct2)])
}));
_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 = [];
_baseExcelBuilder.Setup(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>()))
.Callback((int[] widths, List<string[]> data) =>
{
countRows = data.Count;
firstRow = data[0];
secondRow = data[1];
})
.Returns(_baseExcelBuilder.Object);
//Act
var data = await _reportContract.CreateDocumentSalesByPeriodAsync(DateTime.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.That(secondRow[0], Is.EqualTo(DateTime.UtcNow.ToString("dd.MM.yyyy")));
Assert.That(secondRow[1], Is.EqualTo(200.ToString("N2")));
Assert.That(secondRow[2], Is.EqualTo(100.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 CreateDocumentClientDiscountByPeriod_ShouldeSuccess_Test()
{
//Arrange
var startDate = DateTime.UtcNow.AddDays(-20);
var endDate = DateTime.UtcNow.AddDays(5);
var client1 = new ClientDataModel(Guid.NewGuid().ToString(), "fio 1", "+7-111-111-11-13", 0.1d);
var client2 = new ClientDataModel(Guid.NewGuid().ToString(), "fio 2", "+7-111-111-11-15", 0.1d);
_clientDiscountStorageContract
.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(new List<ClientDiscountDataModel>()
{
new(client1.Id, DateTime.UtcNow.AddDays(-10), 100, client1),
new(client1.Id, endDate, 1000, client1),
new(client1.Id, startDate, 1000, client1),
new(client2.Id, DateTime.UtcNow.AddDays(-10), 100, client2),
new(client2.Id, DateTime.UtcNow.AddDays(-5), 200, client2)
}));
_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.CreateDocumentClientDiscountByPeriodAsync(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(client1.FIO));
Assert.That(firstRow.Item2, Is.EqualTo(2100));
Assert.That(secondRow.Item1, Is.EqualTo(client2.FIO));
Assert.That(secondRow.Item2, Is.EqualTo(300));
});
_clientDiscountStorageContract.Verify(
x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
_basePdfBuilder.Verify(x => x.AddHeader(It.IsAny<string>()), Times.Once);
_basePdfBuilder.Verify(x => x.AddParagraph(It.IsAny<string>()), Times.Once);
_basePdfBuilder.Verify(x => x.AddPieChart(It.IsAny<string>(), It.IsAny<List<(string, double)>>()), Times.Once);
_basePdfBuilder.Verify(x => x.Build(), Times.Once);
}
}

View File

@@ -2,7 +2,9 @@
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Infrastructure.PostConfigurations;
using CandyHouseContracts.StoragesContracts;
using CandyHouseTests.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 CandyHouseTests.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 SaleProductDataModel(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.SuperManager, 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.SuperManager, 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.SuperManager, 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.SuperManager, 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.SuperManager, 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.SuperManager, 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.SuperManager, 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_WithSuperManagerPostConfiguration_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 SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]),
new(Guid.NewGuid().ToString(), employeeId, null, DiscountType.None, false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]),
new(Guid.NewGuid().ToString(), employeeId, null, DiscountType.None, false, [new SaleProductDataModel(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.SuperManager, new ManagerPostConfiguration() { 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 SaleProductDataModel(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.SuperManager, new BakerPostConfiguration() { 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));
}
}

View File

@@ -58,14 +58,14 @@ internal class ClientDataModelTests
var fio = "Fio";
var phoneNumber = "+7-777-777-77-77";
var discountSize = 11;
var buyer = CreateDataModel(clientId, fio, phoneNumber, discountSize);
Assert.That(() => buyer.Validate(), Throws.Nothing);
var client = CreateDataModel(clientId, fio, phoneNumber, discountSize);
Assert.That(() => client.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(buyer.Id, Is.EqualTo(clientId));
Assert.That(buyer.FIO, Is.EqualTo(fio));
Assert.That(buyer.PhoneNumber, Is.EqualTo(phoneNumber));
Assert.That(buyer.DiscountSize, Is.EqualTo(discountSize));
Assert.That(client.Id, Is.EqualTo(clientId));
Assert.That(client.FIO, Is.EqualTo(fio));
Assert.That(client.PhoneNumber, Is.EqualTo(phoneNumber));
Assert.That(client.DiscountSize, Is.EqualTo(discountSize));
});
}

View File

@@ -14,73 +14,73 @@ internal class EmployeeDataModelTests
[Test]
public void IdIsNullOrEmptyTest()
{
var employee = CreateDataModel(null, "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
var employee = CreateDataModel(null, "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
employee = CreateDataModel(string.Empty, "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
employee = CreateDataModel(string.Empty, "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var employee = CreateDataModel("id", "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
var employee = CreateDataModel("id", "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void FIOIsNullOrEmptyTest()
{
var employee = CreateDataModel(Guid.NewGuid().ToString(), null, "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
var employee = CreateDataModel(Guid.NewGuid().ToString(), null, "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
employee = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
employee = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void EmailIsNullOrEmptyTest()
{
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", null, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", null, Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", string.Empty, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", string.Empty, Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void EmailIsIncorrectTest()
{
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostIdIsNullOrEmptyTest()
{
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", null, DateTime.Now.AddYears(-18), DateTime.Now, false);
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", null, DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", string.Empty, DateTime.Now.AddYears(-18), DateTime.Now, false);
employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", string.Empty, DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostIdIsNotGuidTest()
{
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", "postId", DateTime.Now.AddYears(-18), DateTime.Now, false);
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", "postId", DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void BirthDateIsNotCorrectTest()
{
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(1), DateTime.Now, false);
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-16).AddDays(1), DateTime.UtcNow, false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void BirthDateAndEmploymentDateIsNotCorrectTest()
{
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now.AddYears(-18).AddDays(-1), false);
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18), DateTime.UtcNow.AddYears(-18).AddDays(-1), false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now.AddYears(-16), false);
employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18), DateTime.UtcNow.AddYears(-16), false);
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
}
@@ -91,8 +91,8 @@ internal class EmployeeDataModelTests
var fio = "fio";
var employeeEmail = "abc@gmail.com";
var postId = Guid.NewGuid().ToString();
var birthDate = DateTime.Now.AddYears(-18).AddDays(-1);
var employmentDate = DateTime.Now;
var birthDate = DateTime.UtcNow.AddYears(-18).AddDays(-1);
var employmentDate = DateTime.UtcNow;
var isDelete = false;
var employee = CreateDataModel(employeeId, fio, employeeEmail, postId, birthDate, employmentDate, isDelete);
Assert.That(() => employee.Validate(), Throws.Nothing);

View File

@@ -1,11 +1,7 @@
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using CandyHouseContracts.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CandyHouseContracts.Infrastructure.PostConfigurations;
namespace CandyHouseTests.DataModelTests;
[TestFixture]
@@ -14,41 +10,48 @@ internal class PostDataModelTests
[Test]
public void IdIsNullOrEmptyTest()
{
var post = CreateDataModel(null, "name", PostType.Manager, 10);
var post = CreateDataModel(null, "name", PostType.SuperManager, 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.SuperManager, 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.SuperManager, 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.SuperManager, 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.SuperManager, 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.SuperManager, 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.SuperManager, new PostConfiguration() { Rate = 0 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.SuperManager, new PostConfiguration() { Rate = -10 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
@@ -58,18 +61,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);
}

View File

@@ -14,25 +14,25 @@ internal class SalaryDataModelTests
[Test]
public void EmployeeIdIsEmptyTest()
{
var salary = CreateDataModel(null, DateTime.Now, 10);
var salary = CreateDataModel(null, DateTime.UtcNow, 10);
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
salary = CreateDataModel(string.Empty, DateTime.Now, 10);
salary = CreateDataModel(string.Empty, DateTime.UtcNow, 10);
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void EmployeeIdIsNotGuidTest()
{
var salary = CreateDataModel("employeeId", DateTime.Now, 10);
var salary = CreateDataModel("employeeId", DateTime.UtcNow, 10);
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void SalaryIsLessOrZeroTest()
{
var salary = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0);
var salary = CreateDataModel(Guid.NewGuid().ToString(), DateTime.UtcNow, 0);
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
salary = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now, -10);
salary = CreateDataModel(Guid.NewGuid().ToString(), DateTime.UtcNow, -10);
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
}
@@ -40,7 +40,7 @@ internal class SalaryDataModelTests
public void AllFieldsIsCorrectTest()
{
var employeeId = Guid.NewGuid().ToString();
var salaryDate = DateTime.Now.AddDays(-3).AddMinutes(-5);
var salaryDate = DateTime.UtcNow.AddDays(-3).AddMinutes(-5);
var enployeeSalary = 10;
var salary = CreateDataModel(employeeId, salaryDate, enployeeSalary);
Assert.That(() => salary.Validate(), Throws.Nothing);

View File

@@ -1,4 +1,5 @@
using CandyHouseContracts.Enums;
using CandyHouseContracts.Infrastructure.PostConfigurations;
using CandyHouseDatabase;
using CandyHouseDatabase.Models;
using Microsoft.EntityFrameworkCore;
@@ -20,9 +21,9 @@ internal static class CandyHouseDbContextExtensions
return client;
}
public static Post InsertPostToDatabaseAndReturn(this CandyHouseDbContext 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 CandyHouseDbContext dbContext, string? id = null, string postName = "test", PostType postType = PostType.SuperManager, 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,13 +68,20 @@ internal static class CandyHouseDbContextExtensions
return sale;
}
public static Employee InsertEmployeeToDatabaseAndReturn(this CandyHouseDbContext 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 CandyHouseDbContext 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 ClientDiscount InsertClientDiscountToDatabaseAndReturn(this CandyHouseDbContext dbContext, string clientId, double discountAmount = 1, DateTime? discountDate = null)
{
var clientDiscount = new ClientDiscount() { ClientId = clientId, DiscountAmount = discountAmount, DiscountDate = discountDate ?? DateTime.UtcNow };
dbContext.ClientDiscounts.Add(clientDiscount);
dbContext.SaveChanges();
return clientDiscount;
}
public static Client? GetClientFromDatabase(this CandyHouseDbContext dbContext, string id) => dbContext.Clients.FirstOrDefault(x => x.Id == id);
@@ -90,6 +98,7 @@ internal static class CandyHouseDbContextExtensions
public static Sale[] GetSalesByClientId(this CandyHouseDbContext dbContext, string? clientId) => [.. dbContext.Sales.Include(x => x.SaleProducts).Where(x => x.ClientId == clientId)];
public static Employee? GetEmployeeFromDatabaseById(this CandyHouseDbContext dbContext, string id) => dbContext.Employees.FirstOrDefault(x => x.Id == id);
public static ClientDiscount[] GetClientDiscountsFromDatabaseByClientId(this CandyHouseDbContext dbContext, string id) => [.. dbContext.ClientDiscounts.Where(x => x.ClientId == id)];
public static void RemoveClientsFromDatabase(this CandyHouseDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Clients\" CASCADE;");
@@ -102,6 +111,7 @@ internal static class CandyHouseDbContextExtensions
public static void RemoveSalesFromDatabase(this CandyHouseDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Sales\" CASCADE;");
public static void RemoveEmployeesFromDatabase(this CandyHouseDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Employees\" CASCADE;");
public static void RemoveClientDiscountsFromDatabase(this CandyHouseDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"ClientDiscounts\" CASCADE;");
private static void ExecuteSqlRaw(this CandyHouseDbContext dbContext, string command) => dbContext.Database.ExecuteSqlRaw(command);
}

View File

@@ -0,0 +1,9 @@
using CandyHouseContracts.Infrastructure;
namespace CandyHouseTests.Infrastructure;
class ConfigurationSalaryTest : IConfigurationSalary
{
public double ExtraSaleSum => 10;
public int MaxConcurrentThreads => 4;
}

View File

@@ -149,7 +149,7 @@ internal class ClientStorageContractTests : BaseStorageContractTest
}
[Test]
public void Try_DelElement_WhenHaveSalesByThisBuyer_Test()
public void Try_DelElement_WhenHaveSalesByThisEmploeer_Test()
{
var client = InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
var employeeId = Guid.NewGuid().ToString();

View File

@@ -0,0 +1,332 @@
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Infrastructure.PostConfigurations;
using CandyHouseDatabase.Implementations;
using CandyHouseDatabase.Models;
using CandyHouseTests.Infrastructure;
using CandyHouseTests.StoragesContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseTests.StoragesContracts;
[TestFixture]
internal class PostStorageContractTests : BaseStorageContractTest
{
private PostStorageContract _postStorageContract;
[SetUp]
public void SetUp()
{
_postStorageContract = new PostStorageContract(CandyHouseDbContext);
}
[TearDown]
public void TearDown()
{
CandyHouseDbContext.RemovePostsFromDatabase();
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn(postName: "name 1");
CandyHouseDbContext.InsertPostToDatabaseAndReturn(postName: "name 2");
CandyHouseDbContext.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 = CandyHouseDbContext.InsertPostToDatabaseAndReturn(postName: "name 1");
var postBuilder = CandyHouseDbContext.InsertPostToDatabaseAndReturn(postName: "name 2", config: new ManagerPostConfiguration() { SalePercent = 500 });
var postLoader = CandyHouseDbContext.InsertPostToDatabaseAndReturn(postName: "name 3", config: new BakerPostConfiguration() { 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();
CandyHouseDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
CandyHouseDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
CandyHouseDbContext.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();
CandyHouseDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
CandyHouseDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
CandyHouseDbContext.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 = CandyHouseDbContext.InsertPostToDatabaseAndReturn();
AssertElement(_postStorageContract.GetElementById(post.PostId), post);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
CandyHouseDbContext.InsertPostToDatabaseAndReturn();
Assert.That(() => _postStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementById_WhenRecordWasDeleted_Test()
{
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn(isActual: false);
Assert.That(() => _postStorageContract.GetElementById(post.PostId), Is.Null);
}
[Test]
public void Try_GetElementById_WhenTrySearchById_Test()
{
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn();
Assert.That(() => _postStorageContract.GetElementById(post.Id), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenHaveRecord_Test()
{
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn();
AssertElement(_postStorageContract.GetElementByName(post.PostName), post);
}
[Test]
public void Try_GetElementByName_WhenNoRecord_Test()
{
CandyHouseDbContext.InsertPostToDatabaseAndReturn();
Assert.That(() => _postStorageContract.GetElementByName("name"), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenRecordWasDeleted_Test()
{
var post = CandyHouseDbContext.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(CandyHouseDbContext.GetPostFromDatabaseByPostId(post.Id), post);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
{
var post = CreateModel(Guid.NewGuid().ToString(), "name unique");
CandyHouseDbContext.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());
CandyHouseDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: true);
Assert.That(() => _postStorageContract.AddElement(post), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_AddElement_WithSuperManagerPostConfiguration_Test()
{
var salePercent = 10;
var post = CreateModel(Guid.NewGuid().ToString(), config: new ManagerPostConfiguration() { SalePercent = salePercent });
_postStorageContract.AddElement(post);
var element = CandyHouseDbContext.GetPostFromDatabaseByPostId(post.Id);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(ManagerPostConfiguration).Name));
Assert.That((element.Configuration as ManagerPostConfiguration)!.SalePercent, Is.EqualTo(salePercent));
});
}
[Test]
public void Try_AddElement_WithChiefPostConfiguration_Test()
{
var trendPremium = 20;
var post = CreateModel(Guid.NewGuid().ToString(), config: new BakerPostConfiguration() { PersonalCountTrendPremium = trendPremium });
_postStorageContract.AddElement(post);
var element = CandyHouseDbContext.GetPostFromDatabaseByPostId(post.Id);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(BakerPostConfiguration).Name));
Assert.That((element.Configuration as BakerPostConfiguration)!.PersonalCountTrendPremium, Is.EqualTo(trendPremium));
});
}
[Test]
public void Try_UpdElement_Test()
{
var post = CreateModel(Guid.NewGuid().ToString());
CandyHouseDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: true);
_postStorageContract.UpdElement(post);
var posts = CandyHouseDbContext.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");
CandyHouseDbContext.InsertPostToDatabaseAndReturn(post.Id, postName: "name");
CandyHouseDbContext.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());
CandyHouseDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: false);
Assert.That(() => _postStorageContract.UpdElement(post), Throws.TypeOf<ElementDeletedException>());
}
[Test]
public void Try_UpdElement_WithSuperManagerPostConfiguration_Test()
{
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn();
var salePercent = 10;
_postStorageContract.UpdElement(CreateModel(post.PostId, config: new ManagerPostConfiguration() { SalePercent = salePercent }));
var element = CandyHouseDbContext.GetPostFromDatabaseByPostId(post.PostId);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(ManagerPostConfiguration).Name));
Assert.That((element.Configuration as ManagerPostConfiguration)!.SalePercent, Is.EqualTo(salePercent));
});
}
[Test]
public void Try_UpdElement_WithChiefPostConfiguration_Test()
{
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn();
var trendPremium = 20;
_postStorageContract.UpdElement(CreateModel(post.PostId, config: new BakerPostConfiguration() { PersonalCountTrendPremium = trendPremium }));
var element = CandyHouseDbContext.GetPostFromDatabaseByPostId(post.PostId);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(BakerPostConfiguration).Name));
Assert.That((element.Configuration as BakerPostConfiguration)!.PersonalCountTrendPremium, Is.EqualTo(trendPremium));
});
}
[Test]
public void Try_DelElement_Test()
{
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn(isActual: true);
_postStorageContract.DelElement(post.PostId);
Assert.That(CandyHouseDbContext.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 = CandyHouseDbContext.InsertPostToDatabaseAndReturn(isActual: false);
Assert.That(() => _postStorageContract.DelElement(post.PostId), Throws.TypeOf<ElementDeletedException>());
}
[Test]
public void Try_ResElement_Test()
{
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn(isActual: false);
_postStorageContract.ResElement(post.PostId);
var element = CandyHouseDbContext.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 = CandyHouseDbContext.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.SuperManager, 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));
});
}
}

View File

@@ -1,13 +1,16 @@
using CandyHouseContracts.BindingModels;
using CandyHouseContracts.Enums;
using CandyHouseContracts.Infrastructure.PostConfigurations;
using CandyHouseContracts.ViewModels;
using CandyHouseDatabase.Models;
using CandyHouseTests.Infrastructure;
using System.Text.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
namespace CandyHouseTests.WebApiControllersTests;
@@ -82,6 +85,24 @@ internal class PostControllerTests : BaseWebApiControllerTest
});
}
[Test]
public async Task GetRecords_WhenDifferentConfigTypes_ShouldSuccess_Test()
{
//Arrange
var postSimple = CandyHouseDbContext.InsertPostToDatabaseAndReturn(postName: "name 1");
var postSuperManager = CandyHouseDbContext.InsertPostToDatabaseAndReturn(postName: "name 2", config: new ManagerPostConfiguration() { SalePercent = 500 });
var postLoader = CandyHouseDbContext.InsertPostToDatabaseAndReturn(postName: "name 3", config: new BakerPostConfiguration() { PersonalCountTrendPremium = 20 });
//Act
var response = await HttpClient.GetAsync("/api/posts");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<PostViewModel>>(response);
Assert.That(data, Is.Not.Null);
AssertElement(data.First(x => x.Id == postSimple.PostId), postSimple);
AssertElement(data.First(x => x.Id == postSuperManager.PostId), postSuperManager);
AssertElement(data.First(x => x.Id == postLoader.PostId), postLoader);
}
[Test]
public async Task GetHistory_WhenWrongData_ShouldBadRequest_Test()
{
@@ -200,10 +221,10 @@ internal class PostControllerTests : BaseWebApiControllerTest
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
{
//Arrange
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.Manager.ToString(), Salary = 10 };
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Manager.ToString(), Salary = 10 };
var postModelWithPostTypeIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = string.Empty, Salary = 10 };
var postModelWithSalaryIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Manager.ToString(), Salary = -10 };
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.SuperManager.ToString(), ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.SuperManager.ToString(), ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
var postModelWithPostTypeIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = string.Empty, ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
var postModelWithSalaryIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.SuperManager.ToString(), ConfigurationJson = null };
//Act
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithIdIncorrect));
var responseWithNameIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithNameIncorrect));
@@ -237,6 +258,44 @@ internal class PostControllerTests : BaseWebApiControllerTest
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Post_WithSuperManagerPostConfiguration_ShouldSuccess_Test()
{
//Arrange
var salePercent = 10;
var postModel = CreateModel(configuration: JsonSerializer.Serialize(new ManagerPostConfiguration() { SalePercent = salePercent, Rate = 10 }));
//Act
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(postModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
var element = CandyHouseDbContext.GetPostFromDatabaseByPostId(postModel.Id!);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(ManagerPostConfiguration).Name));
Assert.That((element.Configuration as ManagerPostConfiguration)!.SalePercent, Is.EqualTo(salePercent));
});
}
[Test]
public async Task Post_WithLoaderPostConfiguration_ShouldSuccess_Test()
{
//Arrange
var trendPremium = 20;
var postModel = CreateModel(configuration: JsonSerializer.Serialize(new BakerPostConfiguration() { PersonalCountTrendPremium = trendPremium, Rate = 10 }));
//Act
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(postModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
var element = CandyHouseDbContext.GetPostFromDatabaseByPostId(postModel.Id!);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(BakerPostConfiguration).Name));
Assert.That((element.Configuration as BakerPostConfiguration)!.PersonalCountTrendPremium, Is.EqualTo(trendPremium));
});
}
[Test]
public async Task Put_ShouldSuccess_Test()
{
@@ -292,10 +351,10 @@ internal class PostControllerTests : BaseWebApiControllerTest
public async Task Put_WhenDataIsIncorrect_ShouldBadRequest_Test()
{
//Arrange
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.Manager.ToString(), Salary = 10 };
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Manager.ToString(), Salary = 10 };
var postModelWithPostTypeIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = string.Empty, Salary = 10 };
var postModelWithSalaryIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Manager.ToString(), Salary = -10 };
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.SuperManager.ToString(), ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.SuperManager.ToString(), ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
var postModelWithPostTypeIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = string.Empty, ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
var postModelWithSalaryIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.SuperManager.ToString(), ConfigurationJson = null };
//Act
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithIdIncorrect));
var responseWithNameIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithNameIncorrect));
@@ -329,6 +388,48 @@ internal class PostControllerTests : BaseWebApiControllerTest
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Put_WithSuperManagerPostConfiguration_ShouldSuccess_Test()
{
//Arrange
var salePercent = 10;
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn();
var postModel = CreateModel(post.PostId, configuration: JsonSerializer.Serialize(new ManagerPostConfiguration() { SalePercent = salePercent, Rate = 10 }));
//Act
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(postModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
CandyHouseDbContext.ChangeTracker.Clear();
var element = CandyHouseDbContext.GetPostFromDatabaseByPostId(postModel.Id!);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(ManagerPostConfiguration).Name));
Assert.That((element.Configuration as ManagerPostConfiguration)!.SalePercent, Is.EqualTo(salePercent));
});
}
[Test]
public async Task Put_WithSupervisorPostConfiguration_ShouldSuccess_Test()
{
//Arrange
var trendPremium = 20;
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn();
var postModel = CreateModel(post.PostId, configuration: JsonSerializer.Serialize(new BakerPostConfiguration() { PersonalCountTrendPremium = trendPremium, Rate = 10 }));
//Act
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(postModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
CandyHouseDbContext.ChangeTracker.Clear();
var element = CandyHouseDbContext.GetPostFromDatabaseByPostId(postModel.Id!);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(BakerPostConfiguration).Name));
Assert.That((element.Configuration as BakerPostConfiguration)!.PersonalCountTrendPremium, Is.EqualTo(trendPremium));
});
}
[Test]
public async Task Delete_ShouldSuccess_Test()
{
@@ -433,17 +534,17 @@ internal class PostControllerTests : BaseWebApiControllerTest
Assert.That(actual.Id, Is.EqualTo(expected.PostId));
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
Assert.That(actual.PostType, Is.EqualTo(expected.PostType.ToString()));
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
Assert.That(JsonNode.Parse(actual.Configuration)!["Type"]!.GetValue<string>(), Is.EqualTo(expected.Configuration.Type));
});
}
private static PostBindingModel CreateModel(string? postId = null, string postName = "name", PostType postType = PostType.Manager, double salary = 10)
private static PostBindingModel CreateModel(string? postId = null, string postName = "name", PostType postType = PostType.Manager, string? configuration = null)
=> new()
{
Id = postId ?? Guid.NewGuid().ToString(),
PostName = postName,
PostType = postType.ToString(),
Salary = salary
ConfigurationJson = configuration ?? JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 })
};
private static void AssertElement(Post? actual, PostBindingModel expected)
@@ -454,7 +555,7 @@ internal class PostControllerTests : BaseWebApiControllerTest
Assert.That(actual.PostId, Is.EqualTo(expected.Id));
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
Assert.That(actual.PostType.ToString(), Is.EqualTo(expected.PostType));
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
Assert.That(actual.Configuration.Type, Is.EqualTo(JsonNode.Parse(expected.ConfigurationJson!)!["Type"]!.GetValue<string>()));
});
}
}

View File

@@ -0,0 +1,218 @@
using System.Net;
using CandyHouseContracts.ViewModels;
using CandyHouseTests.Infrastructure;
namespace CandyHouseTests.WebApiControllersTests;
[TestFixture]
internal class ReportControllerTests : BaseWebApiControllerTest
{
[TearDown]
public void TearDown()
{
CandyHouseDbContext.RemoveClientDiscountsFromDatabase();
CandyHouseDbContext.RemoveSalesFromDatabase();
CandyHouseDbContext.RemoveClientsFromDatabase();
CandyHouseDbContext.RemoveProductsFromDatabase();
}
[Test]
public async Task GetProductHistoryPrices_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var product1 = CandyHouseDbContext.InsertProductToDatabaseAndReturn(productName: "Product 1", price: 10);
var product2 = CandyHouseDbContext.InsertProductToDatabaseAndReturn(productName: "Product 2", price: 20);
CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product1.Id, 17, DateTime.UtcNow.AddDays(-3));
CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product1.Id, 15, DateTime.UtcNow.AddDays(-2));
CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product1.Id, 12, DateTime.UtcNow.AddDays(-1));
CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product2.Id, 25, DateTime.UtcNow.AddDays(-4));
CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product2.Id, 26, DateTime.UtcNow.AddDays(-3));
//Act
var response = await HttpClient.GetAsync("/api/report/getproducthistoryprices");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<ProductHistoryPricesViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(data, Has.Count.EqualTo(2));
Assert.That(data.First(x => x.ProductName == product1.ProductName).Prices, Has.Count.EqualTo(3));
Assert.That(data.First(x => x.ProductName == product2.ProductName).Prices, Has.Count.EqualTo(2));
});
}
[Test]
public async Task GetSales_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var worker = CandyHouseDbContext.InsertEmployeeToDatabaseAndReturn();
var product1 = CandyHouseDbContext.InsertProductToDatabaseAndReturn(productName: "name 1");
var product2 = CandyHouseDbContext.InsertProductToDatabaseAndReturn(productName: "name 2");
CandyHouseDbContext.InsertSaleToDatabaseAndReturn(worker.Id,
products: [(product1.Id, 10, 1.1), (product2.Id, 10, 1.1)]);
CandyHouseDbContext.InsertSaleToDatabaseAndReturn(worker.Id, products: [(product1.Id, 10, 1.1)]);
//Act
var response = await HttpClient.GetAsync(
$"/api/report/getsales?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.Multiple(() => { Assert.That(data, Has.Count.EqualTo(2)); });
}
[Test]
public async Task GetSales_WhenDateIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync(
$"/api/report/getsales?fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task GetClientDiscount_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var client1 = CandyHouseDbContext.InsertClientToDatabaseAndReturn(fio: "fio 1", phoneNumber: "+5-555-555-55-55");
var client2 = CandyHouseDbContext.InsertClientToDatabaseAndReturn(fio: "fio 2", phoneNumber: "+5-555-555-57-56");
CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client1.Id, discountAmount: 100,
discountDate: DateTime.UtcNow.AddDays(-10));
CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client1.Id, discountAmount: 1000,
discountDate: DateTime.UtcNow.AddDays(-5));
CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client1.Id, discountAmount: 200,
discountDate: DateTime.UtcNow.AddDays(5));
CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client2.Id, discountAmount: 500,
discountDate: DateTime.UtcNow.AddDays(-5));
CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client2.Id, discountAmount: 300,
discountDate: DateTime.UtcNow.AddDays(-3));
//Act
var response = await HttpClient.GetAsync(
$"/api/report/GetClientDiscount?fromDate={DateTime.UtcNow.AddDays(-7):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<ClientDiscountByPeriodViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(2));
Assert.Multiple(() =>
{
Assert.That(data.First(x => x.ClientFIO == client1.FIO).TotalDiscount, Is.EqualTo(1000));
Assert.That(data.First(x => x.ClientFIO == client2.FIO).TotalDiscount, Is.EqualTo(800));
});
}
[Test]
public async Task GetClientDiscount_WhenDateIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync(
$"/api/report/GetClientDiscount?fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task LoadProductHistoryPrices_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var product1 = CandyHouseDbContext.InsertProductToDatabaseAndReturn(productName: "Product 1", price: 10);
var product2 = CandyHouseDbContext.InsertProductToDatabaseAndReturn(productName: "Product 2", price: 20);
CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product1.Id, 17, DateTime.UtcNow.AddDays(-3));
CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product1.Id, 15, DateTime.UtcNow.AddDays(-2));
CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product1.Id, 12, DateTime.UtcNow.AddDays(-1));
CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product2.Id, 25, DateTime.UtcNow.AddDays(-4));
CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product2.Id, 26, DateTime.UtcNow.AddDays(-3));
//Act
var response = await HttpClient.GetAsync("/api/report/LoadProductHistoryPrices");
//Assert
await AssertStreamAsync(response, "file.docx");
}
[Test]
public async Task LoadSales_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var worker = CandyHouseDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio_worker");
var product1 = CandyHouseDbContext.InsertProductToDatabaseAndReturn(productName: "name 1");
var product2 = CandyHouseDbContext.InsertProductToDatabaseAndReturn(productName: "name 2");
CandyHouseDbContext.InsertSaleToDatabaseAndReturn(worker.Id, sum: 60,
products: [(product1.Id, 10, 2), (product2.Id, 10, 4)]);
CandyHouseDbContext.InsertSaleToDatabaseAndReturn(worker.Id, sum: 20, products: [(product1.Id, 10, 2)]);
//Act
var response = await HttpClient.GetAsync(
$"/api/report/loadsales?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
await AssertStreamAsync(response, "file.xlsx");
}
[Test]
public async Task LoadSales_WhenDateIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync(
$"/api/report/loadsales?fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task LoadSalary_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var client1 = CandyHouseDbContext.InsertClientToDatabaseAndReturn(fio: "fio 1", phoneNumber: "+5-555-555-55-55");
var client2 = CandyHouseDbContext.InsertClientToDatabaseAndReturn(fio: "fio 2", phoneNumber: "+5-555-555-57-56");
CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client1.Id, discountAmount: 100,
discountDate: DateTime.UtcNow.AddDays(-10));
CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client1.Id, discountAmount: 1000,
discountDate: DateTime.UtcNow.AddDays(-5));
CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client1.Id, discountAmount: 200,
discountDate: DateTime.UtcNow.AddDays(5));
CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client2.Id, discountAmount: 500,
discountDate: DateTime.UtcNow.AddDays(-5));
CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client2.Id, discountAmount: 300,
discountDate: DateTime.UtcNow.AddDays(-3));
//Act
var response = await HttpClient.GetAsync(
$"/api/report/LoadClientDiscount?fromDate={DateTime.UtcNow.AddDays(-7):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
//Assert
await AssertStreamAsync(response, "file.pdf");
}
[Test]
public async Task LoadClientDiscount_WhenDateIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync(
$"/api/report/loadclientdiscount?fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
private static async Task AssertStreamAsync(HttpResponseMessage response, string fileNameForSave = "")
{
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
using var data = await response.Content.ReadAsStreamAsync();
Assert.That(data, Is.Not.Null);
Assert.That(data.Length, Is.GreaterThan(0));
await SaveStreamAsync(data, fileNameForSave);
}
private static async Task SaveStreamAsync(Stream stream, string fileName)
{
if (string.IsNullOrEmpty(fileName))
{
return;
}
var path = Path.Combine(Directory.GetCurrentDirectory(), fileName);
if (File.Exists(path))
{
File.Delete(path);
}
stream.Position = 0;
using var fileStream = new FileStream(path, FileMode.OpenOrCreate);
await stream.CopyToAsync(fileStream);
}
}

View File

@@ -151,29 +151,7 @@ internal class SalaryControllerTests : BaseWebApiControllerTest
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Calculate_ShouldSuccess_Test()
{
//Arrange
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn(salary: 1000);
var employee = CandyHouseDbContext.InsertEmployeeToDatabaseAndReturn(fio: "Иванов И.И.", postId: post.PostId);
var sale = CandyHouseDbContext.InsertSaleToDatabaseAndReturn(employee.Id);
var expectedSum = sale.Sum * 0.1 + post.Salary;
//Act
var response = await HttpClient.PostAsync($"/api/salary/calculate?date={DateTime.UtcNow:MM/dd/yyyy}", null);
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
var salaries = CandyHouseDbContext.GetSalariesFromDatabaseByEmployeeId(employee.Id);
Assert.Multiple(() =>
{
Assert.That(salaries, Has.Length.EqualTo(1));
Assert.That(salaries.First().EmployeeSalary, Is.EqualTo(expectedSum));
Assert.That(salaries.First().SalaryDate.Month, Is.EqualTo(DateTime.UtcNow.Month));
});
}
[Test]
public async Task Calculate_WithoutEmployees_ShouldSuccess_Test()
{
@@ -184,34 +162,4 @@ internal class SalaryControllerTests : BaseWebApiControllerTest
var salaries = CandyHouseDbContext.Salaries.ToArray();
Assert.That(salaries, Has.Length.EqualTo(0));
}
[Test]
public async Task Calculate_WithoutSalesByEmployee_ShouldSuccess_Test()
{
//Arrange
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn(salary: 1000);
var employee1 = CandyHouseDbContext.InsertEmployeeToDatabaseAndReturn(fio: "name 1", postId: post.PostId);
var employee2 = CandyHouseDbContext.InsertEmployeeToDatabaseAndReturn(fio: "name 2", postId: post.PostId);
var sale = CandyHouseDbContext.InsertSaleToDatabaseAndReturn(employee1.Id);
//Act
var response = await HttpClient.PostAsync($"/api/salary/calculate?date={DateTime.UtcNow:MM/dd/yyyy}", null);
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
var salary1 = CandyHouseDbContext.GetSalariesFromDatabaseByEmployeeId(employee1.Id).First().EmployeeSalary;
var salary2 = CandyHouseDbContext.GetSalariesFromDatabaseByEmployeeId(employee2.Id).First().EmployeeSalary;
Assert.That(salary1, Is.Not.EqualTo(salary2));
}
[Test]
public async Task Calculate_PostNotFound_ShouldNotFound_Test()
{
//Arrange
CandyHouseDbContext.InsertPostToDatabaseAndReturn();
var employee = CandyHouseDbContext.InsertEmployeeToDatabaseAndReturn(fio: "name", postId: Guid.NewGuid().ToString());
var sale = CandyHouseDbContext.InsertSaleToDatabaseAndReturn(employee.Id);
//Act
var response = await HttpClient.PostAsync($"/api/salary/calculate?date={DateTime.UtcNow:MM/dd/yyyy}", null);
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
}
}

View File

@@ -14,7 +14,7 @@
{
"Name": "File",
"Args": {
"path": "../logs/magiccarpet-.log",
"path": "../logs/candyhouse-.log",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {CorrelationId} {Level:u3} {Username} {Message:lj}{Exception}{NewLine}"
}

View File

@@ -6,6 +6,7 @@ using CandyHouseContracts.BuisnessLogicContracts;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.ViewModels;
using System.Text.Json;
namespace CandyHouseWebApi.Adapters;
@@ -17,6 +18,11 @@ public class PostAdapter : IPostAdapter
private readonly Mapper _mapper;
private readonly JsonSerializerOptions JsonSerializerOptions = new()
{
PropertyNameCaseInsensitive = true
};
public PostAdapter(IPostBusinessLogicContract postBusinessLogicContract, ILogger<PostAdapter> logger)
{
_postBusinessLogicContract = postBusinessLogicContract;
@@ -24,7 +30,9 @@ public class PostAdapter : IPostAdapter
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<PostBindingModel, PostDataModel>();
cfg.CreateMap<PostDataModel, PostViewModel>();
cfg.CreateMap<PostDataModel, PostViewModel>()
.ForMember(x => x.Configuration,
x => x.MapFrom(src => JsonSerializer.Serialize(src.ConfigurationModel, JsonSerializerOptions)));
});
_mapper = new Mapper(config);
}
@@ -33,7 +41,9 @@ public class PostAdapter : IPostAdapter
{
try
{
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllPosts().Select(x => _mapper.Map<PostViewModel>(x))]);
return PostOperationResponse.OK([
.. _postBusinessLogicContract.GetAllPosts().Select(x => _mapper.Map<PostViewModel>(x))
]);
}
catch (NullListException)
{
@@ -43,7 +53,8 @@ public class PostAdapter : IPostAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.InternalServerError(
$"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
@@ -56,7 +67,9 @@ public class PostAdapter : IPostAdapter
{
try
{
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllDataOfPost(id).Select(x => _mapper.Map<PostViewModel>(x))]);
return PostOperationResponse.OK([
.. _postBusinessLogicContract.GetAllDataOfPost(id).Select(x => _mapper.Map<PostViewModel>(x))
]);
}
catch (ArgumentNullException ex)
{
@@ -71,7 +84,8 @@ public class PostAdapter : IPostAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.InternalServerError(
$"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
@@ -104,7 +118,8 @@ public class PostAdapter : IPostAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.InternalServerError(
$"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
@@ -138,7 +153,8 @@ public class PostAdapter : IPostAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.BadRequest(
$"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
@@ -182,7 +198,8 @@ public class PostAdapter : IPostAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.BadRequest(
$"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
@@ -221,7 +238,8 @@ public class PostAdapter : IPostAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.BadRequest(
$"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
@@ -255,7 +273,8 @@ public class PostAdapter : IPostAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.BadRequest(
$"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
@@ -263,4 +282,4 @@ public class PostAdapter : IPostAdapter
return PostOperationResponse.InternalServerError(ex.Message);
}
}
}
}

View File

@@ -3,6 +3,7 @@ using CandyHouseContracts.AdapterContracts;
using CandyHouseContracts.AdapterContracts.OperationResponses;
using CandyHouseContracts.BindingModels;
using CandyHouseContracts.BuisnessLogicContracts;
using CandyHouseContracts.BusinessLogicContracts;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.ViewModels;

View File

@@ -0,0 +1,208 @@
using AutoMapper;
using CandyHouseContracts.AdapterContracts;
using CandyHouseContracts.AdapterContracts.OperationResponses;
using CandyHouseContracts.BusinessLogicContracts;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.ViewModels;
namespace CandyHouseWebApi.Adapters;
public class ReportAdapter : IReportAdapter
{
private readonly IReportContract _reportContract;
private readonly ILogger _logger;
private readonly Mapper _mapper;
public ReportAdapter(IReportContract reportContract, ILogger<ProductAdapter> logger)
{
_reportContract = reportContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<ProductHistoryPricesDataModel, ProductHistoryPricesViewModel>();
cfg.CreateMap<SaleDataModel, SaleViewModel>();
cfg.CreateMap<SaleProductDataModel, SaleProductViewModel>();
cfg.CreateMap<ClientDiscountByPeriodDataModel, ClientDiscountByPeriodViewModel>();
});
_mapper = new Mapper(config);
}
public async Task<ReportOperationResponse> GetDataProductHistoryPricesAsync(CancellationToken ct)
{
try
{
return ReportOperationResponse.OK([.. (await _reportContract.GetDataProductHistoryPricesAsync(ct)).Select(x => _mapper.Map<ProductHistoryPricesViewModel>(x))]);
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "InvalidOperationException");
var errorMessage = ex.InnerException?.Message ?? ex.Message;
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {errorMessage}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
var errorMessage = ex.InnerException?.Message ?? ex.Message;
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {errorMessage}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return ReportOperationResponse.InternalServerError(ex.Message);
}
}
public async Task<ReportOperationResponse> GetDataSaleByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
try
{
return ReportOperationResponse.OK((await _reportContract.GetDataSaleByPeriodAsync(dateStart, dateFinish, ct)).Select(x => _mapper.Map<SaleViewModel>(x)).ToList());
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "InvalidOperationException");
var errorMessage = ex.InnerException?.Message ?? ex.Message;
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {errorMessage}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
var errorMessage = ex.InnerException?.Message ?? ex.Message;
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {errorMessage}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return ReportOperationResponse.InternalServerError(ex.Message);
}
}
public async Task<ReportOperationResponse> GetDataClientDiscountByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
try
{
return ReportOperationResponse.OK((await _reportContract.GetDataClientDiscountByPeriodAsync(dateStart, dateFinish, ct)).Select(x => _mapper.Map<ClientDiscountByPeriodViewModel>(x)).ToList());
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "InvalidOperationException");
var errorMessage = ex.InnerException?.Message ?? ex.Message;
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {errorMessage}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
var errorMessage = ex.InnerException?.Message ?? ex.Message;
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {errorMessage}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return ReportOperationResponse.InternalServerError(ex.Message);
}
}
public async Task<ReportOperationResponse> CreateDocumentProductHistoryPricesAsync(CancellationToken ct)
{
try
{
return SendStream(await _reportContract.CreateDocumentProductHistoryPricesAsync(ct), "producthistoryprices.docx");
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "InvalidOperationException");
var errorMessage = ex.InnerException?.Message ?? ex.Message;
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {errorMessage}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
var errorMessage = ex.InnerException?.Message ?? ex.Message;
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {errorMessage}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return ReportOperationResponse.InternalServerError(ex.Message);
}
}
public async Task<ReportOperationResponse> CreateDocumentSalesByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
try
{
return SendStream(await _reportContract.CreateDocumentSalesByPeriodAsync(dateStart, dateFinish, ct), "sales.xslx");
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "InvalidOperationException");
var errorMessage = ex.InnerException?.Message ?? ex.Message;
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {errorMessage}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
var errorMessage = ex.InnerException?.Message ?? ex.Message;
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {errorMessage}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return ReportOperationResponse.InternalServerError(ex.Message);
}
}
public async Task<ReportOperationResponse> CreateDocumentClientDiscountByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
try
{
return SendStream(await _reportContract.CreateDocumentClientDiscountByPeriodAsync(dateStart, dateFinish, ct), "file.pdf");
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "InvalidOperationException");
var errorMessage = ex.InnerException?.Message ?? ex.Message;
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {errorMessage}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
var errorMessage = ex.InnerException?.Message ?? ex.Message;
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {errorMessage}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return ReportOperationResponse.InternalServerError(ex.Message);
}
}
private static ReportOperationResponse SendStream(Stream stream, string fileName)
{
stream.Position = 0;
return ReportOperationResponse.OK(stream, fileName);
}
}

View File

@@ -9,6 +9,15 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.3" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" />
</ItemGroup>

View File

@@ -0,0 +1,62 @@
using CandyHouseContracts.AdapterContracts;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace CandyHouseWebApi.Controllers;
[Authorize]
[Route("api/[controller]/[action]")]
[ApiController]
public class ReportController(IReportAdapter adapter) : ControllerBase
{
private readonly IReportAdapter _adapter = adapter;
[HttpGet]
[Consumes("application/json")]
public async Task<IActionResult> GetProductHistoryPrices(CancellationToken ct)
{
return (await _adapter.GetDataProductHistoryPricesAsync(ct)).GetResponse(Request, Response);
}
[HttpGet]
[Consumes("application/json")]
public async Task<IActionResult> GetSales(DateTime fromDate, DateTime toDate, CancellationToken cancellationToken)
{
return (await _adapter.GetDataSaleByPeriodAsync(fromDate, toDate, cancellationToken)).GetResponse(Request,
Response);
}
[HttpGet]
[Consumes("application/json")]
public async Task<IActionResult> GetClientDiscount(DateTime fromDate, DateTime toDate,
CancellationToken cancellationToken)
{
return (await _adapter.GetDataClientDiscountByPeriodAsync(fromDate, toDate, cancellationToken)).GetResponse(
Request, Response);
}
[HttpGet]
[Consumes("application/octet-stream")]
public async Task<IActionResult> LoadProductHistoryPrices(CancellationToken cancellationToken)
{
return (await _adapter.CreateDocumentProductHistoryPricesAsync(cancellationToken)).GetResponse(Request,
Response);
}
[HttpGet]
[Consumes("application/octet-stream")]
public async Task<IActionResult> LoadSales(DateTime fromDate, DateTime toDate, CancellationToken cancellationToken)
{
return (await _adapter.CreateDocumentSalesByPeriodAsync(fromDate, toDate, cancellationToken)).GetResponse(
Request, Response);
}
[HttpGet]
[Consumes("application/octet-stream")]
public async Task<IActionResult> LoadClientDiscount(DateTime fromDate, DateTime toDate,
CancellationToken cancellationToken)
{
return (await _adapter.CreateDocumentClientDiscountByPeriodAsync(fromDate, toDate, cancellationToken))
.GetResponse(Request, Response);
}
}

View File

@@ -25,7 +25,7 @@ public class WeatherForecastController : ControllerBase
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Date = DateOnly.FromDateTime(DateTime.UtcNow.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})

View File

@@ -0,0 +1,16 @@
using CandyHouseContracts.Infrastructure;
namespace CandyHouseWebApi.Infrastructure;
public class ConfigurationSalary(IConfiguration configuration) : IConfigurationSalary
{
private readonly Lazy<SalarySettings> _salarySettings = new(() =>
{
return configuration.GetValue<SalarySettings>("SalarySettings") ??
throw new InvalidDataException(nameof(SalarySettings));
});
public double ExtraSaleSum => _salarySettings.Value.ExtraSaleSum;
public int MaxConcurrentThreads => _salarySettings.Value.MaxConcurrentThreads;
}

View File

@@ -0,0 +1,8 @@
namespace CandyHouseWebApi.Infrastructure;
public class SalarySettings
{
public double ExtraSaleSum { get; set; }
public int MaxConcurrentThreads { get; set; }
}

View File

@@ -14,9 +14,15 @@ using Microsoft.IdentityModel.Tokens;
using Serilog;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using CandyHouseBusinessLogic.OfficePackage;
using CandyHouseContracts.BusinessLogicContracts;
using PdfSharp.Fonts;
var builder = WebApplication.CreateBuilder(args);
// Configure PDFSharp to use Windows system fonts
GlobalFontSettings.UseWindowsFontsUnderWindows = true;
// Add services to the container.
builder.Services.AddControllers();
@@ -31,7 +37,6 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = AuthOptions.ISSUER,
@@ -65,13 +70,22 @@ builder.Services.AddTransient<ISalaryStorageContract, SalaryStorageContract>();
builder.Services.AddTransient<ISaleStorageContract, SaleStorageContract>();
builder.Services.AddTransient<IEmployeeStorageContract, EmployeeStorageContract>();
builder.Services.AddTransient<IClientDiscountStorageContract, ClientDiscountStorageContract>();
builder.Services.AddTransient<IClientAdapter, ClientAdapter>();
builder.Services.AddTransient<IPostAdapter, PostAdapter>();
builder.Services.AddTransient<IProductAdapter, ProductAdapter>();
builder.Services.AddTransient<ISaleAdapter, SaleAdapter>();
builder.Services.AddTransient<IEmployeeAdapter, EmployeeAdapter>();
builder.Services.AddTransient<ISalaryAdapter, SalaryAdapter>();
builder.Services.AddSingleton<IConfigurationSalary, ConfigurationSalary>();
builder.Services.AddTransient<IReportContract, ReportContract>();
builder.Services.AddTransient<BaseWordBuilder, OpenXmlWordBuilder>();
builder.Services.AddTransient<BaseExcelBuilder, OpenXmlExcelBuilder>();
builder.Services.AddTransient<BasePdfBuilder, MigraDocPdfBuilder>();
builder.Services.AddTransient<IReportAdapter, ReportAdapter>();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddOpenApi();
@@ -81,6 +95,7 @@ if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
if (app.Environment.IsProduction())
{
var dbContext = app.Services.GetRequiredService<CandyHouseDbContext>();
@@ -98,11 +113,12 @@ app.UseAuthorization();
app.Map("/login/{username}", (string username) =>
{
return new JwtSecurityTokenHandler().WriteToken(new JwtSecurityToken(
issuer: AuthOptions.ISSUER,
audience: AuthOptions.AUDIENCE,
claims: [new(ClaimTypes.Name, username)],
expires: DateTime.UtcNow.Add(TimeSpan.FromMinutes(2)),
signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)));
issuer: AuthOptions.ISSUER,
audience: AuthOptions.AUDIENCE,
claims: [new(ClaimTypes.Name, username)],
expires: DateTime.UtcNow.Add(TimeSpan.FromMinutes(2)),
signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(),
SecurityAlgorithms.HmacSha256)));
});
app.MapControllers();

View File

@@ -14,15 +14,18 @@
{
"Name": "File",
"Args": {
"path": "../logs/magiccarpet-.log",
"path": "../logs/candyhouse-.log",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {CorrelationId} {Level:u3} {Username} {Message:lj}{Exception}{NewLine}"
}
}
]
},
"AllowedHosts": "*"
//"DataBaseSettings": {
// "ConnectionString": "Host=127.0.0.1;Port=5432;Database=CandyHouseTest;Username=postgres;Password=postgres;"
//}
"AllowedHosts": "*",
"DataBaseSettings": {
"ConnectionString": "Host=127.0.0.1;Port=5432;Database=CandyHouseTest;Username=postgres;Password=postgres;"
},
"SalarySettings": {
"ExtraSaleSum": 1000
}
}