4 Commits

68 changed files with 3485 additions and 170 deletions

View File

@@ -9,11 +9,13 @@
<ItemGroup>
<PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="DocumentFormat.OpenXml" Version="3.3.0" />
<PackageReference Include="EntityFramework" Version="6.5.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.4" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.4" />
<PackageReference Include="Npgsql" Version="9.0.3" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
<PackageReference Include="PDFsharp-MigraDoc-gdi" Version="6.2.0" />
</ItemGroup>
<ItemGroup>

View File

@@ -0,0 +1,184 @@

using AndDietCokeBuisnessLogic.BusinessLogicsContracts;
using AndDietCokeBuisnessLogic.OfficePackage;
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Extensions;
using AndDietCokeContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
namespace AndDietCokeBuisnessLogic.Implementations
{
public class ReportContract(IDishStorageContract dishStorageContract, ISaleStorageContract saleStorageContract, ISalaryStorageContract salaryStorageContract, ILogger logger, BaseWordBuilder baseWordBuilder, BaseExcelBuilder baseExcelBuilder, BasePdfBuilder basePdfBuilder) : IReportContract
{
private readonly ILogger _logger = logger;
private readonly BaseWordBuilder _baseWordBuilder = baseWordBuilder;
private readonly IDishStorageContract _dishStorageContract = dishStorageContract;
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
private readonly BaseExcelBuilder _baseExcelBuilder = baseExcelBuilder;
private readonly ISalaryStorageContract _salaryStorageContract = salaryStorageContract;
private readonly BasePdfBuilder _basePdfBuilder = basePdfBuilder;
internal static readonly string[] tableHeader = ["Дата продажи", "Сумма", "Название блюда", "Количество", "Имя работника"];
internal static readonly string[] documentHeader = ["Блюдо", "История цен", "Дата изменения"];
public Task<List<DishPriceReportDataModel>> GetDataDishPricesAsync(CancellationToken ct)
{
_logger.LogInformation("GetDataDishPricesAsync");
return GetDishPriceHistoryAsync(ct);
}
public Task<List<WorkerSalaryDataModel>> GetDataSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
_logger.LogInformation("Get SalaryPeriod from {dateStart} to {dateFinish}", dateStart, dateFinish);
return GetDataBySalaryAsync(dateStart, dateFinish, ct);
}
public Task<List<SaleDataModel>> GetDataSalesByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
_logger.LogInformation("Get data SalesByPeriod from {dateStart} to{ dateFinish}", dateStart, dateFinish);
return GetDataBySaleAsync(dateStart, dateFinish, ct);
}
public async Task<Stream> CreateDocumentSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
_logger.LogInformation("Create report SalaryByPeriod from {dateStart} to {dateFinish}", dateStart, dateFinish);
var data = await GetDataBySalaryAsync(dateStart, dateFinish, ct) ?? throw new InvalidOperationException("No found data");
var totalSalary = data.Sum(x => x.TotalSalary);
return _basePdfBuilder
.AddHeader("Зарплатная ведомость")
.AddParagraph($"за период с {dateStart.ToShortDateString()} по {dateFinish.ToShortDateString()}")
.AddPieChart("Начисления", [.. data.Select(x => (x.WorkerFIO, x.TotalSalary))])
.AddParagraph("")
.AddParagraph($"Общая сумма начислений: {totalSalary:N2} руб.")
.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 GetDataBySaleAsync(dateStart, dateFinish, ct) ?? throw new InvalidOperationException("No found data");
var tableRows = new List<string[]>();
foreach (var sale in data)
{
tableRows.Add(new[]
{
sale.SaleDate.ToShortDateString(),
sale.Sum.ToString("N2"),
"",
"",
sale.WorkerFIO,
});
foreach (var dish in sale.Dishes!)
{
tableRows.Add(new[]
{
"", "",
dish.DishName,
dish.Count.ToString(),
""
});
}
}
tableRows.Add(new[]
{
"Всего",
data.Sum(x => x.Sum).ToString("N2"),
"", "",""
});
return _baseExcelBuilder
.AddHeader("Продажи за период", 0, 5)
.AddParagraph($"c {dateStart.ToShortDateString()} по {dateFinish.ToShortDateString()}", 2)
.AddTable(
new[] { 10, 10, 10, 10, 10 },
[tableHeader, .. tableRows]
)
.Build();
}
public async Task<Stream> CreateDocumentDishPricesByDishAsync(CancellationToken ct)
{
logger.LogInformation("Create report ProductsByManufacturer");
var data = await GetDishPriceHistoryAsync(ct) ?? throw new InvalidOperationException("No found data");
var documentHeader = new string[] { "Название блюда", "Цена", "Дата" };
var tableData = new List<string[]>() { documentHeader }
.Union(
data.SelectMany(x =>
new List<string[]>
{
new[] { x.DishName, "", "" }
}
.Union(
x.DishPrices.Select(y => new[] { "", y.Item1, y.Item2 })
)
).ToList()
)
.ToList();
return _baseWordBuilder
.AddHeader("История цен блюд")
.AddParagraph($"Сформировано на дату {DateTime.Now}")
.AddTable(
new[] { 3000, 5000, 3000 },
tableData
)
.Build();
}
private async Task<List<DishPriceReportDataModel>> GetDishPriceHistoryAsync(CancellationToken ct)
{
try
{
var dishPriceHistories = await _dishStorageContract.GetHistoryAsync(ct);
return dishPriceHistories.GroupBy(x => x.DishName).Select(x => new DishPriceReportDataModel
{
DishName = x.Key,
DishPrices = x.Select(y => (y.OldPrice.ToString(), y.ChangeDate.ToString())).ToList()
}).ToList();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error fetching dish price history");
return new List<DishPriceReportDataModel>();
}
}
private async Task<List<SaleDataModel>> GetDataBySaleAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
if (dateStart.IsDateNotOlder(dateFinish))
{
throw new IncorrectDatesException(dateStart, dateFinish);
}
var sales = await _saleStorageContract.GetListAsync(dateStart, dateFinish, ct);
return sales
.OrderBy(x => x.SaleDate)
.GroupBy(x => x.WorkerId)
.SelectMany(g => g)
.ToList();
}
private async Task<List<WorkerSalaryDataModel>> GetDataBySalaryAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
if (dateStart.IsDateNotOlder(dateFinish))
{
throw new IncorrectDatesException(dateStart, dateFinish);
}
return [.. (await _salaryStorageContract.GetListAsync(dateStart, dateFinish, ct))
.GroupBy(x => x.WorkerId)
.Select(group => new WorkerSalaryDataModel
{
WorkerFIO = group.First().WorkerFIO,
TotalSalary = group.Sum(y => y.Salary),
FromPeriod = group.Min(y => y.SalaryDate),
ToPeriod = group.Max(y => y.SalaryDate)
})
.OrderBy(x => x.WorkerFIO)];
}
}
}

View File

@@ -2,24 +2,22 @@
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Extensions;
using AndDietCokeContracts.Infrastrusture;
using AndDietCokeContracts.Infrastrusture.PostConfiguration;
using AndDietCokeContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static AndDietCokeBuisnessLogic.Implementations.SalaryBusinessLogicContract;
namespace AndDietCokeBuisnessLogic.Implementations;
internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract,
ISaleStorageContract saleStorageContract, IPostStorageContract postStorageContract, IWorkerStorageContract workerStorageContract, ILogger logger) : ISalaryBusinessLogicContract
ISaleStorageContract saleStorageContract, IPostStorageContract postStorageContract, IWorkerStorageContract workerStorageContract, ILogger logger, IConfigurationSalary сonfiguration) : ISalaryBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISalaryStorageContract _salaryStorageContract = salaryStorageContract;
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
private readonly IWorkerStorageContract _workerStorageContract = workerStorageContract;
private readonly IPostStorageContract _roleStorageContract = postStorageContract;
private readonly IConfigurationSalary _salaryConfiguration = сonfiguration;
public List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate)
{
@@ -57,12 +55,69 @@ internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageC
var workers = _workerStorageContract.GetList() ?? throw new NullListException();
foreach (var worker in workers)
{
var sales = _saleStorageContract.GetList(startDate, finishDate, workerId: worker.Id)?.Sum(x => x.Dishes!.Count) ??
var sales = _saleStorageContract.GetList(startDate, finishDate, workerId: worker.Id) ??
throw new NullListException();
var salary = 100 + sales * 0.1;
var post = _roleStorageContract.GetElementById(worker.PostId) ?? throw new NullListException();
var salary = post.ConfigurationModel switch
{
null => 0,
WaiterPostConfiguration cpc => CalculateSalaryForCourier(sales, startDate, finishDate, cpc),
ChefPostConfiguration spc => CalculateSalaryForOperator(startDate, finishDate, spc),
PostConfiguration pc => pc.Rate,
};
_logger.LogDebug("The employee {workerId} was paid a salary of {salary}", worker.Id, salary);
_salaryStorageContract.AddElement(new SalaryDataModel(Guid.NewGuid().ToString(), worker.Id, finishDate, salary));
}
}
private double CalculateSalaryForCourier(List<SaleDataModel> sales, DateTime startDate, DateTime finishDate, WaiterPostConfiguration config)
{
double calcPercent = 0.0;
object lockObj = new();
var parallelOptions = new ParallelOptions
{
MaxDegreeOfParallelism = _salaryConfiguration.MaxConcurrentThreads
};
var days = Enumerable.Range(0, (finishDate - startDate).Days)
.Select(offset => startDate.AddDays(offset))
.ToList();
Parallel.ForEach(days, parallelOptions, date =>
{
var salesInDay = sales
.Where(x => x.SaleDate >= date && x.SaleDate < date.AddDays(1))
.ToArray();
if (salesInDay.Length > 0)
{
double dayPercent = (salesInDay.Sum(x => x.Sum) / salesInDay.Length) * config.SalePercent;
lock (lockObj)
{
calcPercent += dayPercent;
}
}
});
double bonus = sales
.Where(x => x.Sum > _salaryConfiguration.ExtraSaleSum)
.Sum(x => x.Sum) * config.BonusForExtraSales;
return config.Rate + calcPercent + bonus;
}
private double CalculateSalaryForOperator(DateTime startDate, DateTime finishDate, ChefPostConfiguration config)
{
try
{
return config.Rate + config.PersonalCountTrendPremium * _workerStorageContract.GetWorkerTrend(startDate, finishDate);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error in the supervisor payroll process");
return 0;
}
}
}

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeBuisnessLogic.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,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeBuisnessLogic.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 AndDietCokeBuisnessLogic.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,86 @@
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Shapes.Charts;
using MigraDoc.Rendering;
using System.Text;
namespace AndDietCokeBuisnessLogic.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,305 @@

using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
namespace AndDietCokeBuisnessLogic.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,93 @@
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace AndDietCokeBuisnessLogic.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

@@ -11,6 +11,11 @@
<PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="EntityFramework" Version="6.5.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql" Version="9.0.3" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
</ItemGroup>

View File

@@ -1,6 +1,10 @@
using AndDietCokeDatabase.Models;
using AndDietCokeContracts.Infrastrusture;
using Microsoft.EntityFrameworkCore;
using System.Data;
using AndDietCokeContracts.Infrastrusture.PostConfiguration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace AndDietCokeDatabase;
@@ -43,6 +47,14 @@ public class AndDietCokeDbContext : DbContext
modelBuilder.Entity<OrderDish>()
.HasKey(x => new { x.OrderId, x.DishId });
modelBuilder.Entity<Post>()
.Property(x => x.Configuration)
.HasColumnType("jsonb")
.HasConversion(
x => SerializeRoleConfiguration(x),
x => DeserialzeRoleConfiguration(x)
);
}
public DbSet<Buyer> Buyers { get; set; }
@@ -60,4 +72,13 @@ public class AndDietCokeDbContext : DbContext
public DbSet<OrderDish> OrderDishes { get; set; }
public DbSet<Worker> Workers { get; set; }
private static string SerializeRoleConfiguration(PostConfiguration roleConfiguration) => JsonConvert.SerializeObject(roleConfiguration);
private static PostConfiguration DeserialzeRoleConfiguration(string jsonString) => JToken.Parse(jsonString).Value<string>("Type") switch
{
nameof(WaiterPostConfiguration) => JsonConvert.DeserializeObject<WaiterPostConfiguration>(jsonString)!,
nameof(ChefPostConfiguration) => JsonConvert.DeserializeObject<ChefPostConfiguration>(jsonString)!,
_ => JsonConvert.DeserializeObject<PostConfiguration>(jsonString)!,
};
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AndDietCokeContracts.Infrastrusture;
namespace AndDietCokeDatabase;
class DefaultConfigurationDatabase : IConfigurationDatabase
{
public string ConnectionString => "";
}

View File

@@ -173,4 +173,21 @@ internal class DishStorageContract : IDishStorageContract
}
private Dish? GetDishById(string id) => _dbContext.Dishes.FirstOrDefault(x => x.Id == id && !x.IsDeleted);
public async Task<List<DishHistoryDataModel>> GetHistoryAsync(CancellationToken ct)
{
try
{
var entities = await _dbContext.DishHistories
.Include(x => x.Dish)
.ToListAsync(ct);
return entities.Select(x => _mapper.Map<DishHistoryDataModel>(x)).ToList();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
}

View File

@@ -29,7 +29,8 @@ internal 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);
}

View File

@@ -3,11 +3,8 @@ using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.StoragesContracts;
using AndDietCokeDatabase.Models;
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace AndDietCokeDatabase.Implementations;
@@ -61,4 +58,17 @@ internal class SalaryStorageContract : ISalaryStorageContract
throw new StorageException(ex);
}
}
public async Task<List<SalaryDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken cancellationToken)
{
try
{
return [.. await _dbContext.Salaries.Include(x => x.Worker).Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate).Select(x => _mapper.Map<SalaryDataModel>(x)).ToListAsync()];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
}

View File

@@ -10,7 +10,6 @@ using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace AndDietCokeDatabase.Implementations;
internal class SaleStorageContract : ISaleStorageContract
@@ -118,4 +117,19 @@ internal class SaleStorageContract : ISaleStorageContract
}
private Sale? GetSaleById(string id) => _dbContext.Sales.Include(x => x.Buyer).Include(x => x.Worker).Include(x => x.OrderDishes)!.ThenInclude(x => x.Dish).FirstOrDefault(x => x.Id == id);
public Task<List<SaleDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct)
{
try
{
var query = _dbContext.Sales.Include(x => x.Buyer).Include(x => x.Worker).Include(x => x.OrderDishes)!.ThenInclude(x => x.Dish).AsQueryable();
query = query.Where(x => x.SaleDate.Date >= startDate.Date && x.SaleDate.Date < endDate.Date);
return Task.FromResult(query.Select(x => _mapper.Map<SaleDataModel>(x)).ToList());
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
}

View File

@@ -105,6 +105,21 @@ internal class WorkerStorageContract : IWorkerStorageContract
}
}
public int GetWorkerTrend(DateTime fromPeriod, DateTime toPeriod)
{
try
{
var countWorkersOnBegining = _dbContext.Workers.Count(x => x.EmploymentDate < fromPeriod && (!x.IsDeleted || x.DateOfDelete > fromPeriod));
var countWorkersOnEnding = _dbContext.Workers.Count(x => x.EmploymentDate < toPeriod && (!x.IsDeleted || x.DateOfDelete > toPeriod));
return countWorkersOnEnding - countWorkersOnBegining;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(WorkerDataModel workerDataModel)
{
try
@@ -131,6 +146,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
{
var element = GetWorkerById(id) ?? throw new ElementNotFoundException(id);
element.IsDeleted = true;
element.DateOfDelete = DateTime.UtcNow;
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)

View File

@@ -0,0 +1,327 @@
// <auto-generated />
using System;
using AndDietCokeDatabase;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace AndDietCokeDatabase.Migrations
{
[DbContext(typeof(AndDietCokeDbContext))]
[Migration("20250525153604_FirstMigration")]
partial class FirstMigration
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.4")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("AndDietCokeDatabase.Models.Buyer", 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("Buyers");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Dish", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("DishName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("DishType")
.HasColumnType("integer");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("DishName", "IsDeleted")
.IsUnique()
.HasFilter("\"IsDeleted\" = FALSE");
b.ToTable("Dishes");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.DishHistory", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("DishId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("OldPrice")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("DishId");
b.ToTable("DishHistories");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.OrderDish", b =>
{
b.Property<string>("OrderId")
.HasColumnType("text");
b.Property<string>("DishId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<double>("Price")
.HasColumnType("double precision");
b.Property<string>("SaleId")
.HasColumnType("text");
b.HasKey("OrderId", "DishId");
b.HasIndex("DishId");
b.HasIndex("SaleId");
b.ToTable("OrderDishes");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Post", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<bool>("IsActual")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PostName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("PostType")
.HasColumnType("integer");
b.Property<double>("Salary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("PostId", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.HasIndex("PostName", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.ToTable("Posts");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Salary", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("SalaryDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("WorkerSalary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("WorkerId");
b.ToTable("Salaries");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Sale", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("BuyerId")
.HasColumnType("text");
b.Property<bool>("IsCancel")
.HasColumnType("boolean");
b.Property<bool>("IsConstantClient")
.HasColumnType("boolean");
b.Property<DateTime>("SaleDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("BuyerId");
b.HasIndex("WorkerId");
b.ToTable("Sales");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Worker", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("BirthDate")
.HasColumnType("timestamp without time zone");
b.Property<DateTime>("EmploymentDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Workers");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.DishHistory", b =>
{
b.HasOne("AndDietCokeDatabase.Models.Dish", "Dish")
.WithMany("DishHistories")
.HasForeignKey("DishId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Dish");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.OrderDish", b =>
{
b.HasOne("AndDietCokeDatabase.Models.Dish", "Dish")
.WithMany()
.HasForeignKey("DishId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AndDietCokeDatabase.Models.Sale", "Sale")
.WithMany("OrderDishes")
.HasForeignKey("SaleId");
b.Navigation("Dish");
b.Navigation("Sale");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Salary", b =>
{
b.HasOne("AndDietCokeDatabase.Models.Worker", "Worker")
.WithMany("Salaries")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Worker");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Sale", b =>
{
b.HasOne("AndDietCokeDatabase.Models.Buyer", "Buyer")
.WithMany("Sales")
.HasForeignKey("BuyerId");
b.HasOne("AndDietCokeDatabase.Models.Worker", "Worker")
.WithMany("Sales")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Buyer");
b.Navigation("Worker");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Buyer", b =>
{
b.Navigation("Sales");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Dish", b =>
{
b.Navigation("DishHistories");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Sale", b =>
{
b.Navigation("OrderDishes");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Worker", b =>
{
b.Navigation("Salaries");
b.Navigation("Sales");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,256 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace AndDietCokeDatabase.Migrations
{
/// <inheritdoc />
public partial class FirstMigration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Buyers",
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_Buyers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Dishes",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
DishName = table.Column<string>(type: "text", nullable: false),
DishType = table.Column<int>(type: "integer", nullable: false),
Price = table.Column<double>(type: "double precision", nullable: false),
IsDeleted = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Dishes", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Posts",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
PostId = table.Column<string>(type: "text", nullable: false),
PostName = table.Column<string>(type: "text", nullable: false),
PostType = table.Column<int>(type: "integer", nullable: false),
Salary = table.Column<double>(type: "double precision", nullable: false),
IsActual = table.Column<bool>(type: "boolean", nullable: false),
ChangeDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Posts", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Workers",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
FIO = table.Column<string>(type: "text", nullable: false),
PostId = table.Column<string>(type: "text", nullable: false),
BirthDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
EmploymentDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
IsDeleted = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Workers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "DishHistories",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
DishId = table.Column<string>(type: "text", nullable: false),
OldPrice = table.Column<double>(type: "double precision", nullable: false),
ChangeDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_DishHistories", x => x.Id);
table.ForeignKey(
name: "FK_DishHistories_Dishes_DishId",
column: x => x.DishId,
principalTable: "Dishes",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Salaries",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
WorkerId = table.Column<string>(type: "text", nullable: false),
SalaryDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
WorkerSalary = table.Column<double>(type: "double precision", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Salaries", x => x.Id);
table.ForeignKey(
name: "FK_Salaries_Workers_WorkerId",
column: x => x.WorkerId,
principalTable: "Workers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Sales",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
WorkerId = table.Column<string>(type: "text", nullable: false),
BuyerId = table.Column<string>(type: "text", nullable: true),
SaleDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
Sum = table.Column<double>(type: "double precision", nullable: false),
IsConstantClient = table.Column<bool>(type: "boolean", nullable: false),
IsCancel = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Sales", x => x.Id);
table.ForeignKey(
name: "FK_Sales_Buyers_BuyerId",
column: x => x.BuyerId,
principalTable: "Buyers",
principalColumn: "Id");
table.ForeignKey(
name: "FK_Sales_Workers_WorkerId",
column: x => x.WorkerId,
principalTable: "Workers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "OrderDishes",
columns: table => new
{
OrderId = table.Column<string>(type: "text", nullable: false),
DishId = table.Column<string>(type: "text", nullable: false),
Count = table.Column<int>(type: "integer", nullable: false),
Price = table.Column<double>(type: "double precision", nullable: false),
SaleId = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_OrderDishes", x => new { x.OrderId, x.DishId });
table.ForeignKey(
name: "FK_OrderDishes_Dishes_DishId",
column: x => x.DishId,
principalTable: "Dishes",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_OrderDishes_Sales_SaleId",
column: x => x.SaleId,
principalTable: "Sales",
principalColumn: "Id");
});
migrationBuilder.CreateIndex(
name: "IX_Buyers_PhoneNumber",
table: "Buyers",
column: "PhoneNumber",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Dishes_DishName_IsDeleted",
table: "Dishes",
columns: new[] { "DishName", "IsDeleted" },
unique: true,
filter: "\"IsDeleted\" = FALSE");
migrationBuilder.CreateIndex(
name: "IX_DishHistories_DishId",
table: "DishHistories",
column: "DishId");
migrationBuilder.CreateIndex(
name: "IX_OrderDishes_DishId",
table: "OrderDishes",
column: "DishId");
migrationBuilder.CreateIndex(
name: "IX_OrderDishes_SaleId",
table: "OrderDishes",
column: "SaleId");
migrationBuilder.CreateIndex(
name: "IX_Posts_PostId_IsActual",
table: "Posts",
columns: new[] { "PostId", "IsActual" },
unique: true,
filter: "\"IsActual\" = TRUE");
migrationBuilder.CreateIndex(
name: "IX_Posts_PostName_IsActual",
table: "Posts",
columns: new[] { "PostName", "IsActual" },
unique: true,
filter: "\"IsActual\" = TRUE");
migrationBuilder.CreateIndex(
name: "IX_Salaries_WorkerId",
table: "Salaries",
column: "WorkerId");
migrationBuilder.CreateIndex(
name: "IX_Sales_BuyerId",
table: "Sales",
column: "BuyerId");
migrationBuilder.CreateIndex(
name: "IX_Sales_WorkerId",
table: "Sales",
column: "WorkerId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "DishHistories");
migrationBuilder.DropTable(
name: "OrderDishes");
migrationBuilder.DropTable(
name: "Posts");
migrationBuilder.DropTable(
name: "Salaries");
migrationBuilder.DropTable(
name: "Dishes");
migrationBuilder.DropTable(
name: "Sales");
migrationBuilder.DropTable(
name: "Buyers");
migrationBuilder.DropTable(
name: "Workers");
}
}
}

View File

@@ -0,0 +1,328 @@
// <auto-generated />
using System;
using AndDietCokeDatabase;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace AndDietCokeDatabase.Migrations
{
[DbContext(typeof(AndDietCokeDbContext))]
[Migration("20250525160705_ChangeFieldsInPost")]
partial class ChangeFieldsInPost
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.4")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("AndDietCokeDatabase.Models.Buyer", 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("Buyers");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Dish", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("DishName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("DishType")
.HasColumnType("integer");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("DishName", "IsDeleted")
.IsUnique()
.HasFilter("\"IsDeleted\" = FALSE");
b.ToTable("Dishes");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.DishHistory", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("DishId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("OldPrice")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("DishId");
b.ToTable("DishHistories");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.OrderDish", b =>
{
b.Property<string>("OrderId")
.HasColumnType("text");
b.Property<string>("DishId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<double>("Price")
.HasColumnType("double precision");
b.Property<string>("SaleId")
.HasColumnType("text");
b.HasKey("OrderId", "DishId");
b.HasIndex("DishId");
b.HasIndex("SaleId");
b.ToTable("OrderDishes");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Post", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Configuration")
.IsRequired()
.HasColumnType("jsonb");
b.Property<bool>("IsActual")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PostName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("PostType")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("PostId", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.HasIndex("PostName", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.ToTable("Posts");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Salary", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("SalaryDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("WorkerSalary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("WorkerId");
b.ToTable("Salaries");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Sale", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("BuyerId")
.HasColumnType("text");
b.Property<bool>("IsCancel")
.HasColumnType("boolean");
b.Property<bool>("IsConstantClient")
.HasColumnType("boolean");
b.Property<DateTime>("SaleDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("BuyerId");
b.HasIndex("WorkerId");
b.ToTable("Sales");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Worker", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("BirthDate")
.HasColumnType("timestamp without time zone");
b.Property<DateTime>("EmploymentDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Workers");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.DishHistory", b =>
{
b.HasOne("AndDietCokeDatabase.Models.Dish", "Dish")
.WithMany("DishHistories")
.HasForeignKey("DishId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Dish");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.OrderDish", b =>
{
b.HasOne("AndDietCokeDatabase.Models.Dish", "Dish")
.WithMany()
.HasForeignKey("DishId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AndDietCokeDatabase.Models.Sale", "Sale")
.WithMany("OrderDishes")
.HasForeignKey("SaleId");
b.Navigation("Dish");
b.Navigation("Sale");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Salary", b =>
{
b.HasOne("AndDietCokeDatabase.Models.Worker", "Worker")
.WithMany("Salaries")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Worker");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Sale", b =>
{
b.HasOne("AndDietCokeDatabase.Models.Buyer", "Buyer")
.WithMany("Sales")
.HasForeignKey("BuyerId");
b.HasOne("AndDietCokeDatabase.Models.Worker", "Worker")
.WithMany("Sales")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Buyer");
b.Navigation("Worker");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Buyer", b =>
{
b.Navigation("Sales");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Dish", b =>
{
b.Navigation("DishHistories");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Sale", b =>
{
b.Navigation("OrderDishes");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Worker", b =>
{
b.Navigation("Salaries");
b.Navigation("Sales");
});
#pragma warning restore 612, 618
}
}
}

View File

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

View File

@@ -0,0 +1,325 @@
// <auto-generated />
using System;
using AndDietCokeDatabase;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace AndDietCokeDatabase.Migrations
{
[DbContext(typeof(AndDietCokeDbContext))]
partial class AndDietCokeDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.4")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("AndDietCokeDatabase.Models.Buyer", 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("Buyers");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Dish", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("DishName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("DishType")
.HasColumnType("integer");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("DishName", "IsDeleted")
.IsUnique()
.HasFilter("\"IsDeleted\" = FALSE");
b.ToTable("Dishes");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.DishHistory", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("DishId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("OldPrice")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("DishId");
b.ToTable("DishHistories");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.OrderDish", b =>
{
b.Property<string>("OrderId")
.HasColumnType("text");
b.Property<string>("DishId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<double>("Price")
.HasColumnType("double precision");
b.Property<string>("SaleId")
.HasColumnType("text");
b.HasKey("OrderId", "DishId");
b.HasIndex("DishId");
b.HasIndex("SaleId");
b.ToTable("OrderDishes");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Post", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Configuration")
.IsRequired()
.HasColumnType("jsonb");
b.Property<bool>("IsActual")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PostName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("PostType")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("PostId", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.HasIndex("PostName", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.ToTable("Posts");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Salary", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("SalaryDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("WorkerSalary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("WorkerId");
b.ToTable("Salaries");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Sale", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("BuyerId")
.HasColumnType("text");
b.Property<bool>("IsCancel")
.HasColumnType("boolean");
b.Property<bool>("IsConstantClient")
.HasColumnType("boolean");
b.Property<DateTime>("SaleDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("BuyerId");
b.HasIndex("WorkerId");
b.ToTable("Sales");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Worker", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("BirthDate")
.HasColumnType("timestamp without time zone");
b.Property<DateTime>("EmploymentDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Workers");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.DishHistory", b =>
{
b.HasOne("AndDietCokeDatabase.Models.Dish", "Dish")
.WithMany("DishHistories")
.HasForeignKey("DishId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Dish");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.OrderDish", b =>
{
b.HasOne("AndDietCokeDatabase.Models.Dish", "Dish")
.WithMany()
.HasForeignKey("DishId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AndDietCokeDatabase.Models.Sale", "Sale")
.WithMany("OrderDishes")
.HasForeignKey("SaleId");
b.Navigation("Dish");
b.Navigation("Sale");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Salary", b =>
{
b.HasOne("AndDietCokeDatabase.Models.Worker", "Worker")
.WithMany("Salaries")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Worker");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Sale", b =>
{
b.HasOne("AndDietCokeDatabase.Models.Buyer", "Buyer")
.WithMany("Sales")
.HasForeignKey("BuyerId");
b.HasOne("AndDietCokeDatabase.Models.Worker", "Worker")
.WithMany("Sales")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Buyer");
b.Navigation("Worker");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Buyer", b =>
{
b.Navigation("Sales");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Dish", b =>
{
b.Navigation("DishHistories");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Sale", b =>
{
b.Navigation("OrderDishes");
});
modelBuilder.Entity("AndDietCokeDatabase.Models.Worker", b =>
{
b.Navigation("Salaries");
b.Navigation("Sales");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -1,4 +1,5 @@
using AndDietCokeContracts.Enums;
using AndDietCokeContracts.Infrastrusture.PostConfiguration;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -17,9 +18,7 @@ public class Post
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

@@ -22,7 +22,7 @@ public class Worker
public DateTime EmploymentDate { get; set; }
public bool IsDeleted { get; set; }
public DateTime? DateOfDelete { get; set; }
[NotMapped]
public Post? Post { get; set; }

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Design;
namespace AndDietCokeDatabase;
internal class SampleContextFactory : IDesignTimeDbContextFactory<AndDietCokeDbContext>
{
public AndDietCokeDbContext CreateDbContext(string[] args)
{
return new AndDietCokeDbContext(new DefaultConfigurationDatabase());
}
}

View File

@@ -0,0 +1,15 @@

using AndDietCokeContracts.AdapterContracts.OperationResponses;
namespace AndDietCokeContracts.AdapterContracts
{
public interface IReportAdapter
{
Task<ReportOperationResponse> GetDishPricesByDishAsync(CancellationToken cancellationToken);
Task<ReportOperationResponse> CreateDocumentDishPricesByDishAsync(CancellationToken cancellationToken);
Task<ReportOperationResponse> GetSalesByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken cancellationToken);
Task<ReportOperationResponse> CreateDocumentSalesByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken cancellationToken);
Task<ReportOperationResponse> GetDataSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken cancellationToken);
Task<ReportOperationResponse> CreateDocumentSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
}
}

View File

@@ -0,0 +1,17 @@
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Infrastrusture;
using AndDietCokeContracts.ViewModels;
namespace AndDietCokeContracts.AdapterContracts.OperationResponses
{
public class ReportOperationResponse : OperationResponse
{
public static ReportOperationResponse OK(List<DishPriceReportViewModel> data) => OK<ReportOperationResponse, List<DishPriceReportViewModel>>(data);
public static ReportOperationResponse OK(Stream data, string fileName) => OK<ReportOperationResponse, Stream>(data, fileName);
public static ReportOperationResponse OK(List<SaleViewModel> data) => OK<ReportOperationResponse, List<SaleViewModel>>(data);
public static ReportOperationResponse OK(List<WorkerSalaryViewModel> data) => OK<ReportOperationResponse, List<WorkerSalaryViewModel>>(data);
public static ReportOperationResponse NoContent() => NoContent<ReportOperationResponse>();
public static ReportOperationResponse NotFound(string message) => NotFound<ReportOperationResponse>(message);
public static ReportOperationResponse BadRequest(string message) => BadRequest<ReportOperationResponse>(message);
public static ReportOperationResponse InternalServerError(string message) => InternalServerError<ReportOperationResponse>(message);
}
}

View File

@@ -9,12 +9,8 @@ namespace AndDietCokeContracts.BindingModels;
public class PostBindingModel
{
public string? Id { get; set; }
public string? PostId => Id;
public string? PostName { get; set; }
public string? PostType { get; set; }
public double Salary { get; set; }
public string? PostId => Id;
public string? PostName { get; set; }
public string? ConfigurationJson { get; set; }
}

View File

@@ -0,0 +1,19 @@
using AndDietCokeContracts.DataModels;
namespace AndDietCokeBuisnessLogic.BusinessLogicsContracts
{
public interface IReportContract
{
Task<List<DishPriceReportDataModel>> GetDataDishPricesAsync(CancellationToken ct);
Task<List<SaleDataModel>> GetDataSalesByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<List<WorkerSalaryDataModel>> GetDataSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<Stream> CreateDocumentDishPricesByDishAsync(CancellationToken ct);
Task<Stream> CreateDocumentSalesByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<Stream> CreateDocumentSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
}
}

View File

@@ -0,0 +1,9 @@

namespace AndDietCokeContracts.DataModels
{
public class DishPriceReportDataModel
{
public required string DishName { get; set; }
public required List<(string, string)> DishPrices { get; set; }
}
}

View File

@@ -8,15 +8,31 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using AndDietCokeContracts.Infrastrusture.PostConfiguration;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
namespace AndDietCokeContracts.DataModels;
public class PostDataModel(string id, 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; } = id;
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(WaiterPostConfiguration) => JsonConvert.DeserializeObject<WaiterPostConfiguration>(configurationJson)!,
nameof(ChefPostConfiguration) => JsonConvert.DeserializeObject<ChefPostConfiguration>(configurationJson)!,
_ => JsonConvert.DeserializeObject<PostConfiguration>(configurationJson)!,
};
}
}
public void Validate()
{
if (Id.IsEmpty())
@@ -27,8 +43,10 @@ public class PostDataModel(string id, string postName, PostType postType, double
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

@@ -19,7 +19,7 @@ workerSalary) : IValidation
public double Salary { get; private set; } = workerSalary;
public string WorkerFIO => _worker?.FIO ?? string.Empty;
public SalaryDataModel(string id, string workerId, DateTime salaryDate, double salary, WorkerDataModel worker) : this(id, workerId, salaryDate, salary)
public SalaryDataModel(string id, string workerId, DateTime salaryDate, double workersalary, WorkerDataModel worker) : this(id, workerId, salaryDate, workersalary)
{
_worker = worker;
}

View File

@@ -0,0 +1,11 @@

namespace AndDietCokeContracts.DataModels
{
public class WorkerSalaryDataModel
{
public required string WorkerFIO { get; set; }
public double TotalSalary { get; set; }
public DateTime FromPeriod { get; set; }
public DateTime ToPeriod { get; set; }
}
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.Infrastrusture;
public interface IConfigurationSalary
{
double ExtraSaleSum { get; }
int MaxConcurrentThreads { get; }
}

View File

@@ -1,42 +1,49 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.Infrastrusture;
public class OperationResponse
namespace AndDietCokeContracts.Infrastrusture
{
protected HttpStatusCode StatusCode { get; set; }
protected object? Result { get; set; }
public IActionResult GetResponse(HttpRequest request, HttpResponse response)
public class OperationResponse
{
ArgumentNullException.ThrowIfNull(request);
ArgumentNullException.ThrowIfNull(response);
protected HttpStatusCode StatusCode { get; set; }
response.StatusCode = (int)StatusCode;
protected object? Result { get; set; }
if (Result is null)
protected string? FileName { get; set; }
public IActionResult GetResponse(HttpRequest request, HttpResponse response)
{
return new StatusCodeResult((int)StatusCode);
ArgumentNullException.ThrowIfNull(request);
ArgumentNullException.ThrowIfNull(response);
response.StatusCode = (int)StatusCode;
if (Result is null)
{
return new StatusCodeResult((int)StatusCode);
}
if (Result is Stream stream)
{
return new FileStreamResult(stream, "application/octet-stream")
{
FileDownloadName = FileName
};
}
return new ObjectResult(Result);
}
return new ObjectResult(Result);
protected static TResult OK<TResult, TData>(TData data) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.OK, Result = data };
protected static TResult OK<TResult, TData>(TData data, string fileName) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.OK, Result = data, FileName = fileName };
protected static TResult NoContent<TResult>() where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.NoContent };
protected static TResult BadRequest<TResult>(string? errorMessage = null) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.BadRequest, Result = errorMessage };
protected static TResult NotFound<TResult>(string? errorMessage = null) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.NotFound, Result = errorMessage };
protected static TResult InternalServerError<TResult>(string? errorMessage = null) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.InternalServerError, Result = errorMessage };
}
protected static TResult OK<TResult, TData>(TData data) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.OK, Result = data };
protected static TResult NoContent<TResult>() where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.NoContent };
protected static TResult BadRequest<TResult>(string? errorMessage = null) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.BadRequest, Result = errorMessage };
protected static TResult NotFound<TResult>(string? errorMessage = null) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.NotFound, Result = errorMessage };
protected static TResult InternalServerError<TResult>(string? errorMessage = null) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.InternalServerError, Result = errorMessage };
}

View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.Infrastrusture.PostConfiguration;
public class ChefPostConfiguration : PostConfiguration
{
public override string Type => nameof(ChefPostConfiguration);
public double PersonalCountTrendPremium { get; set; }
}

View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.Infrastrusture.PostConfiguration;
public class PostConfiguration
{
public virtual string Type => nameof(PostConfiguration);
public double Rate { get; set; }
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.Infrastrusture.PostConfiguration;
public class WaiterPostConfiguration : PostConfiguration
{
public override string Type => nameof(WaiterPostConfiguration);
public double SalePercent { get; set; }
public double BonusForExtraSales { get; set; }
}

View File

@@ -10,6 +10,7 @@ public interface IDishStorageContract
{
List<DishDataModel> GetList(bool onlyActive = true);
List<DishHistoryDataModel> GetHistoryByDishId(string dishId);
Task<List<DishHistoryDataModel>> GetHistoryAsync(CancellationToken ct);
DishDataModel? GetElementById(string id);
DishDataModel? GetElementByName(string name);
void AddElement(DishDataModel dishDataModel);

View File

@@ -1,9 +1,4 @@
using AndDietCokeContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.StoragesContracts;
@@ -11,5 +6,6 @@ public interface ISalaryStorageContract
{
List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string?
workerId = null);
Task<List<SalaryDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken cancellationToken);
void AddElement(SalaryDataModel salaryDataModel);
}

View File

@@ -11,6 +11,7 @@ public interface ISaleStorageContract
{
List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? workerId = null, string? buyerId = null, string? dishId = null);
SaleDataModel? GetElementById(string id);
Task<List<SaleDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct);
void AddElement(SaleDataModel saleDataModel);
void DelElement(string id);
}

View File

@@ -15,5 +15,6 @@ public interface IWorkerStorageContract
void AddElement(WorkerDataModel workerDataModel);
void UpdElement(WorkerDataModel workerDataModel);
void DelElement(string id);
public int GetWorkerTrend(DateTime fromPeriod, DateTime toPeriod);
}

View File

@@ -0,0 +1,8 @@
namespace AndDietCokeContracts.ViewModels
{
public class DishPriceReportViewModel
{
public required string DishName { get; set; }
public required List<(string, string)> DishPrices { 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,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndDietCokeContracts.ViewModels
{
public class WorkerSalaryViewModel
{
public required string WorkerFIO { get; set; }
public double TotalSalary { get; set; }
public DateTime FromPeriod { get; set; }
public DateTime ToPeriod { get; set; }
}
}

View File

@@ -12,6 +12,7 @@ using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Infrastrusture.PostConfiguration;
namespace AndDietCokeTests.BuisnessLogicsContractsTests;
@@ -38,9 +39,9 @@ internal class PostBusinessLogicContractTests
//Arrange
var listOriginal = new List<PostDataModel>()
{
new(Guid.NewGuid().ToString(),"name 1", PostType.Chef, 10),
new(Guid.NewGuid().ToString(),"name 2", PostType.Chef, 10),
new(Guid.NewGuid().ToString(),"name 3", PostType.Chef, 10)
new(Guid.NewGuid().ToString(),"name 1", PostType.Chef, new PostConfiguration { Rate = 10 }),
new(Guid.NewGuid().ToString(),"name 2", PostType.Chef, new PostConfiguration { Rate = 10 }),
new(Guid.NewGuid().ToString(),"name 3", PostType.Chef, new PostConfiguration { Rate = 10 })
};
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).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.Chef, 10),
new(postId,"name 2", PostType.Chef, 10)
new(postId,"name 1", PostType.Chef, new PostConfiguration { Rate = 10 }),
new(postId,"name 2", PostType.Chef, new PostConfiguration { Rate = 10 })
};
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns(listOriginal);
//Act
@@ -157,7 +158,7 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new PostDataModel(id,"name", PostType.Chef, 10);
var record = new PostDataModel(id,"name", PostType.Chef, new PostConfiguration { Rate = 10 });
_postStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(id);
@@ -171,7 +172,7 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var postName = "name";
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, 10);
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, new PostConfiguration { Rate = 10 });
_postStorageContract.Setup(x => x.GetElementByName(postName)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(postName);
@@ -223,11 +224,11 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, 10);
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, 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;
});
//Act
_postBusinessLogicContract.InsertPost(record);
@@ -241,7 +242,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.Chef, 10)), Throws.TypeOf<ElementExistsException>());
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Chef, new PostConfiguration { Rate = 10 })), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
@@ -255,7 +256,7 @@ internal class PostBusinessLogicContractTests
public void InsertPost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Chef, 10)), Throws.TypeOf<ValidationException>());
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Chef, new PostConfiguration { Rate = 10 })), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
@@ -264,7 +265,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.Chef, 10)), Throws.TypeOf<StorageException>());
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Chef, new PostConfiguration { Rate = 10 })), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
@@ -272,11 +273,11 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, 10);
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, 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;
});
//Act
_postBusinessLogicContract.UpdatePost(record);
@@ -290,7 +291,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.Chef, 10)), Throws.TypeOf<ElementNotFoundException>());
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Chef, new PostConfiguration { Rate = 10 })), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x =>
x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
@@ -300,7 +301,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(), "name", PostType.Chef, 10)), Throws.TypeOf<ElementExistsException>());
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Chef, new PostConfiguration { Rate = 10 })), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
@@ -314,7 +315,7 @@ internal class PostBusinessLogicContractTests
public void UpdatePost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Chef, 10)), Throws.TypeOf<ValidationException>());
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Chef, new PostConfiguration { Rate = 10 })), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
@@ -323,7 +324,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.Chef, 10)), Throws.TypeOf<StorageException>());
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Chef, new PostConfiguration { Rate = 10 })), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]

View File

@@ -0,0 +1,342 @@
using AndDietCokeBuisnessLogic.BusinessLogicsContracts;
using AndDietCokeBuisnessLogic.Implementations;
using AndDietCokeBuisnessLogic.OfficePackage;
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Enums;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
namespace AndDietCokeTests.BusinessLogicContractsTests
{
internal class ReportContractTests
{
private IReportContract _reportContract;
private Mock<IDishStorageContract> _dishStorageContractMock;
private Mock<BaseWordBuilder> _baseWordBuilder;
private Mock<ISaleStorageContract> _saleStorageContract;
private Mock<BaseExcelBuilder> _baseExcelBuilder;
private Mock<ISalaryStorageContract> _salaryStorageContractMock;
private Mock<BasePdfBuilder> _basePdfBuilder;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_baseWordBuilder = new Mock<BaseWordBuilder>();
_dishStorageContractMock = new Mock<IDishStorageContract>();
_saleStorageContract = new Mock<ISaleStorageContract>();
_baseExcelBuilder = new Mock<BaseExcelBuilder>();
_basePdfBuilder = new Mock<BasePdfBuilder>();
_salaryStorageContractMock = new Mock<ISalaryStorageContract>();
_reportContract = new ReportContract(_dishStorageContractMock.Object, _saleStorageContract.Object, _salaryStorageContractMock.Object, new Mock<ILogger>().Object, _baseWordBuilder.Object, _baseExcelBuilder.Object, _basePdfBuilder.Object);
}
[SetUp]
public void SetUp()
{
_dishStorageContractMock.Reset();
_saleStorageContract.Reset();
_salaryStorageContractMock.Reset();
}
[Test]
public async Task GetDataBySaleByPeriod_ShouldSucces_Test()
{
_saleStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(new List<SaleDataModel>()
{
new SaleDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), false, false,new List<OrderDishDataModel>(){ new OrderDishDataModel(Guid.NewGuid().ToString(),Guid.NewGuid().ToString(),10, 1000)}),
new SaleDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), false, false,new List<OrderDishDataModel>(){ new OrderDishDataModel(Guid.NewGuid().ToString(),Guid.NewGuid().ToString(), 10, 1000)}),
}));
var data = _reportContract.GetDataSalesByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1), CancellationToken.None);
Assert.That(data, Is.Not.Null);
Assert.That(data.Result, Has.Count.EqualTo(2));
_saleStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public void GetDataBySaleByPeriod_WhenNoRecords_ShouldSuccess_Test()
{
_saleStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(new List<SaleDataModel>()));
var data = _reportContract.GetDataSalesByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1), CancellationToken.None);
Assert.That(data, Is.Not.Null);
Assert.That(data.Result, Is.Empty);
_saleStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public void GetDataBySales_WhenIncorrectDates_ShouldFail_Test()
{
var date = DateTime.UtcNow;
Assert.That(() => _reportContract.GetDataSalesByPeriodAsync(date, date.AddDays(-1), CancellationToken.None), Throws.TypeOf<IncorrectDatesException>());
}
[Test]
public async Task GetDataBySaleByPeriod_ShouldThrowException_Test()
{
_saleStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
.Throws(new StorageException(new InvalidOperationException()));
Assert.That(async () =>
await _reportContract.GetDataSalesByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1), 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 GetDataDishs_ShouldSucces()
{
// Arrange
var dish = new DishDataModel(Guid.NewGuid().ToString(), "Dish1", DishType.Dessert,100,false);
var dish2 = new DishDataModel(Guid.NewGuid().ToString(), "Dish2", DishType.Dessert, 100, false);
List<DishHistoryDataModel> dishPriceHistories = new List<DishHistoryDataModel>
{
new DishHistoryDataModel( dish.Id,100,DateTime.UtcNow, dish),
new DishHistoryDataModel( dish.Id, 200, DateTime.UtcNow, dish),
new DishHistoryDataModel( dish2.Id, 300, DateTime.UtcNow, dish2),
};
_dishStorageContractMock.Setup(x => x.GetHistoryAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult(dishPriceHistories));
// Act
var result = await _reportContract.GetDataDishPricesAsync(CancellationToken.None);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result, Is.Not.Empty);
Assert.Multiple(() =>
{
Assert.That(result.First(x => x.DishName == dish.DishName).DishPrices, Has.Count.EqualTo(2));
Assert.That(result.First(x => x.DishName == dish2.DishName).DishPrices, Has.Count.EqualTo(1));
});
}
[Test]
public async Task GetDataNoRecords_ShouldSuccess()
{
// Arrange
var dish = new DishDataModel(Guid.NewGuid().ToString(), "Dish1", DishType.Dessert, 231, false);
List<DishHistoryDataModel> dishPriceHistories = new List<DishHistoryDataModel>
{
};
_dishStorageContractMock.Setup(x => x.GetHistoryAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult(dishPriceHistories));
// Act
var result = await _reportContract.GetDataDishPricesAsync(CancellationToken.None);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result, Is.Empty);
_dishStorageContractMock.Verify(x => x.GetHistoryAsync(It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public async Task GetDataDishs_ShouldThrowException()
{
// Arrange
_dishStorageContractMock.Setup(x => x.GetHistoryAsync(It.IsAny<CancellationToken>())).Throws(new Exception("Test exception"));
// Act
var result = await _reportContract.GetDataDishPricesAsync(CancellationToken.None);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result, Is.Empty);
_dishStorageContractMock.Verify(x => x.GetHistoryAsync(It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public async Task CreateDocumentDishPricesByDish_ShouldSuccess()
{
// Arrange
var stream = new MemoryStream();
var dish = new DishDataModel(Guid.NewGuid().ToString(), "Dish1", DishType.Dessert, 100, false);
var dish2 = new DishDataModel(Guid.NewGuid().ToString(), "Dish2", DishType.Dessert, 100, false);
DateTime dateTimeToCheck = DateTime.UtcNow;
_dishStorageContractMock.Setup(x => x.GetHistoryAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult(new List<DishHistoryDataModel>
{
new DishHistoryDataModel( dish.Id,100,DateTime.UtcNow, dish),
new DishHistoryDataModel( dish2.Id,200,DateTime.UtcNow, dish2),
new DishHistoryDataModel( dish.Id, 200, DateTime.UtcNow, dish),
new DishHistoryDataModel( dish2.Id,300,DateTime.UtcNow, dish2),
}));
var countRows = 0;
string[] firstRow = [];
string[] secondRow = [];
_baseWordBuilder.Setup(x => x.AddHeader(It.IsAny<string>())).Returns(_baseWordBuilder.Object);
_baseWordBuilder.Setup(x => x.AddParagraph(It.IsAny<string>())).Returns(_baseWordBuilder.Object);
_baseWordBuilder.Setup(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>()))
.Callback((int[] widths, List<string[]> data) =>
{
countRows = data.Count;
firstRow = data[1];
secondRow = data[2];
})
.Returns(_baseWordBuilder.Object);
// Act
var data = await _reportContract.CreateDocumentDishPricesByDishAsync(CancellationToken.None);
// Assert
_dishStorageContractMock.Verify(x => x.GetHistoryAsync(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(7));
Assert.That(firstRow, Has.Length.EqualTo(3));
Assert.That(secondRow, Has.Length.EqualTo(3));
});
Assert.Multiple(() =>
{
Assert.That(firstRow[0], Is.EqualTo(dish.DishName));
Assert.That(secondRow[1], Is.EqualTo(100.ToString()));
Assert.That(secondRow[2], Is.EqualTo(dateTimeToCheck.ToString()));
});
}
[Test]
public async Task CreateDocumentSalesByPeriod_ShouldSucces()
{
// Arrange
var stream = new MemoryStream();
var dish1 = new DishDataModel(Guid.NewGuid().ToString(), "Dish1", DishType.Dessert, 100, false);
var dish2 = new DishDataModel(Guid.NewGuid().ToString(), "Dish2", DishType.Dessert, 100, false);
DateTime dateTimeToCheck = DateTime.UtcNow;
_saleStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(new List<SaleDataModel>
{
new SaleDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), false, false,new List<OrderDishDataModel>(){ new OrderDishDataModel(Guid.NewGuid().ToString(),Guid.NewGuid().ToString(),10,500)}),
new SaleDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), false, false,new List<OrderDishDataModel>(){ new OrderDishDataModel(Guid.NewGuid().ToString(),Guid.NewGuid().ToString(),10,500)}),
}));
_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[1];
secondRow = data[2];
})
.Returns(_baseExcelBuilder.Object);
// Act
var data = await _reportContract.CreateDocumentSalesByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1), CancellationToken.None);
//Assert
Assert.Multiple(() =>
{
Assert.That(countRows, Is.EqualTo(6));
Assert.That(firstRow, Is.Not.Default);
Assert.That(secondRow, Is.Not.Default);
});
Assert.Multiple(() =>
{
Assert.That(firstRow[0], Is.EqualTo(DateTime.Now.ToShortDateString()));
Assert.That(firstRow[1], Is.EqualTo(5000.ToString("N2")));
Assert.That(secondRow[3], Is.EqualTo(10.ToString()));
});
_saleStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
_baseExcelBuilder.Verify(x => x.AddHeader(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()), Times.Once);
_baseExcelBuilder.Verify(x => x.AddParagraph(It.IsAny<string>(), It.IsAny<int>()), Times.Once);
_baseExcelBuilder.Verify(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>()), Times.Once);
_baseExcelBuilder.Verify(x => x.Build(), Times.Once);
}
[Test]
public async Task GetDataSalaryByPeriod_ShouldSuccess_Test()
{
var startDate = DateTime.UtcNow.AddDays(-20);
var endDate = DateTime.UtcNow.AddDays(5);
var employee = new WorkerDataModel(Guid.NewGuid().ToString(), "Name", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-20),
DateTime.UtcNow.AddDays(-3));
var employee2 = new WorkerDataModel(Guid.NewGuid().ToString(), "Name 2", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-20),
DateTime.UtcNow.AddDays(-3));
_salaryStorageContractMock.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(new List<SalaryDataModel>()
{
new(Guid.NewGuid().ToString(), employee.Id,DateTime.UtcNow.AddDays(-10),100,employee),
new(Guid.NewGuid().ToString(), employee.Id, endDate, 1000,employee),
new(Guid.NewGuid().ToString(), employee.Id, startDate, 1000, employee),
new(Guid.NewGuid().ToString(), employee2.Id, DateTime.UtcNow.AddDays(-10),100, employee2),
new (Guid.NewGuid().ToString(), employee2.Id, DateTime.UtcNow.AddDays(-5),200, employee2)
}));
//Act
var data = await _reportContract.GetDataSalaryByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None);
//Assert
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(2));
var employeeSalary = data.First(x => x.WorkerFIO == employee.FIO);
Assert.That(employeeSalary, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(employeeSalary.TotalSalary, Is.EqualTo(2100));
Assert.That(employeeSalary.FromPeriod, Is.EqualTo(startDate));
Assert.That(employeeSalary.ToPeriod, Is.EqualTo(endDate));
});
var employee2Salary = data.First(x => x.WorkerFIO == employee2.FIO);
Assert.That(employee2Salary, Is.Not.Null);
Assert.That(employee2Salary.TotalSalary, Is.EqualTo(300));
_salaryStorageContractMock.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public async Task GetDataSalaryByPeriod_WhenNoRecords_ShouldSuccess_Test()
{
//Arrange
_salaryStorageContractMock.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(new List<SalaryDataModel>()));
//Act
var data = await _reportContract.GetDataSalaryByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None);
//Assert
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(0));
_salaryStorageContractMock.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public void GetDataBySalaryByPeriod_WhenStorageThrowError_ShouldFail_Test()
{
//Arrange
_salaryStorageContractMock.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.GetDataSalaryByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None), Throws.TypeOf<StorageException>());
_salaryStorageContractMock.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public async Task CreateDocumentSalaryByPeriod_ShouldeSuccess_Test()
{
//Arrange
var startDate = DateTime.UtcNow.AddDays(-20);
var endDate = DateTime.UtcNow.AddDays(5);
var worker1 = new WorkerDataModel(Guid.NewGuid().ToString(), "fio 1", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-20), DateTime.UtcNow.AddDays(-3));
var worker2 = new WorkerDataModel(Guid.NewGuid().ToString(), "fio 2", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-20), DateTime.UtcNow.AddDays(-3));
_salaryStorageContractMock.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(new List<SalaryDataModel>()
{
new(Guid.NewGuid().ToString(), worker1.Id, DateTime.UtcNow.AddDays(-10), 100, worker1),
new(Guid.NewGuid().ToString(), worker1.Id, endDate, 1000, worker1),
new(Guid.NewGuid().ToString(), worker1.Id, startDate, 1000, worker1),
new(Guid.NewGuid().ToString(), worker2.Id, DateTime.UtcNow.AddDays(-10), 100, worker2),
new(Guid.NewGuid().ToString(), worker2.Id, DateTime.UtcNow.AddDays(-5), 200, worker2)
}));
_basePdfBuilder.Setup(x => x.AddHeader(It.IsAny<string>())).Returns(_basePdfBuilder.Object);
_basePdfBuilder.Setup(x => x.AddParagraph(It.IsAny<string>())).Returns(_basePdfBuilder.Object);
var countRows = 0;
(string, double) firstRow = default;
(string, double) secondRow = default;
_basePdfBuilder.Setup(x => x.AddPieChart(It.IsAny<string>(), It.IsAny<List<(string, double)>>()))
.Callback((string header, List<(string, double)> data) =>
{
countRows = data.Count;
firstRow = data[0];
secondRow = data[1];
})
.Returns(_basePdfBuilder.Object);
//Act
var data = await _reportContract.CreateDocumentSalaryByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None);
//Assert
Assert.Multiple(() =>
{
Assert.That(countRows, Is.EqualTo(2));
Assert.That(firstRow, Is.Not.Default);
Assert.That(secondRow, Is.Not.Default);
});
Assert.Multiple(() =>
{
Assert.That(firstRow.Item1, Is.EqualTo(worker1.FIO));
Assert.That(firstRow.Item2, Is.EqualTo(2100));
Assert.That(secondRow.Item1, Is.EqualTo(worker2.FIO));
Assert.That(secondRow.Item2, Is.EqualTo(300));
});
_salaryStorageContractMock.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.AtLeast(3));
_basePdfBuilder.Verify(x => x.AddPieChart(It.IsAny<string>(), It.IsAny<List<(string, double)>>()), Times.Once);
_basePdfBuilder.Verify(x => x.Build(), Times.Once);
}
}
}

View File

@@ -11,6 +11,8 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using AndDietCokeContracts.Infrastrusture.PostConfiguration;
using AndDietCokeTests.Infrastructure;
namespace AndDietCokeTests.BuisnessLogicsContractsTests;
@@ -22,6 +24,7 @@ internal class SalaryBuisnessLogicContractTests
private Mock<ISaleStorageContract> _saleStorageContract;
private Mock<IPostStorageContract> _postStorageContract;
private Mock<IWorkerStorageContract> _workerStorageContract;
private readonly ConfigurationSalaryTest _salaryConfigurationTest = new();
[OneTimeSetUp]
public void OneTimeSetUp()
@@ -31,7 +34,7 @@ internal class SalaryBuisnessLogicContractTests
_postStorageContract = new Mock<IPostStorageContract>();
_workerStorageContract = new Mock<IWorkerStorageContract>();
_salaryBusinessLogicContract = new SalaryBusinessLogicContract(_salaryStorageContract.Object,
_saleStorageContract.Object, _postStorageContract.Object, _workerStorageContract.Object, new Mock<ILogger>().Object);
_saleStorageContract.Object, _postStorageContract.Object, _workerStorageContract.Object, new Mock<ILogger>().Object, _salaryConfigurationTest);
}
[SetUp]
@@ -206,7 +209,63 @@ internal class SalaryBuisnessLogicContractTests
new SaleDataModel(Guid.NewGuid().ToString(), worker3Id, null, true, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), worker3Id, null, true, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, 2000));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, new PostConfiguration { Rate = 2000 }));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns(list);
//Act
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
//Assert
_salaryStorageContract.Verify(x => x.AddElement(It.IsAny<SalaryDataModel>()), Times.Exactly(list.Count));
}
[Test]
public void CalculateSalaryByMounth_WithWaiterConfiguration_Test()
{
//Arrange
var worker1Id = Guid.NewGuid().ToString();
var worker2Id = Guid.NewGuid().ToString();
var worker3Id = Guid.NewGuid().ToString();
var list = new List<WorkerDataModel>() {
new(worker1Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
new(worker2Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
new(worker3Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)
};
_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(), worker1Id, null, true, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), worker1Id, null, true, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), worker2Id, null, true, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), worker3Id, null, true, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), worker3Id, null, true, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, new WaiterPostConfiguration { Rate = 2000 }));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns(list);
//Act
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
//Assert
_salaryStorageContract.Verify(x => x.AddElement(It.IsAny<SalaryDataModel>()), Times.Exactly(list.Count));
}
[Test]
public void CalculateSalaryByMounth_WithChefConfiguration_Test()
{
//Arrange
var worker1Id = Guid.NewGuid().ToString();
var worker2Id = Guid.NewGuid().ToString();
var worker3Id = Guid.NewGuid().ToString();
var list = new List<WorkerDataModel>() {
new(worker1Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
new(worker2Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
new(worker3Id, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)
};
_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(), worker1Id, null, true, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), worker1Id, null, true, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), worker2Id, null, true, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), worker3Id, null, true, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), worker3Id, null, true, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, new ChefPostConfiguration { Rate = 2000 }));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns(list);
//Act
@@ -224,11 +283,11 @@ internal class SalaryBuisnessLogicContractTests
_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.Chef, postSalary));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, new PostConfiguration { Rate = postSalary }));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
var sum = 0.0;
var expectedSum = 100;
var expectedSum = 2000;
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
.Callback((SalaryDataModel x) =>
{
@@ -240,13 +299,15 @@ internal class SalaryBuisnessLogicContractTests
Assert.That(sum, Is.EqualTo(expectedSum));
}
[Test]
public void CalculateSalaryByMounth_SaleStorageReturnNull_ThrowException_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, 2000));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, new PostConfiguration { Rate = 2000 }));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
@@ -262,7 +323,7 @@ internal class SalaryBuisnessLogicContractTests
_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(), workerId, null, true, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, 2000));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, new PostConfiguration { Rate = 2000 }));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
@@ -275,7 +336,7 @@ internal class SalaryBuisnessLogicContractTests
_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.Chef, 2000));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, new PostConfiguration { Rate = 2000 }));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
@@ -290,7 +351,7 @@ internal class SalaryBuisnessLogicContractTests
_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(), workerId, null, true, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, 2000));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chef, new PostConfiguration { Rate = 2000 }));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert

View File

@@ -1,9 +1,11 @@
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Enums;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.Infrastrusture.PostConfiguration;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@@ -16,53 +18,62 @@ internal class PostDataModelTests
[Test]
public void IdIsNullOrEmptyTest()
{
var post = CreateDataModel("0", "name", PostType.Waiter, 10, true, DateTime.UtcNow);
var post = CreateDataModel("0", "name", PostType.Waiter, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(string.Empty, "name", PostType.Waiter, 10, true, DateTime.UtcNow);
post = CreateDataModel(string.Empty, "name", PostType.Waiter, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var post = CreateDataModel("id", "name", PostType.Waiter, 10, true, DateTime.UtcNow);
var post = CreateDataModel("id", "name", PostType.Waiter, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostIdIsNullEmptyTest()
{
var post = CreateDataModel("0", "name", PostType.Waiter, 10, true, DateTime.UtcNow);
var post = CreateDataModel("0", "name", PostType.Waiter, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel("0", "name", PostType.Waiter, 10, true, DateTime.UtcNow);
post = CreateDataModel("0", "name", PostType.Waiter, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostIdIsNotGuidTest()
{
var post = CreateDataModel("0", "name", PostType.Waiter, 10, true, DateTime.UtcNow);
var post = CreateDataModel("0", "name", PostType.Waiter, new PostConfiguration() { Rate = 110 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostNameIsEmptyTest()
{
var manufacturer = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Waiter, 10, true, DateTime.UtcNow);
var manufacturer = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Waiter, new PostConfiguration() { Rate = 10 });
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
manufacturer = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Waiter, 10, true, DateTime.UtcNow);
manufacturer = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Waiter, 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, true, DateTime.UtcNow);
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.Waiter, 0, true, DateTime.UtcNow);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Waiter, -10, true, DateTime.UtcNow);
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Waiter, null);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void RateIsLessOrZeroTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Waiter, new PostConfiguration() { Rate = 0 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Waiter, new PostConfiguration() { Rate = -10 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void AllFieldsIsCorrectTest()
{
@@ -70,20 +81,19 @@ internal class PostDataModelTests
var postPostId = Guid.NewGuid().ToString();
var postName = "name";
var postType = PostType.Waiter;
var salary = 10;
var isActual = false;
var changeDate = DateTime.UtcNow.AddDays(-1);
var post = CreateDataModel(postId, postName, postType, salary, isActual, changeDate);
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, Is.EqualTo(configuration));
Assert.That(post.ConfigurationModel.Rate, Is.EqualTo(configuration.Rate));
});
}
private static PostDataModel CreateDataModel(string? id, string? postName, PostType postType, double salary, bool isActual, DateTime changeDate) => new(id, postName, postType, salary);
private static PostDataModel CreateDataModel(string id, string postName, PostType postType, PostConfiguration configuration) => new(id, postName, postType, configuration);
}

View File

@@ -8,6 +8,7 @@ using System.Text;
using System.Threading.Tasks;
using static NUnit.Framework.Internal.OSPlatform;
using Microsoft.EntityFrameworkCore;
using AndDietCokeContracts.Infrastrusture.PostConfiguration;
namespace AndDietCokeTests.Infrastructure;
@@ -23,7 +24,7 @@ internal static class AndDietCokeDbContextExtensions
public static Post InsertPostToDatabaseAndReturn(this AndDietCokeDbContext dbContext, string? id = null, string postName = "test", PostType postType = PostType.Packer, double salary = 10, bool isActual = true, DateTime? changeDate = null)
{
var post = new Post() { Id = Guid.NewGuid().ToString(), PostId = id ?? Guid.NewGuid().ToString(), PostName = postName, PostType = postType, 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 = new PostConfiguration { Rate = salary }, IsActual = isActual, ChangeDate = changeDate ?? DateTime.UtcNow };
dbContext.Posts.Add(post);
dbContext.SaveChanges();
return post;
@@ -57,12 +58,13 @@ internal static class AndDietCokeDbContextExtensions
public static Sale InsertSaleToDatabaseAndReturn(this AndDietCokeDbContext dbContext, string workerId, string? buyerId = null, DateTime? saleDate = null, double sum = 1, bool isConstantClient = false, bool isCancel = false, List<(string, int, double)>? dishes = null)
{
var sale = new Sale() { WorkerId = workerId, BuyerId = buyerId, SaleDate = saleDate ?? DateTime.UtcNow, Sum = sum, IsConstantClient = isConstantClient, IsCancel = isCancel, OrderDishes = [] };
var sale = new Sale() { WorkerId = workerId, BuyerId = buyerId, SaleDate = saleDate ?? DateTime.UtcNow, IsConstantClient = isConstantClient, IsCancel = isCancel, OrderDishes = [] };
if (dishes is not null)
{
foreach (var elem in dishes)
{
sale.OrderDishes.Add(new OrderDish { DishId = elem.Item1, OrderId = sale.Id, Count = elem.Item2 });
sale.Sum += elem.Item3 * elem.Item2; // Assuming elem.Item3 is the price per dish
}
}
dbContext.Sales.Add(sale);

View File

@@ -10,5 +10,5 @@ namespace AndDietCokeTests.Infrastructure;
internal class ConfigurationDatabaseTest : IConfigurationDatabase
{
public string ConnectionString =>
"Host=127.0.0.1;Port=5432;Database=OTP_1;Username=postgres;Password=030405;";
"Host=127.0.0.1;Port=5432;Database=OTP_1;Username=postgres;Password=postgres;";
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AndDietCokeContracts.Infrastrusture;
namespace AndDietCokeTests.Infrastructure;
class ConfigurationSalaryTest : IConfigurationSalary
{
public double ExtraSaleSum => 10;
public int MaxConcurrentThreads => 4;
}

View File

@@ -106,7 +106,25 @@ internal class DishStorageContractTests : BaseStorageContractTest
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
}
[Test]
public void Try_GetHistoryAsync_ShouldSucces()
{
var dish = AndDietCokeDbContext.InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), dishName: "name 1");
var dishPrice = AndDietCokeDbContext.InsertDishHistoryToDatabaseAndReturn(dish.Id, 20, DateTime.UtcNow.AddDays(-1));
AndDietCokeDbContext.InsertDishHistoryToDatabaseAndReturn(dish.Id, 30, DateTime.UtcNow.AddMinutes(-10));
AndDietCokeDbContext.InsertDishHistoryToDatabaseAndReturn(dish.Id, 40, DateTime.UtcNow.AddDays(1));
var list = _dishStorageContract.GetHistoryAsync(CancellationToken.None).Result;
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(list => list.DishId == dishPrice.DishId), dishPrice);
}
[Test]
public void Try_GetHistoryAsync_WhenNoRecords_Test()
{
var list = _dishStorageContract.GetHistoryAsync(CancellationToken.None).Result;
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
@@ -293,4 +311,14 @@ internal class DishStorageContractTests : BaseStorageContractTest
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
});
}
private static void AssertElement(DishHistoryDataModel? actual, DishHistory expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.DishId, Is.EqualTo(expected.DishId));
Assert.That(actual.OldPrice, Is.EqualTo(expected.OldPrice));
Assert.That(actual.ChangeDate, Is.EqualTo(expected.ChangeDate));
});
}
}

View File

@@ -12,6 +12,7 @@ using AndDietCokeDatabase.Implementations;
using Microsoft.EntityFrameworkCore;
using AndDietCokeDatabase.Models;
using AndDietCokeTests.Infrastructure;
using AndDietCokeContracts.Infrastrusture.PostConfiguration;
namespace AndDietCokeTests.StoragesContracts;
@@ -35,13 +36,12 @@ internal class PostStorageContractTests : BaseStorageContractTest
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var post = AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postName: "name 1");
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postName: "name 2");
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(postName: "name 3");
var post = AndDietCokeDbContext.InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), postName: "name 1");
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), postName: "name 2");
AndDietCokeDbContext.InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), 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.Id), post);
}
[Test]
@@ -79,7 +79,7 @@ internal class PostStorageContractTests : BaseStorageContractTest
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var post = AndDietCokeDbContext.InsertPostToDatabaseAndReturn();
var post = AndDietCokeDbContext.InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_postStorageContract.GetElementById(post.PostId), post);
}
@@ -107,7 +107,7 @@ internal class PostStorageContractTests : BaseStorageContractTest
[Test]
public void Try_GetElementByName_WhenHaveRecord_Test()
{
var post = AndDietCokeDbContext.InsertPostToDatabaseAndReturn();
var post = AndDietCokeDbContext.InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
AssertElement(_postStorageContract.GetElementByName(post.PostName), post);
}
@@ -237,16 +237,16 @@ internal class PostStorageContractTests : BaseStorageContractTest
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.Id));
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.Salary, Is.EqualTo(expected.Salary));
Assert.That(actual.ConfigurationModel.Rate, Is.EqualTo(expected.Configuration.Rate));
});
}
private static PostDataModel CreateModel(string postId, string postName = "test", PostType postType = PostType.Packer, double salary = 10, bool isActive = true, DateTime? changeDate = null)
{
return new(postId, postName, postType, salary);
return new(postId, postName, postType, new PostConfiguration { Rate = salary });
}
private static void AssertElement(Post? actual, PostDataModel expected)
@@ -257,7 +257,7 @@ internal class PostStorageContractTests : BaseStorageContractTest
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.Salary, Is.EqualTo(expected.Salary));
Assert.That(actual.Configuration.Rate, Is.EqualTo(expected.ConfigurationModel.Rate));
});
}
}

View File

@@ -103,7 +103,25 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
Assert.That(list.All(x => x.WorkerId == _worker.Id));
});
}
[Test]
public async Task Try_GetListAsync_ByPeriod_Test()
{
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
var list = await _salaryStorageContract.GetListAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1), CancellationToken.None);
Assert.That(list, Is.Not.Null);
Assert.That(list.Count, Is.EqualTo(2));
}
[Test]
public async Task Try_GetListAsync_WhenNoRecords_Test()
{
var list = await _salaryStorageContract.GetListAsync(DateTime.UtcNow.AddDays(-10), DateTime.UtcNow.AddDays(10), CancellationToken.None);
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_AddElement_Test()
{

View File

@@ -140,7 +140,24 @@ internal class SaleStorageContractTests : BaseStorageContractTest
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, dishes: [(_dish.Id, 1, 1.2)]);
Assert.That(() => _saletStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public async Task Try_GetListAsync_ByPeriod_Test()
{
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.Date.AddDays(-1).AddMinutes(-3), dishes: [(_dish.Id,10,10)]);
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, _buyer.Id, saleDate: DateTime.UtcNow.Date.AddDays(-1).AddMinutes(3), dishes: [(_dish.Id, 10, 10)]);
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, null, saleDate: DateTime.UtcNow.Date.AddDays(1).AddMinutes(-3), dishes: [(_dish.Id, 10, 10)]);
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_worker.Id, null, saleDate: DateTime.UtcNow.Date.AddDays(1).AddMinutes(3), dishes: [(_dish.Id, 10, 10)]);
var list = await _saletStorageContract.GetListAsync(startDate: DateTime.UtcNow.Date.AddDays(-1), endDate: DateTime.UtcNow.Date.AddDays(1), CancellationToken.None);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
}
[Test]
public async Task Try_GetListAsync_WhenNoRecords_Test()
{
var list = await _saletStorageContract.GetListAsync(startDate: DateTime.UtcNow.Date.AddDays(-1), endDate: DateTime.UtcNow.Date.AddDays(1), CancellationToken.None);
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetElementById_WhenRecordHasCanceled_Test()
{

View File

@@ -1,13 +1,17 @@
using AndDietCokeContracts.BindingModels;
using AndDietCokeContracts.Enums;
using AndDietCokeContracts.Infrastrusture.PostConfiguration;
using AndDietCokeContracts.ViewModels;
using AndDietCokeDatabase.Models;
using AndDietCokeTests.Infrastructure;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
namespace AndDietCokeTests.WebApiControllersTests;
@@ -160,10 +164,10 @@ internal class PostControllerTests : BaseWebApiControllerTest
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
{
//Arrange
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.Packer.ToString(), Salary = 10 };
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Packer.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.Packer.ToString(), Salary = -10 };
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.Packer.ToString(), ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Packer.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.Packer.ToString(), ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = -10 }) };
//Act
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithIdIncorrect));
var responseWithNameIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithNameIncorrect));
@@ -252,10 +256,10 @@ internal class PostControllerTests : BaseWebApiControllerTest
public async Task Put_WhenDataIsIncorrect_ShouldBadRequest_Test()
{
//Arrange
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.Packer.ToString(), Salary = 10 };
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Packer.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.Packer.ToString(), Salary = -10 };
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.Packer.ToString(), ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Packer.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.Packer.ToString(), ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = -10 }) };
//Act
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithIdIncorrect));
var responseWithNameIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithNameIncorrect));
@@ -392,7 +396,7 @@ internal class PostControllerTests : BaseWebApiControllerTest
{
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));
});
}
@@ -402,7 +406,7 @@ internal class PostControllerTests : BaseWebApiControllerTest
Id = postId ?? Guid.NewGuid().ToString(),
PostName = postName,
PostType = postType.ToString(),
Salary = salary
ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = salary })
};
private static void AssertElement(Post? actual, PostBindingModel expected)
@@ -412,7 +416,7 @@ internal class PostControllerTests : BaseWebApiControllerTest
{
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,191 @@
using System.Net;
using AndDietCokeContracts.ViewModels;
using AndDietCokeTests.Infrastructure;
namespace AndDietCokeTests.WebApiControllersTests
{
internal class ReportControllerTests : BaseWebApiControllerTest
{
[TearDown]
public void TearDown()
{
AndDietCokeDbContext.RemoveDishesFromDatabase();
AndDietCokeDbContext.RemoveSalesFromDatabase();
AndDietCokeDbContext.RemoveBuyersFromDatabase();
AndDietCokeDbContext.RemovePostsFromDatabase();
AndDietCokeDbContext.RemoveWorkersFromDatabase();
AndDietCokeDbContext.RemoveSalariesFromDatabase();
}
[Test]
public async Task GetSales_WhenHaveRecords_ShouldSucces_Test()
{
// Arrange
var worker = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn();
var buyer = AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn();
var dish1 = AndDietCokeDbContext.InsertDishToDatabaseAndReturn();
var dish2 = AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: "CustomNameOfDish");
var sale = AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(workerId:worker.Id, buyerId:buyer.Id, dishes: [(dish1.Id, 10,100),(dish2.Id,5,20)]);
var sale2 = AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(workerId: worker.Id, buyerId: buyer.Id, dishes: [(dish1.Id, 8, 100)]);
// Act
var result = await HttpClient.GetAsync($"/api/report/GetSalesByPeriod?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(result);
Assert.That(data, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(data, Has.Count.EqualTo(2));
});
}
[Test]
public async Task GetSales_WhenDatesIncorrect_ShouldBadRequest()
{
var response = await HttpClient.GetAsync($"/api/report/GetSalesByPeriod?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 GetDishsWhenHaveRecords_ShouldSucces()
{
// Arrange
var dish = AndDietCokeDbContext.InsertDishToDatabaseAndReturn();
var dish2 = AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName:"CustomNameOfDish");
AndDietCokeDbContext.InsertDishHistoryToDatabaseAndReturn(dish.Id, 100, DateTime.UtcNow);
AndDietCokeDbContext.InsertDishHistoryToDatabaseAndReturn(dish.Id, 200, DateTime.UtcNow);
AndDietCokeDbContext.InsertDishHistoryToDatabaseAndReturn(dish2.Id, 300, DateTime.UtcNow);
// Act
var result = await HttpClient.GetAsync("/api/Report/GetDishes");
Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<DishPriceReportViewModel>>(result);
Assert.That(data, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(data, Has.Count.EqualTo(2));
Assert.That(data.First(x => x.DishName == dish.DishName).DishPrices, Has.Count.EqualTo(2));
Assert.That(data.First(x => x.DishName == dish2.DishName).DishPrices, Has.Count.EqualTo(1));
});
}
[Test]
public async Task LoadDishs_WhenHaveRecords_ShouldSuccess()
{
// Arrange
var dish = AndDietCokeDbContext.InsertDishToDatabaseAndReturn();
var dish2 = AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: "CustomNameOfDish");
AndDietCokeDbContext.InsertDishHistoryToDatabaseAndReturn(dish.Id, 100, DateTime.UtcNow.AddDays(-5));
AndDietCokeDbContext.InsertDishHistoryToDatabaseAndReturn(dish.Id, 200, DateTime.UtcNow.AddDays(-1));
AndDietCokeDbContext.InsertDishHistoryToDatabaseAndReturn(dish2.Id, 300, DateTime.UtcNow);
// Act
var result = await HttpClient.GetAsync("/api/Report/LoadDishes");
await AssertStreamAsync(result, "file.docx");
}
[Test]
public async Task LoadSales_WhenHaveRecords_ShouldSucces()
{
// Arrange
var date = DateTime.UtcNow.AddMinutes(-1);
var worker = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio:"Работник 1");
var worker2 = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "Работник 2");
var buyer = AndDietCokeDbContext.InsertBuyerToDatabaseAndReturn();
var dish1 = AndDietCokeDbContext.InsertDishToDatabaseAndReturn();
var dish2 = AndDietCokeDbContext.InsertDishToDatabaseAndReturn(dishName: "CustomNameOfDish");
var sale = AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(workerId: worker.Id, buyerId: buyer.Id, dishes: [(dish1.Id, 10, 100), (dish2.Id, 5, 20)]);
var sale2 = AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(workerId: worker2.Id, buyerId: buyer.Id, dishes: [(dish1.Id, 4, 85)]);
// Act
var result = await HttpClient.GetAsync($"/api/Report/LoadSales?fromDate={date:MM/dd/yyyy HH:mm:ss}&toDate={date.AddDays(1):MM/dd/yyyy HH:mm:ss}");
await AssertStreamAsync(result, "file.xlsx");
}
[Test]
public async Task LoadSales_WhenDatesIncorrect_ShouldBadRequest()
{
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 GetSalary_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var post = AndDietCokeDbContext.InsertPostToDatabaseAndReturn();
var worker1 = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: post.PostId).AddPost(post);
var worker2 = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: post.PostId).AddPost(post);
AndDietCokeDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, workerSalary: 100, salaryDate: DateTime.UtcNow.AddDays(-10));
AndDietCokeDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, workerSalary: 1000, salaryDate: DateTime.UtcNow.AddDays(-5));
AndDietCokeDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, workerSalary: 200, salaryDate: DateTime.UtcNow.AddDays(5));
AndDietCokeDbContext.InsertSalaryToDatabaseAndReturn(worker2.Id, workerSalary: 500, salaryDate: DateTime.UtcNow.AddDays(-5));
AndDietCokeDbContext.InsertSalaryToDatabaseAndReturn(worker2.Id, workerSalary: 300, salaryDate: DateTime.UtcNow.AddDays(-3));
//Act
var response = await HttpClient.GetAsync($"/api/report/getsalary?fromDate={DateTime.UtcNow.AddDays(-7):MM/dd/yyyy}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<WorkerSalaryViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(2));
Assert.Multiple(() =>
{
Assert.That(data.First(x => x.WorkerFIO == worker1.FIO).TotalSalary, Is.EqualTo(1000));
Assert.That(data.First(x => x.WorkerFIO == worker2.FIO).TotalSalary, Is.EqualTo(800));
});
}
[Test]
public async Task GetSalary_WhenDateIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/report/getsalary?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 post = AndDietCokeDbContext.InsertPostToDatabaseAndReturn();
var worker1 = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: post.PostId).AddPost(post);
var worker2 = AndDietCokeDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: post.PostId).AddPost(post);
AndDietCokeDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, workerSalary: 100, salaryDate: DateTime.UtcNow.AddDays(-10));
AndDietCokeDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, workerSalary: 1000, salaryDate: DateTime.UtcNow.AddDays(-5));
AndDietCokeDbContext.InsertSalaryToDatabaseAndReturn(worker1.Id, workerSalary: 200, salaryDate: DateTime.UtcNow.AddDays(5));
AndDietCokeDbContext.InsertSalaryToDatabaseAndReturn(worker2.Id, workerSalary: 500, salaryDate: DateTime.UtcNow.AddDays(-5));
AndDietCokeDbContext.InsertSalaryToDatabaseAndReturn(worker2.Id, workerSalary: 300, salaryDate: DateTime.UtcNow.AddDays(-3));
//Act
var response = await HttpClient.GetAsync($"/api/report/loadsalary?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 LoadSalary_WhenDateIsIncorrect_ShouldBadRequest_Test()
{
//Act
var response = await HttpClient.GetAsync($"/api/report/loadsalary?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

@@ -171,7 +171,7 @@ internal class SalaryControllerTests : BaseWebApiControllerTest
Assert.Multiple(() =>
{
Assert.That(salaries, Has.Length.EqualTo(1));
Assert.That(salaries.First().WorkerSalary, Is.EqualTo(100));
Assert.That(salaries.First().WorkerSalary, Is.EqualTo(1000));
Assert.That(salaries.First().SalaryDate.Month, Is.EqualTo(DateTime.UtcNow.Month));
});
}

View File

@@ -39,9 +39,9 @@ internal class SaleControllerTests : BaseWebApiControllerTest
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var sale = AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, buyerId: _buyerId, sum: 10, dishes: [(_dishId, 10, 1.1)]);
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, dishes: [(_dishId, 10, 1.1)]);
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, dishes: [(_dishId, 10, 1.1)]);
var sale = AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, buyerId: _buyerId, sum: 11.1, dishes: [(_dishId, 10, 1.1)]);
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, dishes: [(_dishId, 10, 1.2)]);
AndDietCokeDbContext.InsertSaleToDatabaseAndReturn(_workerId, dishes: [(_dishId, 10, 1.3)]);
//Act
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert

View File

@@ -6,6 +6,7 @@ using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.ViewModels;
using AutoMapper;
using System.Text.Json;
namespace AndDietCokeWebApi.Adapters;
@@ -17,6 +18,7 @@ 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 +26,7 @@ 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);
}

View File

@@ -0,0 +1,194 @@
using AndDietCokeBuisnessLogic.BusinessLogicsContracts;
using AndDietCokeContracts.AdapterContracts;
using AndDietCokeContracts.AdapterContracts.OperationResponses;
using AndDietCokeContracts.DataModels;
using AndDietCokeContracts.Exceptions;
using AndDietCokeContracts.ViewModels;
using AutoMapper;
namespace AndDietCokeWebApi.Adapters
{
public class ReportAdapter : IReportAdapter
{
private readonly IReportContract _reportContract;
private readonly ILogger _logger;
private readonly Mapper _mapper;
public ReportAdapter(IReportContract reportContract, ILogger logger)
{
_reportContract = reportContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<DishPriceReportDataModel, DishPriceReportViewModel>();
cfg.CreateMap<SaleDataModel, SaleViewModel>();
cfg.CreateMap<OrderDishDataModel,OrderDishViewModel>();
cfg.CreateMap<WorkerSalaryDataModel, WorkerSalaryViewModel>();
});
_mapper = new Mapper(config);
}
public async Task<ReportOperationResponse> CreateDocumentDishPricesByDishAsync(CancellationToken cancellationToken)
{
try
{
return SendStream(await _reportContract.CreateDocumentDishPricesByDishAsync(cancellationToken), "dishes.docx");
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "InvalidOperationException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return ReportOperationResponse.InternalServerError(ex.Message);
}
}
public async Task<ReportOperationResponse> GetSalesByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken cancellationToken)
{
try
{
return ReportOperationResponse.OK((await _reportContract.GetDataSalesByPeriodAsync(dateStart, dateFinish, cancellationToken)).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");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return ReportOperationResponse.InternalServerError(ex.Message);
}
}
public async Task<ReportOperationResponse> GetDishPricesByDishAsync(CancellationToken cancellationToken)
{
try
{
return ReportOperationResponse.OK([..( await _reportContract.GetDataDishPricesAsync(cancellationToken)).Select(x=>_mapper.Map<DishPriceReportViewModel>(x))]);
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "InvalidOperationException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return ReportOperationResponse.InternalServerError(ex.Message);
}
}
public async Task<ReportOperationResponse> CreateDocumentSalesByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken cancellationToken)
{
try
{
return SendStream(await _reportContract.CreateDocumentSalesByPeriodAsync(dateStart, dateFinish, cancellationToken), "tourPackages.docx");
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "InvalidOperationException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch(IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return ReportOperationResponse.InternalServerError(ex.Message);
}
}
public async Task<ReportOperationResponse> GetDataSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken cancellationToken)
{
try
{
return ReportOperationResponse.OK((await _reportContract.GetDataSalaryByPeriodAsync(dateStart, dateFinish, cancellationToken)).Select(x => _mapper.Map<WorkerSalaryViewModel>(x)).ToList());
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "InvalidOperationException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return ReportOperationResponse.InternalServerError(ex.Message);
}
}
public async Task<ReportOperationResponse> CreateDocumentSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
try
{
return SendStream(await _reportContract.CreateDocumentSalaryByPeriodAsync(dateStart, dateFinish, ct), "salary.pdf");
}
catch (IncorrectDatesException ex)
{
_logger.LogError(ex, "IncorrectDatesException");
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
}
catch (InvalidOperationException ex)
{
_logger.LogError(ex, "InvalidOperationException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
}
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

@@ -11,6 +11,10 @@
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.4" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="NSwag.AspNetCore" Version="14.3.0" />
<PackageReference Include="NUnit" Version="4.3.2" />
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" />

View File

@@ -0,0 +1,53 @@
using AndDietCokeContracts.AdapterContracts;
using AndDietCokeWebApi.Adapters;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace AndDietCokeWebApi.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> GetDishes(CancellationToken ct)
{
return (await _adapter.GetDishPricesByDishAsync(ct)).GetResponse(Request, Response);
}
[HttpGet]
[Consumes("application/octet-stream")]
public async Task<IActionResult> LoadDishes(CancellationToken cancellationToken)
{
return (await _adapter.CreateDocumentDishPricesByDishAsync(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/json")]
public async Task<IActionResult> GetSalesByPeriod(DateTime fromDate, DateTime toDate, CancellationToken ct)
{
return (await _adapter.GetSalesByPeriodAsync(fromDate, toDate, ct)).GetResponse(Request, Response);
}
[HttpGet]
[Consumes("application/json")]
public async Task<IActionResult> GetSalary(DateTime fromDate, DateTime toDate, CancellationToken cancellationToken)
{
return (await _adapter.GetDataSalaryByPeriodAsync(fromDate, toDate, cancellationToken)).GetResponse(Request, Response);
}
[HttpGet]
[Consumes("application/octet-stream")]
public async Task<IActionResult> LoadSalary(DateTime fromDate, DateTime toDate, CancellationToken cancellationToken)
{
return (await _adapter.CreateDocumentSalaryByPeriodAsync(fromDate, toDate, cancellationToken)).GetResponse(Request, Response);
}
}
}

View File

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

View File

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

View File

@@ -14,6 +14,8 @@ using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using AndDietCokeContracts.AdapterContracts;
using AndDietCokeWebApi.Adapters;
using AndDietCokeBuisnessLogic.BusinessLogicsContracts;
using AndDietCokeBuisnessLogic.OfficePackage;
var builder = WebApplication.CreateBuilder(args);
@@ -49,6 +51,7 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
});
builder.Services.AddSingleton<IConfigurationDatabase, ConfigurationDatabase>();
builder.Services.AddSingleton<IConfigurationSalary, ConfigurationSalary>();
builder.Services.AddTransient<IBuyerBusinessLogicContract, BuyerBusinessLogicContract>();
builder.Services.AddTransient<IPostBusinessLogicContract, PostBusinessLogicContract>();
@@ -73,6 +76,11 @@ builder.Services.AddTransient<ISaleAdapter, SaleAdapter>();
builder.Services.AddTransient<IWorkerAdapter, WorkerAdapter>();
builder.Services.AddTransient<IReportContract, ReportContract>();
builder.Services.AddTransient<BaseWordBuilder, OpenXmlWordBuilder>();
builder.Services.AddTransient<BasePdfBuilder, MigraDocPdfBuilder>();
builder.Services.AddTransient<BaseExcelBuilder, OpenXmlExcelBuilder>();
builder.Services.AddTransient<IReportAdapter, ReportAdapter>();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddOpenApi();

View File

@@ -1,28 +1,36 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": {
"Default": "Information"
},
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "../logs/anddietcoke-.log",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {CorrelationId} {Level:u3} {Username} {Message:lj}{Exception}{NewLine}"
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
]
},
"AllowedHosts": "*",
"DataBaseSettings": {
"ConnectionString": "Host=127.0.0.1;Port=5432;Database=OTP_1;Username=postgres;Password=030405;"
}
},
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": {
"Default": "Information"
},
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "../logs/anddietcoke-.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=OTP_1;Username=postgres;Password=030405;"
},
"SalarySettings": {
"ExtraSaleSum": 1000,
"MaxConcurrentThreads": 4
},
"WaiterSettings": {
"SalePercent": 0.05,
"BonusForExtraSales": 0.1
}
}