Compare commits
1 Commits
lab-8-hard
...
lab-6
| Author | SHA1 | Date | |
|---|---|---|---|
| 8fa02a428f |
@@ -11,7 +11,9 @@
|
||||
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="DocumentFormat.OpenXml" Version="3.3.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.2" />
|
||||
<PackageReference Include="PDFsharp-MigraDoc" Version="6.2.0-preview-3" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -10,6 +10,7 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
using CandyHouseContracts.BusinessLogicContracts;
|
||||
|
||||
namespace CandyHouseBusinessLogic.Implementations;
|
||||
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
using CandyHouseBusinessLogic.OfficePackage;
|
||||
using CandyHouseContracts.BusinessLogicContracts;
|
||||
using CandyHouseContracts.DataModels;
|
||||
using CandyHouseContracts.Exceptions;
|
||||
using CandyHouseContracts.Extensions;
|
||||
using CandyHouseContracts.StoragesContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace CandyHouseBusinessLogic.Implementations;
|
||||
|
||||
internal class ReportContract(
|
||||
IProductStorageContract productStorageContract,
|
||||
ISaleStorageContract saleStorageContract,
|
||||
IClientDiscountStorageContract clientDiscountStorageContract,
|
||||
BaseWordBuilder baseWordBuilder,
|
||||
BaseExcelBuilder baseExcelBuilder,
|
||||
BasePdfBuilder basePdfBuilder,
|
||||
ILogger logger) : IReportContract
|
||||
{
|
||||
private readonly IProductStorageContract _productStorageContract = productStorageContract;
|
||||
|
||||
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
|
||||
|
||||
private readonly IClientDiscountStorageContract _clientDiscountStorageContract = clientDiscountStorageContract;
|
||||
|
||||
private readonly BaseWordBuilder _baseWordBuilder = baseWordBuilder;
|
||||
|
||||
private readonly BaseExcelBuilder _baseExcelBuilder = baseExcelBuilder;
|
||||
|
||||
private readonly BasePdfBuilder _basePdfBuilder = basePdfBuilder;
|
||||
|
||||
private readonly ILogger _logger = logger;
|
||||
|
||||
internal static readonly string[] documentHeader = ["Продукт", "Цена", "Дата"];
|
||||
|
||||
internal static readonly string[] tableHeader = ["Дата", "Сумма", "Скидка", "Продавец", "Товар", "Кол-во"];
|
||||
|
||||
public async Task<Stream> CreateDocumentProductHistoryPricesAsync(CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Create report ProductHistoryPrices");
|
||||
var data = await GetDataByHistoryPricesAsync(ct);
|
||||
return _baseWordBuilder
|
||||
.AddHeader("История цен на продукцию")
|
||||
.AddParagraph($"Сформировано на дату {DateTime.UtcNow}")
|
||||
.AddTable([3000, 5000, 4000],
|
||||
[
|
||||
.. new List<string[]>() { documentHeader }.Union([
|
||||
.. data.SelectMany(x =>
|
||||
(new List<string[]>() { new string[] { x.ProductName, "", "" } }).Union(x.Prices.Select(y =>
|
||||
new string[] { "", y.Split(" (")[0], y.Split(" (")[1].TrimEnd(')') })))
|
||||
])
|
||||
])
|
||||
.Build();
|
||||
}
|
||||
|
||||
public async Task<Stream> CreateDocumentSalesByPeriodAsync(DateTime dateStart, DateTime dateFinish,
|
||||
CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Create report SalesByPeriod from {dateStart} to {dateFinish}", dateStart, dateFinish);
|
||||
var data = await GetDataBySalesAsync(dateStart, dateFinish, ct) ??
|
||||
throw new InvalidOperationException("No found data");
|
||||
return _baseExcelBuilder
|
||||
.AddHeader("Продажи за период", 0, 6)
|
||||
.AddParagraph($"c {dateStart.ToShortDateString()} по {dateFinish.ToShortDateString()}", 2)
|
||||
.AddTable([10, 10, 10, 10, 10, 10],
|
||||
[
|
||||
.. new List<string[]>() { tableHeader }.Union(data.SelectMany(x =>
|
||||
(new List<string[]>()
|
||||
{
|
||||
new string[]
|
||||
{
|
||||
x.SaleDate.ToShortDateString(), x.Sum.ToString("N2"), x.Discount.ToString("N2"),
|
||||
x.EmployeeFIO, "", ""
|
||||
}
|
||||
}).Union(x.Products!.Select(y => new string[]
|
||||
{ "", "", "", "", y.ProductName, y.Count.ToString("N2") })).ToArray())).Union([
|
||||
["Всего", data.Sum(x => x.Sum).ToString("N2"), data.Sum(x => x.Discount).ToString("N2"), "", "", ""]
|
||||
])
|
||||
])
|
||||
.Build();
|
||||
}
|
||||
|
||||
public async Task<Stream> CreateDocumentClientDiscountByPeriodAsync(DateTime dateStart, DateTime dateFinish,
|
||||
CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Create report ClientDiscountByPeriod from {dateStart} to {dateFinish}", dateStart,
|
||||
dateFinish);
|
||||
var data = await GetDataByClientDiscountAsync(dateStart, dateFinish, ct) ??
|
||||
throw new InvalidOperationException("No found data");
|
||||
return _basePdfBuilder
|
||||
.AddHeader("Скидочная ведомость")
|
||||
.AddParagraph($"за период с {dateStart.ToShortDateString()} по {dateFinish.ToShortDateString()}")
|
||||
.AddPieChart("Начисления", [.. data.Select(x => (x.ClientFIO, x.TotalDiscount))])
|
||||
.Build();
|
||||
}
|
||||
|
||||
public Task<List<ProductHistoryPricesDataModel>> GetDataProductHistoryPricesAsync(CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Get data ProductHistoryPrices");
|
||||
return GetDataByHistoryPricesAsync(ct);
|
||||
}
|
||||
|
||||
public Task<List<SaleDataModel>> GetDataSaleByPeriodAsync(DateTime dateStart, DateTime dateFinish,
|
||||
CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Get data SalesByPeriod from {dateStart} to {dateFinish}", dateStart, dateFinish);
|
||||
return GetDataBySalesAsync(dateStart, dateFinish, ct);
|
||||
}
|
||||
|
||||
public Task<List<ClientDiscountByPeriodDataModel>> GetDataClientDiscountByPeriodAsync(DateTime dateStart,
|
||||
DateTime dateFinish, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Get data ClientDiscountByPeriod from {dateStart} to {dateFinish}", dateStart,
|
||||
dateFinish);
|
||||
return GetDataByClientDiscountAsync(dateStart, dateFinish, ct);
|
||||
}
|
||||
|
||||
private async Task<List<ProductHistoryPricesDataModel>> GetDataByHistoryPricesAsync(CancellationToken ct) =>
|
||||
[
|
||||
.. (await _productStorageContract.GetListAsync(ct))
|
||||
.Select(async product => new
|
||||
{
|
||||
ProductName = product.ProductName,
|
||||
History = await Task.Run(() => _productStorageContract.GetHistoryByProductId(product.Id))
|
||||
}).Select(t => t.Result).Select(x => new ProductHistoryPricesDataModel
|
||||
{
|
||||
ProductName = x.ProductName,
|
||||
Prices =
|
||||
[
|
||||
.. x.History.OrderByDescending(h => h.ChangeDate)
|
||||
.Select(h => $"{h.OldPrice:N2} ({h.ChangeDate:dd.MM.yyyy})")
|
||||
]
|
||||
})
|
||||
];
|
||||
|
||||
private async Task<List<SaleDataModel>> GetDataBySalesAsync(DateTime dateStart, DateTime dateFinish,
|
||||
CancellationToken ct)
|
||||
{
|
||||
if (dateStart.IsDateNotOlder(dateFinish))
|
||||
{
|
||||
throw new IncorrectDatesException(dateStart, dateFinish);
|
||||
}
|
||||
|
||||
return [.. (await _saleStorageContract.GetListAsync(dateStart, dateFinish, ct)).OrderBy(x => x.SaleDate)];
|
||||
}
|
||||
|
||||
private async Task<List<ClientDiscountByPeriodDataModel>> GetDataByClientDiscountAsync(DateTime dateStart,
|
||||
DateTime dateFinish, CancellationToken ct)
|
||||
{
|
||||
if (dateStart.IsDateNotOlder(dateFinish))
|
||||
{
|
||||
throw new IncorrectDatesException(dateStart, dateFinish);
|
||||
}
|
||||
|
||||
return
|
||||
[
|
||||
.. (await _clientDiscountStorageContract.GetListAsync(dateStart, dateFinish, ct)).GroupBy(x => x.ClientFIO)
|
||||
.Select(x => new ClientDiscountByPeriodDataModel
|
||||
{
|
||||
ClientFIO = x.Key, TotalDiscount = x.Sum(y => y.DiscountAmount),
|
||||
FromPeriod = x.Min(y => y.DiscountDate), ToPeriod = x.Max(y => y.DiscountDate)
|
||||
}).OrderBy(x => x.ClientFIO)
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -48,7 +48,7 @@ public class SaleBusinessLogicContract(ISaleStorageContract saleStorageContract,
|
||||
|
||||
public List<SaleDataModel> GetAllSalesByClientByPeriod(string clientId, DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
_logger.LogInformation("GetAllSales params: {buyerId}, {fromDate}, {toDate}", clientId, fromDate, toDate);
|
||||
_logger.LogInformation("GetAllSales params: {clientId}, {fromDate}, {toDate}", clientId, fromDate, toDate);
|
||||
if (fromDate.IsDateNotOlder(toDate))
|
||||
{
|
||||
throw new IncorrectDatesException(fromDate, toDate);
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace CandyHouseBusinessLogic.OfficePackage;
|
||||
|
||||
public abstract class BaseExcelBuilder
|
||||
{
|
||||
public abstract BaseExcelBuilder AddHeader(string header, int startIndex, int count);
|
||||
|
||||
public abstract BaseExcelBuilder AddParagraph(string text, int columnIndex);
|
||||
|
||||
public abstract BaseExcelBuilder AddTable(int[] columnsWidths, List<string[]> data);
|
||||
|
||||
public abstract Stream Build();
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace CandyHouseBusinessLogic.OfficePackage;
|
||||
|
||||
public abstract class BasePdfBuilder
|
||||
{
|
||||
public abstract BasePdfBuilder AddHeader(string header);
|
||||
|
||||
public abstract BasePdfBuilder AddParagraph(string text);
|
||||
|
||||
public abstract BasePdfBuilder AddPieChart(string title, List<(string Caption, double Value)> data);
|
||||
|
||||
public abstract Stream Build();
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace CandyHouseBusinessLogic.OfficePackage;
|
||||
|
||||
public abstract class BaseWordBuilder
|
||||
{
|
||||
public abstract BaseWordBuilder AddHeader(string header);
|
||||
|
||||
public abstract BaseWordBuilder AddParagraph(string text);
|
||||
|
||||
public abstract BaseWordBuilder AddTable(int[] widths, List<string[]> data);
|
||||
|
||||
public abstract Stream Build();
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
using MigraDoc.DocumentObjectModel;
|
||||
using MigraDoc.DocumentObjectModel.Shapes.Charts;
|
||||
using MigraDoc.Rendering;
|
||||
using System.Text;
|
||||
|
||||
namespace CandyHouseBusinessLogic.OfficePackage;
|
||||
|
||||
internal class MigraDocPdfBuilder : BasePdfBuilder
|
||||
{
|
||||
private readonly Document _document;
|
||||
|
||||
public MigraDocPdfBuilder()
|
||||
{
|
||||
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
|
||||
_document = new Document();
|
||||
DefineStyles();
|
||||
}
|
||||
|
||||
public override BasePdfBuilder AddHeader(string header)
|
||||
{
|
||||
_document.AddSection().AddParagraph(header, "NormalBold");
|
||||
return this;
|
||||
}
|
||||
|
||||
public override BasePdfBuilder AddParagraph(string text)
|
||||
{
|
||||
_document.LastSection.AddParagraph(text, "Normal");
|
||||
return this;
|
||||
}
|
||||
|
||||
public override BasePdfBuilder AddPieChart(string title, List<(string Caption, double Value)> data)
|
||||
{
|
||||
if (data == null || data.Count == 0)
|
||||
{
|
||||
return this;
|
||||
}
|
||||
|
||||
var chart = new Chart(ChartType.Pie2D);
|
||||
var series = chart.SeriesCollection.AddSeries();
|
||||
series.Add(data.Select(x => x.Value).ToArray());
|
||||
|
||||
var xseries = chart.XValues.AddXSeries();
|
||||
xseries.Add(data.Select(x => x.Caption).ToArray());
|
||||
|
||||
chart.DataLabel.Type = DataLabelType.Percent;
|
||||
chart.DataLabel.Position = DataLabelPosition.OutsideEnd;
|
||||
|
||||
chart.Width = Unit.FromCentimeter(16);
|
||||
chart.Height = Unit.FromCentimeter(12);
|
||||
|
||||
chart.TopArea.AddParagraph(title);
|
||||
|
||||
chart.XAxis.MajorTickMark = TickMarkType.Outside;
|
||||
|
||||
chart.YAxis.MajorTickMark = TickMarkType.Outside;
|
||||
chart.YAxis.HasMajorGridlines = true;
|
||||
|
||||
chart.PlotArea.LineFormat.Width = 1;
|
||||
chart.PlotArea.LineFormat.Visible = true;
|
||||
|
||||
chart.TopArea.AddLegend();
|
||||
|
||||
_document.LastSection.Add(chart);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public override Stream Build()
|
||||
{
|
||||
var stream = new MemoryStream();
|
||||
var renderer = new PdfDocumentRenderer(true)
|
||||
{
|
||||
Document = _document
|
||||
};
|
||||
renderer.RenderDocument();
|
||||
renderer.PdfDocument.Save(stream);
|
||||
return stream;
|
||||
}
|
||||
|
||||
private void DefineStyles()
|
||||
{
|
||||
var style = _document.Styles.AddStyle("NormalBold", "Normal");
|
||||
style.Font.Bold = true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
using CandyHouseBusinessLogic.OfficePackage;
|
||||
using DocumentFormat.OpenXml.Packaging;
|
||||
using DocumentFormat.OpenXml.Spreadsheet;
|
||||
using DocumentFormat.OpenXml;
|
||||
|
||||
namespace CandyHouseBusinessLogic.OfficePackage;
|
||||
|
||||
internal class OpenXmlExcelBuilder : BaseExcelBuilder
|
||||
{
|
||||
private readonly SheetData _sheetData;
|
||||
|
||||
private readonly MergeCells _mergeCells;
|
||||
|
||||
private readonly Columns _columns;
|
||||
|
||||
private uint _rowIndex = 0;
|
||||
|
||||
public OpenXmlExcelBuilder()
|
||||
{
|
||||
_sheetData = new SheetData();
|
||||
_mergeCells = new MergeCells();
|
||||
_columns = new Columns();
|
||||
_rowIndex = 1;
|
||||
}
|
||||
|
||||
public override BaseExcelBuilder AddHeader(string header, int startIndex, int count)
|
||||
{
|
||||
CreateCell(startIndex, _rowIndex, header, StyleIndex.BoldTextWithoutBorder);
|
||||
for (int i = startIndex + 1; i < startIndex + count; ++i)
|
||||
{
|
||||
CreateCell(i, _rowIndex, "", StyleIndex.SimpleTextWithoutBorder);
|
||||
}
|
||||
|
||||
_mergeCells.Append(new MergeCell()
|
||||
{
|
||||
Reference =
|
||||
new StringValue($"{GetExcelColumnName(startIndex)}{_rowIndex}:{GetExcelColumnName(startIndex + count - 1)}{_rowIndex}")
|
||||
});
|
||||
|
||||
_rowIndex++;
|
||||
return this;
|
||||
}
|
||||
|
||||
public override BaseExcelBuilder AddParagraph(string text, int columnIndex)
|
||||
{
|
||||
CreateCell(columnIndex, _rowIndex++, text, StyleIndex.SimpleTextWithoutBorder);
|
||||
return this;
|
||||
}
|
||||
|
||||
public override BaseExcelBuilder AddTable(int[] columnsWidths, List<string[]> data)
|
||||
{
|
||||
if (columnsWidths == null || columnsWidths.Length == 0)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(columnsWidths));
|
||||
}
|
||||
|
||||
if (data == null || data.Count == 0)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(data));
|
||||
}
|
||||
|
||||
if (data.Any(x => x.Length != columnsWidths.Length))
|
||||
{
|
||||
throw new InvalidOperationException("widths.Length != data.Length");
|
||||
}
|
||||
|
||||
uint counter = 1;
|
||||
int coef = 2;
|
||||
_columns.Append(columnsWidths.Select(x => new Column
|
||||
{
|
||||
Min = counter,
|
||||
Max = counter++,
|
||||
Width = x * coef,
|
||||
CustomWidth = true
|
||||
}));
|
||||
|
||||
for (var j = 0; j < data.First().Length; ++j)
|
||||
{
|
||||
CreateCell(j, _rowIndex, data.First()[j], StyleIndex.BoldTextWithBorder);
|
||||
}
|
||||
|
||||
_rowIndex++;
|
||||
for (var i = 1; i < data.Count - 1; ++i)
|
||||
{
|
||||
for (var j = 0; j < data[i].Length; ++j)
|
||||
{
|
||||
CreateCell(j, _rowIndex, data[i][j], StyleIndex.SimpleTextWithBorder);
|
||||
}
|
||||
|
||||
_rowIndex++;
|
||||
}
|
||||
|
||||
for (var j = 0; j < data.Last().Length; ++j)
|
||||
{
|
||||
CreateCell(j, _rowIndex, data.Last()[j], StyleIndex.BoldTextWithBorder);
|
||||
}
|
||||
|
||||
_rowIndex++;
|
||||
return this;
|
||||
}
|
||||
|
||||
public override Stream Build()
|
||||
{
|
||||
var stream = new MemoryStream();
|
||||
using var spreadsheetDocument = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook);
|
||||
var workbookpart = spreadsheetDocument.AddWorkbookPart();
|
||||
GenerateStyle(workbookpart);
|
||||
workbookpart.Workbook = new Workbook();
|
||||
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
|
||||
worksheetPart.Worksheet = new Worksheet();
|
||||
if (_columns.HasChildren)
|
||||
{
|
||||
worksheetPart.Worksheet.Append(_columns);
|
||||
}
|
||||
|
||||
worksheetPart.Worksheet.Append(_sheetData);
|
||||
var sheets = spreadsheetDocument.WorkbookPart!.Workbook.AppendChild(new Sheets());
|
||||
var sheet = new Sheet()
|
||||
{
|
||||
Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
|
||||
SheetId = 1,
|
||||
Name = "Лист 1"
|
||||
};
|
||||
|
||||
sheets.Append(sheet);
|
||||
if (_mergeCells.HasChildren)
|
||||
{
|
||||
worksheetPart.Worksheet.InsertAfter(_mergeCells, worksheetPart.Worksheet.Elements<SheetData>().First());
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
private static void GenerateStyle(WorkbookPart workbookPart)
|
||||
{
|
||||
var workbookStylesPart = workbookPart.AddNewPart<WorkbookStylesPart>();
|
||||
workbookStylesPart.Stylesheet = new Stylesheet();
|
||||
|
||||
var fonts = new Fonts() { Count = 2, KnownFonts = BooleanValue.FromBoolean(true) };
|
||||
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
|
||||
{
|
||||
FontSize = new FontSize() { Val = 11 },
|
||||
FontName = new FontName() { Val = "Calibri" },
|
||||
FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 },
|
||||
FontScheme = new FontScheme() { Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor) }
|
||||
});
|
||||
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
|
||||
{
|
||||
FontSize = new FontSize() { Val = 11 },
|
||||
FontName = new FontName() { Val = "Calibri" },
|
||||
FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 },
|
||||
FontScheme = new FontScheme() { Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor) },
|
||||
Bold = new Bold()
|
||||
});
|
||||
workbookStylesPart.Stylesheet.Append(fonts);
|
||||
|
||||
// Default Fill
|
||||
var fills = new Fills() { Count = 1 };
|
||||
fills.Append(new Fill
|
||||
{
|
||||
PatternFill = new PatternFill() { PatternType = new EnumValue<PatternValues>(PatternValues.None) }
|
||||
});
|
||||
workbookStylesPart.Stylesheet.Append(fills);
|
||||
|
||||
// Default Border
|
||||
var borders = new Borders() { Count = 2 };
|
||||
borders.Append(new Border
|
||||
{
|
||||
LeftBorder = new LeftBorder(),
|
||||
RightBorder = new RightBorder(),
|
||||
TopBorder = new TopBorder(),
|
||||
BottomBorder = new BottomBorder(),
|
||||
DiagonalBorder = new DiagonalBorder()
|
||||
});
|
||||
borders.Append(new Border
|
||||
{
|
||||
LeftBorder = new LeftBorder() { Style = BorderStyleValues.Thin },
|
||||
RightBorder = new RightBorder() { Style = BorderStyleValues.Thin },
|
||||
TopBorder = new TopBorder() { Style = BorderStyleValues.Thin },
|
||||
BottomBorder = new BottomBorder() { Style = BorderStyleValues.Thin }
|
||||
});
|
||||
workbookStylesPart.Stylesheet.Append(borders);
|
||||
|
||||
// Default cell format and a date cell format
|
||||
var cellFormats = new CellFormats() { Count = 4 };
|
||||
cellFormats.Append(new CellFormat
|
||||
{
|
||||
NumberFormatId = 0,
|
||||
FormatId = 0,
|
||||
FontId = 0,
|
||||
BorderId = 0,
|
||||
FillId = 0,
|
||||
Alignment = new Alignment()
|
||||
{
|
||||
Horizontal = HorizontalAlignmentValues.Left,
|
||||
Vertical = VerticalAlignmentValues.Center,
|
||||
WrapText = true
|
||||
}
|
||||
});
|
||||
cellFormats.Append(new CellFormat
|
||||
{
|
||||
NumberFormatId = 0,
|
||||
FormatId = 0,
|
||||
FontId = 0,
|
||||
BorderId = 1,
|
||||
FillId = 0,
|
||||
Alignment = new Alignment()
|
||||
{
|
||||
Horizontal = HorizontalAlignmentValues.Left,
|
||||
Vertical = VerticalAlignmentValues.Center,
|
||||
WrapText = true
|
||||
}
|
||||
});
|
||||
cellFormats.Append(new CellFormat
|
||||
{
|
||||
NumberFormatId = 0,
|
||||
FormatId = 0,
|
||||
FontId = 1,
|
||||
BorderId = 0,
|
||||
FillId = 0,
|
||||
Alignment = new Alignment()
|
||||
{
|
||||
Horizontal = HorizontalAlignmentValues.Center,
|
||||
Vertical = VerticalAlignmentValues.Center,
|
||||
WrapText = true
|
||||
}
|
||||
});
|
||||
cellFormats.Append(new CellFormat
|
||||
{
|
||||
NumberFormatId = 0,
|
||||
FormatId = 0,
|
||||
FontId = 1,
|
||||
BorderId = 1,
|
||||
FillId = 0,
|
||||
Alignment = new Alignment()
|
||||
{
|
||||
Horizontal = HorizontalAlignmentValues.Center,
|
||||
Vertical = VerticalAlignmentValues.Center,
|
||||
WrapText = true
|
||||
}
|
||||
});
|
||||
workbookStylesPart.Stylesheet.Append(cellFormats);
|
||||
}
|
||||
|
||||
private enum StyleIndex
|
||||
{
|
||||
SimpleTextWithoutBorder = 0,
|
||||
SimpleTextWithBorder = 1,
|
||||
BoldTextWithoutBorder = 2,
|
||||
BoldTextWithBorder = 3
|
||||
}
|
||||
|
||||
private void CreateCell(int columnIndex, uint rowIndex, string text, StyleIndex styleIndex)
|
||||
{
|
||||
var columnName = GetExcelColumnName(columnIndex);
|
||||
var cellReference = columnName + rowIndex;
|
||||
var row = _sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex! == rowIndex);
|
||||
if (row == null)
|
||||
{
|
||||
row = new Row() { RowIndex = rowIndex };
|
||||
_sheetData.Append(row);
|
||||
}
|
||||
|
||||
var newCell = row.Elements<Cell>()
|
||||
.FirstOrDefault(c => c.CellReference != null && c.CellReference.Value == columnName + rowIndex);
|
||||
if (newCell == null)
|
||||
{
|
||||
Cell? refCell = null;
|
||||
foreach (Cell cell in row.Elements<Cell>())
|
||||
{
|
||||
if (cell.CellReference?.Value != null && cell.CellReference.Value.Length == cellReference.Length)
|
||||
{
|
||||
if (string.Compare(cell.CellReference.Value, cellReference, true) > 0)
|
||||
{
|
||||
refCell = cell;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
newCell = new Cell() { CellReference = cellReference };
|
||||
row.InsertBefore(newCell, refCell);
|
||||
}
|
||||
|
||||
newCell.CellValue = new CellValue(text);
|
||||
newCell.DataType = CellValues.String;
|
||||
newCell.StyleIndex = (uint)styleIndex;
|
||||
}
|
||||
|
||||
private static string GetExcelColumnName(int columnNumber)
|
||||
{
|
||||
columnNumber += 1;
|
||||
int dividend = columnNumber;
|
||||
string columnName = string.Empty;
|
||||
int modulo;
|
||||
|
||||
while (dividend > 0)
|
||||
{
|
||||
modulo = (dividend - 1) % 26;
|
||||
columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
|
||||
dividend = (dividend - modulo) / 26;
|
||||
}
|
||||
|
||||
return columnName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
using DocumentFormat.OpenXml.Packaging;
|
||||
using DocumentFormat.OpenXml.Wordprocessing;
|
||||
using DocumentFormat.OpenXml;
|
||||
|
||||
namespace CandyHouseBusinessLogic.OfficePackage;
|
||||
|
||||
internal class OpenXmlWordBuilder : BaseWordBuilder
|
||||
{
|
||||
private readonly Document _document;
|
||||
|
||||
private readonly Body _body;
|
||||
|
||||
public OpenXmlWordBuilder()
|
||||
{
|
||||
_document = new Document();
|
||||
_body = _document.AppendChild(new Body());
|
||||
}
|
||||
|
||||
public override BaseWordBuilder AddHeader(string header)
|
||||
{
|
||||
var paragraph = _body.AppendChild(new Paragraph());
|
||||
var run = paragraph.AppendChild(new Run());
|
||||
run.AppendChild(new RunProperties(new Bold()));
|
||||
run.AppendChild(new Text(header));
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public override BaseWordBuilder AddParagraph(string text)
|
||||
{
|
||||
var paragraph = _body.AppendChild(new Paragraph());
|
||||
var run = paragraph.AppendChild(new Run());
|
||||
run.AppendChild(new Text(text));
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public override BaseWordBuilder AddTable(int[] widths, List<string[]> data)
|
||||
{
|
||||
if (widths == null || widths.Length == 0)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(widths));
|
||||
}
|
||||
|
||||
if (data == null || data.Count == 0)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(data));
|
||||
}
|
||||
|
||||
if (data.Any(x => x.Length != widths.Length))
|
||||
{
|
||||
throw new InvalidOperationException("widths.Length != data.Length");
|
||||
}
|
||||
|
||||
var table = new Table();
|
||||
table.AppendChild(new TableProperties(
|
||||
new TableBorders(
|
||||
new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
|
||||
new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
|
||||
new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
|
||||
new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
|
||||
new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
|
||||
new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 }
|
||||
)
|
||||
));
|
||||
|
||||
// Заголовок
|
||||
var tr = new TableRow();
|
||||
for (var j = 0; j < widths.Length; ++j)
|
||||
{
|
||||
tr.Append(new TableCell(
|
||||
new TableCellProperties(new TableCellWidth() { Width = widths[j].ToString() }),
|
||||
new Paragraph(new Run(new RunProperties(new Bold()), new Text(data.First()[j])))));
|
||||
}
|
||||
table.Append(tr);
|
||||
|
||||
// Данные
|
||||
table.Append(data.Skip(1).Select(x =>
|
||||
new TableRow(x.Select(y => new TableCell(new Paragraph(new Run(new Text(y))))))));
|
||||
|
||||
_body.Append(table);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public override Stream Build()
|
||||
{
|
||||
var stream = new MemoryStream();
|
||||
using var wordDocument = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document);
|
||||
var mainPart = wordDocument.AddMainDocumentPart();
|
||||
mainPart.Document = _document;
|
||||
return stream;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using CandyHouseContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
namespace CandyHouseContracts.AdapterContracts;
|
||||
|
||||
public interface IReportAdapter
|
||||
{
|
||||
Task<ReportOperationResponse> GetDataProductHistoryPricesAsync(CancellationToken ct);
|
||||
|
||||
Task<ReportOperationResponse> GetDataSaleByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
|
||||
Task<ReportOperationResponse> GetDataClientDiscountByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
|
||||
Task<ReportOperationResponse> CreateDocumentProductHistoryPricesAsync(CancellationToken ct);
|
||||
|
||||
Task<ReportOperationResponse> CreateDocumentSalesByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
|
||||
Task<ReportOperationResponse> CreateDocumentClientDiscountByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using CandyHouseContracts.Infrastructure;
|
||||
using CandyHouseContracts.ViewModels;
|
||||
|
||||
namespace CandyHouseContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class ReportOperationResponse : OperationResponse
|
||||
{
|
||||
public static ReportOperationResponse OK(List<ProductHistoryPricesViewModel> data) => OK<ReportOperationResponse, List<ProductHistoryPricesViewModel>>(data);
|
||||
|
||||
public static ReportOperationResponse OK(List<SaleViewModel> data) => OK<ReportOperationResponse, List<SaleViewModel>>(data);
|
||||
|
||||
public static ReportOperationResponse OK(List<ClientDiscountByPeriodViewModel> data) => OK<ReportOperationResponse, List<ClientDiscountByPeriodViewModel>>(data);
|
||||
|
||||
public static ReportOperationResponse OK(Stream data, string fileName) => OK<ReportOperationResponse, Stream>(data, fileName);
|
||||
|
||||
public static ReportOperationResponse BadRequest(string message) => BadRequest<ReportOperationResponse>(message);
|
||||
|
||||
public static ReportOperationResponse InternalServerError(string message) => InternalServerError<ReportOperationResponse>(message);
|
||||
}
|
||||
@@ -1,11 +1,6 @@
|
||||
using CandyHouseContracts.DataModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace CandyHouseContracts.BuisnessLogicContracts;
|
||||
namespace CandyHouseContracts.BusinessLogicContracts;
|
||||
|
||||
public interface IProductBusinessLogicContract
|
||||
{
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
using CandyHouseContracts.DataModels;
|
||||
|
||||
namespace CandyHouseContracts.BusinessLogicContracts;
|
||||
|
||||
|
||||
public interface IReportContract
|
||||
{
|
||||
Task<List<ProductHistoryPricesDataModel>> GetDataProductHistoryPricesAsync(CancellationToken ct);
|
||||
|
||||
Task<List<SaleDataModel>> GetDataSaleByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
|
||||
Task<List<ClientDiscountByPeriodDataModel>> GetDataClientDiscountByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
|
||||
Task<Stream> CreateDocumentProductHistoryPricesAsync(CancellationToken ct);
|
||||
|
||||
Task<Stream> CreateDocumentSalesByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
|
||||
Task<Stream> CreateDocumentClientDiscountByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace CandyHouseContracts.DataModels;
|
||||
|
||||
public class ClientDiscountByPeriodDataModel
|
||||
{
|
||||
public required string ClientFIO { get; set; }
|
||||
|
||||
public double TotalDiscount { get; set; }
|
||||
|
||||
public DateTime FromPeriod { get; set; }
|
||||
|
||||
public DateTime ToPeriod { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using CandyHouseContracts.Exceptions;
|
||||
using CandyHouseContracts.Extensions;
|
||||
using CandyHouseContracts.Infrastructure;
|
||||
|
||||
namespace CandyHouseContracts.DataModels;
|
||||
|
||||
public class ClientDiscountDataModel(string clientId, DateTime discountDate, double discountAmount) : IValidation
|
||||
{
|
||||
private readonly ClientDataModel? _client;
|
||||
|
||||
public string ClientId { get; private set; } = clientId;
|
||||
|
||||
public DateTime DiscountDate { get; private set; } = discountDate;
|
||||
|
||||
public double DiscountAmount { get; private set; } = discountAmount;
|
||||
|
||||
public string ClientFIO => _client?.FIO ?? string.Empty;
|
||||
|
||||
public ClientDiscountDataModel(string clientId, DateTime discountDate, double discountAmount, ClientDataModel client) : this(clientId, discountDate, discountAmount)
|
||||
{
|
||||
_client = client;
|
||||
}
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (ClientId.IsEmpty())
|
||||
throw new ValidationException("Field ClientId is empty");
|
||||
|
||||
if (!ClientId.IsGuid())
|
||||
throw new ValidationException("The value in the field ClientId is not a unique identifier");
|
||||
|
||||
if (DiscountAmount < 0)
|
||||
throw new ValidationException("Field DiscountAmount in the field is less than 0");
|
||||
}
|
||||
}
|
||||
@@ -58,7 +58,7 @@ public class EmployeeDataModel(string id, string fio, string email, string postI
|
||||
if (!PostId.IsGuid())
|
||||
throw new ValidationException("The value in the field PostId is not a unique identifier");
|
||||
|
||||
if (BirthDate.Date > DateTime.Now.AddYears(-18).Date)
|
||||
if (BirthDate.Date > DateTime.UtcNow.AddYears(-18).Date)
|
||||
throw new ValidationException($"Only adults can be hired (BirthDate = {BirthDate.ToShortDateString()})");
|
||||
|
||||
if (EmploymentDate.Date < BirthDate.Date)
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace CandyHouseContracts.DataModels;
|
||||
|
||||
public class ProductHistoryPricesDataModel
|
||||
{
|
||||
public required string ProductName { get; set; }
|
||||
|
||||
public required List<string> Prices { get; set; }
|
||||
}
|
||||
@@ -98,7 +98,7 @@ public class SaleDataModel : IValidation
|
||||
throw new ValidationException("The value in the field EmployeeId is not a unique identifier");
|
||||
|
||||
if (!ClientId?.IsGuid() ?? !ClientId?.IsEmpty() ?? false)
|
||||
throw new ValidationException("The value in the field BuyerId is not a unique identifier");
|
||||
throw new ValidationException("The value in the field EmploeerId is not a unique identifier");
|
||||
|
||||
if (Sum <= 0)
|
||||
throw new ValidationException("Field Sum is less than or equal to 0");
|
||||
|
||||
@@ -14,6 +14,8 @@ public class OperationResponse
|
||||
protected HttpStatusCode StatusCode { get; set; }
|
||||
|
||||
protected object? Result { get; set; }
|
||||
|
||||
protected string? FileName { get; set; }
|
||||
|
||||
public IActionResult GetResponse(HttpRequest request, HttpResponse response)
|
||||
{
|
||||
@@ -26,13 +28,23 @@ public class OperationResponse
|
||||
{
|
||||
return new StatusCodeResult((int)StatusCode);
|
||||
}
|
||||
|
||||
|
||||
if (Result is Stream stream)
|
||||
{
|
||||
return new FileStreamResult(stream, "application/octet-stream")
|
||||
{
|
||||
FileDownloadName = FileName
|
||||
};
|
||||
}
|
||||
|
||||
return new ObjectResult(Result);
|
||||
}
|
||||
|
||||
protected static TResult OK<TResult, TData>(TData data) where TResult : OperationResponse,
|
||||
new() => new() { StatusCode = HttpStatusCode.OK, Result = data };
|
||||
|
||||
protected static TResult OK<TResult, TData>(TData data, string fileName) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.OK, Result = data, FileName = fileName };
|
||||
|
||||
protected static TResult NoContent<TResult>() where TResult : OperationResponse,
|
||||
new() => new() { StatusCode = HttpStatusCode.NoContent };
|
||||
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
using CandyHouseContracts.DataModels;
|
||||
|
||||
namespace CandyHouseContracts.StoragesContracts;
|
||||
|
||||
public interface IClientDiscountStorageContract
|
||||
{
|
||||
List<ClientDiscountDataModel> GetList(DateTime startDate, DateTime endDate, string? clientId = null);
|
||||
|
||||
Task<List<ClientDiscountDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct);
|
||||
|
||||
void AddElement(ClientDiscountDataModel clientDiscountDataModel);
|
||||
}
|
||||
@@ -16,4 +16,5 @@ public interface IProductStorageContract
|
||||
void AddElement(ProductDataModel productDataModel);
|
||||
void UpdElement(ProductDataModel productDataModel);
|
||||
void DelElement(string id);
|
||||
Task<List<ProductDataModel>> GetListAsync(CancellationToken ct);
|
||||
}
|
||||
|
||||
@@ -17,4 +17,6 @@ public interface ISaleStorageContract
|
||||
void AddElement(SaleDataModel saleDataModel);
|
||||
|
||||
void DelElement(string id);
|
||||
|
||||
Task<List<SaleDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace CandyHouseContracts.ViewModels;
|
||||
|
||||
public class ClientDiscountByPeriodViewModel
|
||||
{
|
||||
public required string ClientFIO { get; set; }
|
||||
|
||||
public double TotalDiscount { get; set; }
|
||||
|
||||
public DateTime FromPeriod { get; set; }
|
||||
|
||||
public DateTime ToPeriod { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace CandyHouseContracts.ViewModels;
|
||||
|
||||
public class ProductHistoryPricesViewModel
|
||||
{
|
||||
public required string ProductName { get; set; }
|
||||
|
||||
public required List<string> Prices { get; set; }
|
||||
}
|
||||
@@ -63,6 +63,7 @@ public class CandyHouseDbContext(IConfigurationDatabase configurationDatabase) :
|
||||
public DbSet<Sale> Sales { get; set; }
|
||||
|
||||
public DbSet<SaleProduct> SaleProducts { get; set; }
|
||||
public DbSet<ClientDiscount> ClientDiscounts { get; set; }
|
||||
|
||||
public DbSet<Employee> Employees { get; set; }
|
||||
private static string SerializePostConfiguration(PostConfiguration postConfiguration) => JsonConvert.SerializeObject(postConfiguration);
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
using AutoMapper;
|
||||
using CandyHouseContracts.DataModels;
|
||||
using CandyHouseContracts.Exceptions;
|
||||
using CandyHouseContracts.StoragesContracts;
|
||||
using CandyHouseDatabase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace CandyHouseDatabase.Implementations;
|
||||
|
||||
public class ClientDiscountStorageContract : IClientDiscountStorageContract
|
||||
{
|
||||
private readonly CandyHouseDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public ClientDiscountStorageContract(CandyHouseDbContext dbContext)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Client, ClientDataModel>();
|
||||
cfg.CreateMap<ClientDiscount, ClientDiscountDataModel>();
|
||||
cfg.CreateMap<ClientDiscountDataModel, ClientDiscount>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<ClientDiscountDataModel> GetList(DateTime startDate, DateTime endDate, string? clientId = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var query = _dbContext.ClientDiscounts.Include(x => x.Client).Where(x => x.DiscountDate >= startDate && x.DiscountDate <= endDate);
|
||||
if (clientId is not null)
|
||||
{
|
||||
query = query.Where(x => x.ClientId == clientId);
|
||||
}
|
||||
return [.. query.Select(x => _mapper.Map<ClientDiscountDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<List<ClientDiscountDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Ensure dates are converted to UTC before comparison
|
||||
var startDateUtc = startDate.ToUniversalTime();
|
||||
var endDateUtc = endDate.ToUniversalTime();
|
||||
|
||||
return [.. await _dbContext.ClientDiscounts
|
||||
.Include(x => x.Client)
|
||||
.Where(x => x.DiscountDate >= startDateUtc && x.DiscountDate <= endDateUtc) // Use UTC dates
|
||||
.Select(x => _mapper.Map<ClientDiscountDataModel>(x))
|
||||
.ToListAsync(ct)];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddElement(ClientDiscountDataModel clientDiscountDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_dbContext.ClientDiscounts.Add(_mapper.Map<ClientDiscount>(clientDiscountDataModel));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -161,9 +161,9 @@ public class EmployeeStorageContract : IEmployeeStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
var countWorkersOnBegining = _dbContext.Employees.Count(x => x.EmploymentDate < fromPeriod && (!x.IsDeleted || x.DateOfDelete > fromPeriod));
|
||||
var countWorkersOnEnding = _dbContext.Employees.Count(x => x.EmploymentDate < toPeriod && (!x.IsDeleted || x.DateOfDelete > toPeriod));
|
||||
return countWorkersOnEnding - countWorkersOnBegining;
|
||||
var countEmployeesOnBegining = _dbContext.Employees.Count(x => x.EmploymentDate < fromPeriod && (!x.IsDeleted || x.DateOfDelete > fromPeriod));
|
||||
var countEmployeesOnEnding = _dbContext.Employees.Count(x => x.EmploymentDate < toPeriod && (!x.IsDeleted || x.DateOfDelete > toPeriod));
|
||||
return countEmployeesOnEnding - countEmployeesOnBegining;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
@@ -43,6 +43,19 @@ public class ProductStorageContract : IProductStorageContract
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<List<ProductDataModel>> GetListAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return [.. await _dbContext.Products.Select(x => _mapper.Map<ProductDataModel>(x)).ToListAsync(ct)];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public List<ProductHistoryDataModel> GetHistoryByProductId(string productId)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -27,7 +27,7 @@ public class SaleStorageContract : ISaleStorageContract
|
||||
cfg.CreateMap<Employee, EmployeeDataModel>();
|
||||
cfg.CreateMap<SaleProduct, SaleProductDataModel>();
|
||||
cfg.CreateMap<SaleProductDataModel, SaleProduct>()
|
||||
.ForMember(x => x.Product, x => x.Ignore());
|
||||
.ForMember(x => x.Product, x => x.Ignore());
|
||||
cfg.CreateMap<Sale, SaleDataModel>();
|
||||
cfg.CreateMap<SaleDataModel, Sale>()
|
||||
.ForMember(x => x.IsCancel, x => x.MapFrom(src => false))
|
||||
@@ -38,7 +38,8 @@ public class SaleStorageContract : ISaleStorageContract
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? employeeId = null, string? clientId = null, string? productId = null)
|
||||
public List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? employeeId = null,
|
||||
string? clientId = null, string? productId = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -49,9 +50,11 @@ public class SaleStorageContract : ISaleStorageContract
|
||||
.ThenInclude(d => d.Product)
|
||||
.AsQueryable();
|
||||
if (startDate.HasValue)
|
||||
query = query.Where(x => x.SaleDate >= DateTime.SpecifyKind(startDate ?? DateTime.UtcNow, DateTimeKind.Utc));
|
||||
query = query.Where(x =>
|
||||
x.SaleDate >= DateTime.SpecifyKind(startDate ?? DateTime.UtcNow, DateTimeKind.Utc));
|
||||
if (endDate.HasValue)
|
||||
query = query.Where(x => x.SaleDate <= DateTime.SpecifyKind(endDate ?? DateTime.UtcNow, DateTimeKind.Utc));
|
||||
query = query.Where(x =>
|
||||
x.SaleDate <= DateTime.SpecifyKind(endDate ?? DateTime.UtcNow, DateTimeKind.Utc));
|
||||
if (employeeId != null)
|
||||
query = query.Where(x => x.EmployeeId == employeeId);
|
||||
if (clientId != null)
|
||||
@@ -104,6 +107,7 @@ public class SaleStorageContract : ISaleStorageContract
|
||||
{
|
||||
throw new ElementDeletedException(id);
|
||||
}
|
||||
|
||||
element.IsCancel = true;
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
@@ -119,5 +123,30 @@ public class SaleStorageContract : ISaleStorageContract
|
||||
}
|
||||
}
|
||||
|
||||
private Sale? GetSaleById(string id) => _dbContext.Sales.Include(x => x.Client).Include(x => x.Employee).Include(x => x.SaleProducts)!.ThenInclude(x => x.Product).FirstOrDefault(x => x.Id == id);
|
||||
}
|
||||
public async Task<List<SaleDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Ensure dates are converted to UTC before comparison
|
||||
var startDateUtc = startDate.ToUniversalTime();
|
||||
var endDateUtc = endDate.ToUniversalTime();
|
||||
|
||||
return
|
||||
[
|
||||
.. await _dbContext.Sales.Include(x => x.Employee).Include(x => x.SaleProducts)!
|
||||
.ThenInclude(x => x.Product)
|
||||
.Where(x => x.SaleDate >= startDateUtc && x.SaleDate < endDateUtc) // Use UTC dates
|
||||
.Select(x => _mapper.Map<SaleDataModel>(x)).ToListAsync(ct)
|
||||
];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private Sale? GetSaleById(string id) =>
|
||||
_dbContext.Sales.Include(x => x.Client).Include(x => x.Employee).Include(x => x.SaleProducts)!
|
||||
.ThenInclude(x => x.Product).FirstOrDefault(x => x.Id == id);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace CandyHouseDatabase.Models;
|
||||
|
||||
public class ClientDiscount
|
||||
{
|
||||
public string Id { get; set; } = Guid.NewGuid().ToString();
|
||||
|
||||
public required string ClientId { get; set; }
|
||||
|
||||
public DateTime DiscountDate { get; set; }
|
||||
|
||||
public double DiscountAmount { get; set; }
|
||||
|
||||
public Client? Client { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
using CandyHouseContracts.DataModels;
|
||||
using CandyHouseContracts.Exceptions;
|
||||
using CandyHouseDatabase.Implementations;
|
||||
using CandyHouseDatabase.Models;
|
||||
using CandyHouseTests.Infrastructure;
|
||||
using CandyHouseTests.StoragesContracts;
|
||||
|
||||
namespace CandyHouseTests.BusinessLogicContractsTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class ClientStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
private ClientStorageContract _clientStorageContract;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_clientStorageContract = new ClientStorageContract(CandyHouseDbContext);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
CandyHouseDbContext.RemoveSalesFromDatabase();
|
||||
CandyHouseDbContext.RemoveEmployeesFromDatabase();
|
||||
CandyHouseDbContext.RemoveClientsFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var client = CandyHouseDbContext.InsertClientToDatabaseAndReturn(phoneNumber: "+5-555-555-55-55");
|
||||
CandyHouseDbContext.InsertClientToDatabaseAndReturn(phoneNumber: "+6-666-666-66-66");
|
||||
CandyHouseDbContext.InsertClientToDatabaseAndReturn(phoneNumber: "+7-777-777-77-77");
|
||||
var list = _clientStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
AssertElement(list.First(x => x.Id == client.Id), client);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenNoRecords_Test()
|
||||
{
|
||||
var list = _clientStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenDifferentConfigTypes_Test()
|
||||
{
|
||||
var clientBasic = CandyHouseDbContext.InsertClientToDatabaseAndReturn(phoneNumber: "+5-555-555-55-55");
|
||||
var clientSilver =
|
||||
CandyHouseDbContext.InsertClientToDatabaseAndReturn(phoneNumber: "+6-666-666-66-66", discountSize: 10);
|
||||
var clientGolden =
|
||||
CandyHouseDbContext.InsertClientToDatabaseAndReturn(phoneNumber: "+7-777-777-77-77", discountSize: 20);
|
||||
var list = _clientStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
AssertElement(list.First(x => x.Id == clientBasic.Id), clientBasic);
|
||||
AssertElement(list.First(x => x.Id == clientSilver.Id), clientSilver);
|
||||
AssertElement(list.First(x => x.Id == clientGolden.Id), clientGolden);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var client = CandyHouseDbContext.InsertClientToDatabaseAndReturn();
|
||||
AssertElement(_clientStorageContract.GetElementById(client.Id), client);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
CandyHouseDbContext.InsertClientToDatabaseAndReturn();
|
||||
Assert.That(() => _clientStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByFIO_WhenHaveRecord_Test()
|
||||
{
|
||||
var client = CandyHouseDbContext.InsertClientToDatabaseAndReturn();
|
||||
AssertElement(_clientStorageContract.GetElementByFIO(client.FIO), client);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByFIO_WhenNoRecord_Test()
|
||||
{
|
||||
CandyHouseDbContext.InsertClientToDatabaseAndReturn();
|
||||
Assert.That(() => _clientStorageContract.GetElementByFIO("New Fio"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByPhoneNumber_WhenHaveRecord_Test()
|
||||
{
|
||||
var client = CandyHouseDbContext.InsertClientToDatabaseAndReturn();
|
||||
AssertElement(_clientStorageContract.GetElementByPhoneNumber(client.PhoneNumber), client);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByPhoneNumber_WhenNoRecord_Test()
|
||||
{
|
||||
CandyHouseDbContext.InsertClientToDatabaseAndReturn();
|
||||
Assert.That(() => _clientStorageContract.GetElementByPhoneNumber("+8-888-888-88-88"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var client = CreateModel(Guid.NewGuid().ToString());
|
||||
_clientStorageContract.AddElement(client);
|
||||
AssertElement(CandyHouseDbContext.GetClientFromDatabase(client.Id), client);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
|
||||
{
|
||||
var client = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55", 10);
|
||||
CandyHouseDbContext.InsertClientToDatabaseAndReturn(client.Id);
|
||||
Assert.That(() => _clientStorageContract.AddElement(client), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSamePhoneNumber_Test()
|
||||
{
|
||||
var client = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55", 10);
|
||||
CandyHouseDbContext.InsertClientToDatabaseAndReturn(phoneNumber: client.PhoneNumber);
|
||||
Assert.That(() => _clientStorageContract.AddElement(client), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var client = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55", 10);
|
||||
CandyHouseDbContext.InsertClientToDatabaseAndReturn(client.Id);
|
||||
_clientStorageContract.UpdElement(client);
|
||||
AssertElement(CandyHouseDbContext.GetClientFromDatabase(client.Id), client);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _clientStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())),
|
||||
Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var client = CandyHouseDbContext.InsertClientToDatabaseAndReturn();
|
||||
_clientStorageContract.DelElement(client.Id);
|
||||
Assert.That(CandyHouseDbContext.GetClientFromDatabase(client.Id), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenHaveSalesByThisClient_Test()
|
||||
{
|
||||
var client = CandyHouseDbContext.InsertClientToDatabaseAndReturn();
|
||||
var worker = CandyHouseDbContext.InsertEmployeeToDatabaseAndReturn();
|
||||
CandyHouseDbContext.InsertSaleToDatabaseAndReturn(worker.Id, client.Id);
|
||||
CandyHouseDbContext.InsertSaleToDatabaseAndReturn(worker.Id, client.Id);
|
||||
var salesBeforeDelete = CandyHouseDbContext.GetSalesByClientId(client.Id);
|
||||
_clientStorageContract.DelElement(client.Id);
|
||||
var element = CandyHouseDbContext.GetClientFromDatabase(client.Id);
|
||||
var salesAfterDelete = CandyHouseDbContext.GetSalesByClientId(client.Id);
|
||||
var salesNoClients = CandyHouseDbContext.GetSalesByClientId(null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element, Is.Null);
|
||||
Assert.That(salesBeforeDelete, Has.Length.EqualTo(2));
|
||||
Assert.That(salesAfterDelete, Is.Empty);
|
||||
Assert.That(salesNoClients, Has.Length.EqualTo(2));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _clientStorageContract.DelElement(Guid.NewGuid().ToString()),
|
||||
Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private static void AssertElement(ClientDataModel? actual, Client expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
|
||||
Assert.That(actual.PhoneNumber, Is.EqualTo(expected.PhoneNumber));
|
||||
Assert.That(actual.DiscountSize, Is.EqualTo(expected.DiscountSize));
|
||||
});
|
||||
}
|
||||
|
||||
private static ClientDataModel CreateModel(string id, string fio = "test", string phoneNumber = "+7-777-777-77-77",
|
||||
double discountSize = 10)
|
||||
=> new(id, fio, phoneNumber, discountSize);
|
||||
|
||||
private static void AssertElement(Client? actual, ClientDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
|
||||
Assert.That(actual.PhoneNumber, Is.EqualTo(expected.PhoneNumber));
|
||||
Assert.That(actual.DiscountSize, Is.EqualTo(expected.DiscountSize));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -37,9 +37,9 @@ internal class EmployeeBusinessLogicContractTests
|
||||
//Arrange
|
||||
var listOriginal = new List<EmployeeDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), "fio 1", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
|
||||
new(Guid.NewGuid().ToString(), "fio 2", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, true),
|
||||
new(Guid.NewGuid().ToString(), "fio 3", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
|
||||
new(Guid.NewGuid().ToString(), "fio 1", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false),
|
||||
new(Guid.NewGuid().ToString(), "fio 2", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, true),
|
||||
new(Guid.NewGuid().ToString(), "fio 3", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false),
|
||||
};
|
||||
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -101,9 +101,9 @@ internal class EmployeeBusinessLogicContractTests
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
var listOriginal = new List<EmployeeDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), "fio 1", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
|
||||
new(Guid.NewGuid().ToString(), "fio 2", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, true),
|
||||
new(Guid.NewGuid().ToString(), "fio 3", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
|
||||
new(Guid.NewGuid().ToString(), "fio 1", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false),
|
||||
new(Guid.NewGuid().ToString(), "fio 2", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, true),
|
||||
new(Guid.NewGuid().ToString(), "fio 3", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false),
|
||||
};
|
||||
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -182,9 +182,9 @@ internal class EmployeeBusinessLogicContractTests
|
||||
var date = DateTime.UtcNow;
|
||||
var listOriginal = new List<EmployeeDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), "fio 1", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
|
||||
new(Guid.NewGuid().ToString(), "fio 2", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, true),
|
||||
new(Guid.NewGuid().ToString(), "fio 3", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
|
||||
new(Guid.NewGuid().ToString(), "fio 1", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false),
|
||||
new(Guid.NewGuid().ToString(), "fio 2", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, true),
|
||||
new(Guid.NewGuid().ToString(), "fio 3", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false),
|
||||
};
|
||||
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -258,9 +258,9 @@ internal class EmployeeBusinessLogicContractTests
|
||||
var date = DateTime.UtcNow;
|
||||
var listOriginal = new List<EmployeeDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), "fio 1", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
|
||||
new(Guid.NewGuid().ToString(), "fio 2", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, true),
|
||||
new(Guid.NewGuid().ToString(), "fio 3", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
|
||||
new(Guid.NewGuid().ToString(), "fio 1", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false),
|
||||
new(Guid.NewGuid().ToString(), "fio 2", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, true),
|
||||
new(Guid.NewGuid().ToString(), "fio 3", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false),
|
||||
};
|
||||
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
|
||||
//Act
|
||||
@@ -332,7 +332,7 @@ internal class EmployeeBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var id = Guid.NewGuid().ToString();
|
||||
var record = new EmployeeDataModel(id, "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false);
|
||||
var record = new EmployeeDataModel(id, "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false);
|
||||
_employeeStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
|
||||
//Act
|
||||
var element = _employeeBusinessLogicContract.GetEmployeeByData(id);
|
||||
@@ -347,7 +347,7 @@ internal class EmployeeBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var fio = "fio";
|
||||
var record = new EmployeeDataModel(Guid.NewGuid().ToString(), fio, "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false);
|
||||
var record = new EmployeeDataModel(Guid.NewGuid().ToString(), fio, "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false);
|
||||
_employeeStorageContract.Setup(x => x.GetElementByFIO(fio)).Returns(record);
|
||||
//Act
|
||||
var element = _employeeBusinessLogicContract.GetEmployeeByData(fio);
|
||||
@@ -362,7 +362,7 @@ internal class EmployeeBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var email = "123@gmail.com";
|
||||
var record = new EmployeeDataModel(Guid.NewGuid().ToString(), "fio", email, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false);
|
||||
var record = new EmployeeDataModel(Guid.NewGuid().ToString(), "fio", email, Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false);
|
||||
_employeeStorageContract.Setup(x => x.GetElementByEmail(email)).Returns(record);
|
||||
//Act
|
||||
var element = _employeeBusinessLogicContract.GetEmployeeByData(email);
|
||||
@@ -427,7 +427,7 @@ internal class EmployeeBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var flag = false;
|
||||
var record = new EmployeeDataModel(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false);
|
||||
var record = new EmployeeDataModel(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false);
|
||||
_employeeStorageContract.Setup(x => x.AddElement(It.IsAny<EmployeeDataModel>()))
|
||||
.Callback((EmployeeDataModel x) =>
|
||||
{
|
||||
@@ -447,7 +447,7 @@ internal class EmployeeBusinessLogicContractTests
|
||||
//Arrange
|
||||
_employeeStorageContract.Setup(x => x.AddElement(It.IsAny<EmployeeDataModel>())).Throws(new ElementExistsException("Data", "Data"));
|
||||
//Act&Assert
|
||||
Assert.That(() => _employeeBusinessLogicContract.InsertEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementExistsException>());
|
||||
Assert.That(() => _employeeBusinessLogicContract.InsertEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false)), Throws.TypeOf<ElementExistsException>());
|
||||
_employeeStorageContract.Verify(x => x.AddElement(It.IsAny<EmployeeDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -463,7 +463,7 @@ internal class EmployeeBusinessLogicContractTests
|
||||
public void InsertEmployee_InvalidRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _employeeBusinessLogicContract.InsertEmployee(new EmployeeDataModel("id", "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ValidationException>());
|
||||
Assert.That(() => _employeeBusinessLogicContract.InsertEmployee(new EmployeeDataModel("id", "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false)), Throws.TypeOf<ValidationException>());
|
||||
_employeeStorageContract.Verify(x => x.AddElement(It.IsAny<EmployeeDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
@@ -473,7 +473,7 @@ internal class EmployeeBusinessLogicContractTests
|
||||
//Arrange
|
||||
_employeeStorageContract.Setup(x => x.AddElement(It.IsAny<EmployeeDataModel>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _employeeBusinessLogicContract.InsertEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>());
|
||||
Assert.That(() => _employeeBusinessLogicContract.InsertEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false)), Throws.TypeOf<StorageException>());
|
||||
_employeeStorageContract.Verify(x => x.AddElement(It.IsAny<EmployeeDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -482,7 +482,7 @@ internal class EmployeeBusinessLogicContractTests
|
||||
{
|
||||
//Arrange
|
||||
var flag = false;
|
||||
var record = new EmployeeDataModel(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false);
|
||||
var record = new EmployeeDataModel(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false);
|
||||
_employeeStorageContract.Setup(x => x.UpdElement(It.IsAny<EmployeeDataModel>()))
|
||||
.Callback((EmployeeDataModel x) =>
|
||||
{
|
||||
@@ -502,7 +502,7 @@ internal class EmployeeBusinessLogicContractTests
|
||||
//Arrange
|
||||
_employeeStorageContract.Setup(x => x.UpdElement(It.IsAny<EmployeeDataModel>())).Throws(new ElementNotFoundException(""));
|
||||
//Act&Assert
|
||||
Assert.That(() => _employeeBusinessLogicContract.UpdateEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementNotFoundException>());
|
||||
Assert.That(() => _employeeBusinessLogicContract.UpdateEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false)), Throws.TypeOf<ElementNotFoundException>());
|
||||
_employeeStorageContract.Verify(x => x.UpdElement(It.IsAny<EmployeeDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
@@ -518,7 +518,7 @@ internal class EmployeeBusinessLogicContractTests
|
||||
public void UpdateEmployee_InvalidRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _employeeBusinessLogicContract.UpdateEmployee(new EmployeeDataModel("id", "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ValidationException>());
|
||||
Assert.That(() => _employeeBusinessLogicContract.UpdateEmployee(new EmployeeDataModel("id", "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false)), Throws.TypeOf<ValidationException>());
|
||||
_employeeStorageContract.Verify(x => x.UpdElement(It.IsAny<EmployeeDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
@@ -528,7 +528,7 @@ internal class EmployeeBusinessLogicContractTests
|
||||
//Arrange
|
||||
_employeeStorageContract.Setup(x => x.UpdElement(It.IsAny<EmployeeDataModel>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _employeeBusinessLogicContract.UpdateEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>());
|
||||
Assert.That(() => _employeeBusinessLogicContract.UpdateEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18).AddDays(-1), DateTime.UtcNow, false)), Throws.TypeOf<StorageException>());
|
||||
_employeeStorageContract.Verify(x => x.UpdElement(It.IsAny<EmployeeDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,446 @@
|
||||
using CandyHouseBusinessLogic.Implementations;
|
||||
using CandyHouseBusinessLogic.OfficePackage;
|
||||
using CandyHouseContracts.DataModels;
|
||||
using CandyHouseContracts.Enums;
|
||||
using CandyHouseContracts.Exceptions;
|
||||
using CandyHouseContracts.StoragesContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
|
||||
namespace CandyHouseTests.BusinessLogicContractsTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class ReportContractTests
|
||||
{
|
||||
private ReportContract _reportContract;
|
||||
private Mock<IProductStorageContract> _productStorageContract;
|
||||
private Mock<ISaleStorageContract> _saleStorageContract;
|
||||
private Mock<IClientDiscountStorageContract> _clientDiscountStorageContract;
|
||||
private Mock<BaseWordBuilder> _baseWordBuilder;
|
||||
private Mock<BaseExcelBuilder> _baseExcelBuilder;
|
||||
private Mock<BasePdfBuilder> _basePdfBuilder;
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
_productStorageContract = new Mock<IProductStorageContract>();
|
||||
_saleStorageContract = new Mock<ISaleStorageContract>();
|
||||
_clientDiscountStorageContract = new Mock<IClientDiscountStorageContract>();
|
||||
_baseWordBuilder = new Mock<BaseWordBuilder>();
|
||||
_baseExcelBuilder = new Mock<BaseExcelBuilder>();
|
||||
_basePdfBuilder = new Mock<BasePdfBuilder>();
|
||||
_reportContract = new ReportContract(_productStorageContract.Object, _saleStorageContract.Object,
|
||||
_clientDiscountStorageContract.Object, _baseWordBuilder.Object, _baseExcelBuilder.Object,
|
||||
_basePdfBuilder.Object, new Mock<ILogger>().Object);
|
||||
}
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_productStorageContract.Reset();
|
||||
_saleStorageContract.Reset();
|
||||
_clientDiscountStorageContract.Reset();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetDataProductHistoryPrices_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var product1 =
|
||||
new ProductDataModel(Guid.NewGuid().ToString(), "Product 1", "descrption 1", 10, ProductType.Cake);
|
||||
var product2 =
|
||||
new ProductDataModel(Guid.NewGuid().ToString(), "Product 2", "desription 2", 20, ProductType.Cake);
|
||||
_productStorageContract.Setup(x => x.GetListAsync(It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.FromResult(new List<ProductDataModel> { product1, product2 }));
|
||||
_productStorageContract.Setup(x => x.GetHistoryByProductId(product1.Id)).Returns(
|
||||
new List<ProductHistoryDataModel>
|
||||
{
|
||||
new(product1.Id, 15, DateTime.UtcNow.AddDays(-2), product1),
|
||||
new(product1.Id, 12, DateTime.UtcNow.AddDays(-1), product1)
|
||||
});
|
||||
_productStorageContract.Setup(x => x.GetHistoryByProductId(product2.Id)).Returns(
|
||||
new List<ProductHistoryDataModel>
|
||||
{
|
||||
new(product2.Id, 25, DateTime.UtcNow.AddDays(-3), product2),
|
||||
new(product2.Id, 22, DateTime.UtcNow.AddDays(-2), product2),
|
||||
new(product2.Id, 18, DateTime.UtcNow.AddDays(-1), product2)
|
||||
});
|
||||
//Act
|
||||
var data = await _reportContract.GetDataProductHistoryPricesAsync(CancellationToken.None);
|
||||
//Assert
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data.First(x => x.ProductName == product1.ProductName).Prices, Has.Count.EqualTo(2));
|
||||
Assert.That(data.First(x => x.ProductName == product2.ProductName).Prices, Has.Count.EqualTo(3));
|
||||
});
|
||||
_productStorageContract.Verify(x => x.GetListAsync(It.IsAny<CancellationToken>()), Times.Once);
|
||||
_productStorageContract.Verify(x => x.GetHistoryByProductId(product1.Id), Times.Once);
|
||||
_productStorageContract.Verify(x => x.GetHistoryByProductId(product2.Id), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetDataProductHistoryPrices_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
_productStorageContract.Setup(x => x.GetListAsync(It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.FromResult(new List<ProductDataModel>()));
|
||||
//Act
|
||||
var data = await _reportContract.GetDataProductHistoryPricesAsync(CancellationToken.None);
|
||||
//Assert
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
_productStorageContract.Verify(x => x.GetListAsync(It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetDataProductHistoryPrices_WhenStorageThrowError_ShouldFail_Test()
|
||||
{
|
||||
//Arrange
|
||||
_productStorageContract.Setup(x => x.GetListAsync(It.IsAny<CancellationToken>()))
|
||||
.Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(async () => await _reportContract.GetDataProductHistoryPricesAsync(CancellationToken.None),
|
||||
Throws.TypeOf<StorageException>());
|
||||
_productStorageContract.Verify(x => x.GetListAsync(It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetDataSalesByPeriod_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
_saleStorageContract
|
||||
.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.FromResult(new List<SaleDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.RegularCustomer, false,
|
||||
[new SaleProductDataModel("", Guid.NewGuid().ToString(), 10, 10)]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.RegularCustomer, false,
|
||||
[new SaleProductDataModel("", Guid.NewGuid().ToString(), 10, 10)])
|
||||
}));
|
||||
//Act
|
||||
var data = await _reportContract.GetDataSaleByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow,
|
||||
CancellationToken.None);
|
||||
//Assert
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
_saleStorageContract.Verify(
|
||||
x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetDataSalesByPeriod_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
_saleStorageContract
|
||||
.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.FromResult(new List<SaleDataModel>()));
|
||||
//Act
|
||||
var data = await _reportContract.GetDataSaleByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow,
|
||||
CancellationToken.None);
|
||||
//Assert
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
_saleStorageContract.Verify(
|
||||
x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetDataSalesByPeriod_WhenIncorrectDates_ShouldFail_Test()
|
||||
{
|
||||
//Arrange
|
||||
var date = DateTime.UtcNow;
|
||||
//Act&Assert
|
||||
Assert.That(async () => await _reportContract.GetDataSaleByPeriodAsync(date, date, CancellationToken.None),
|
||||
Throws.TypeOf<IncorrectDatesException>());
|
||||
Assert.That(
|
||||
async () => await _reportContract.GetDataSaleByPeriodAsync(date, DateTime.UtcNow.AddDays(-1),
|
||||
CancellationToken.None), Throws.TypeOf<IncorrectDatesException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetDataBySalesByPeriod_WhenStorageThrowError_ShouldFail_Test()
|
||||
{
|
||||
//Arrange
|
||||
_saleStorageContract
|
||||
.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
|
||||
.Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(
|
||||
async () => await _reportContract.GetDataSaleByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow,
|
||||
CancellationToken.None), Throws.TypeOf<StorageException>());
|
||||
_saleStorageContract.Verify(
|
||||
x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetDataClientDiscountByPeriod_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var startDate = DateTime.UtcNow.AddDays(-20);
|
||||
var endDate = DateTime.UtcNow.AddDays(5);
|
||||
var client1 = new ClientDataModel(Guid.NewGuid().ToString(), "fio 1", "+7-111-111-11-13", 0.1d);
|
||||
var client2 = new ClientDataModel(Guid.NewGuid().ToString(), "fio 2", "+7-111-111-11-15", 0.1d);
|
||||
_clientDiscountStorageContract
|
||||
.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.FromResult(new List<ClientDiscountDataModel>()
|
||||
{
|
||||
new(client1.Id, DateTime.UtcNow.AddDays(-10), 100, client1),
|
||||
new(client1.Id, endDate, 1000, client1),
|
||||
new(client1.Id, startDate, 1000, client1),
|
||||
new(client2.Id, DateTime.UtcNow.AddDays(-10), 100, client2),
|
||||
new(client2.Id, DateTime.UtcNow.AddDays(-5), 200, client2)
|
||||
}));
|
||||
//Act
|
||||
var data = await _reportContract.GetDataClientDiscountByPeriodAsync(DateTime.UtcNow.AddDays(-1),
|
||||
DateTime.UtcNow, CancellationToken.None);
|
||||
//Assert
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
var client1Discount = data.First(x => x.ClientFIO == client1.FIO);
|
||||
Assert.That(client1Discount, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(client1Discount.TotalDiscount, Is.EqualTo(2100));
|
||||
Assert.That(client1Discount.FromPeriod, Is.EqualTo(startDate));
|
||||
Assert.That(client1Discount.ToPeriod, Is.EqualTo(endDate));
|
||||
});
|
||||
var client2Discount = data.First(x => x.ClientFIO == client2.FIO);
|
||||
Assert.That(client2Discount, Is.Not.Null);
|
||||
Assert.That(client2Discount.TotalDiscount, Is.EqualTo(300));
|
||||
_clientDiscountStorageContract.Verify(
|
||||
x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetDataClientDiscountByPeriod_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
_clientDiscountStorageContract
|
||||
.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.FromResult(new List<ClientDiscountDataModel>()));
|
||||
//Act
|
||||
var data = await _reportContract.GetDataClientDiscountByPeriodAsync(DateTime.UtcNow.AddDays(-1),
|
||||
DateTime.UtcNow, CancellationToken.None);
|
||||
//Assert
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
_clientDiscountStorageContract.Verify(
|
||||
x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetDataClientDiscountByPeriod_WhenIncorrectDates_ShouldFail_Test()
|
||||
{
|
||||
//Arrange
|
||||
var date = DateTime.UtcNow;
|
||||
//Act&Assert
|
||||
Assert.That(
|
||||
async () => await _reportContract.GetDataClientDiscountByPeriodAsync(date, date, CancellationToken.None),
|
||||
Throws.TypeOf<IncorrectDatesException>());
|
||||
Assert.That(
|
||||
async () => await _reportContract.GetDataClientDiscountByPeriodAsync(date, DateTime.UtcNow.AddDays(-1),
|
||||
CancellationToken.None), Throws.TypeOf<IncorrectDatesException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetDataClientDiscountByPeriod_WhenStorageThrowError_ShouldFail_Test()
|
||||
{
|
||||
//Arrange
|
||||
_clientDiscountStorageContract
|
||||
.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
|
||||
.Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(
|
||||
async () => await _reportContract.GetDataClientDiscountByPeriodAsync(DateTime.UtcNow.AddDays(-1),
|
||||
DateTime.UtcNow, CancellationToken.None), Throws.TypeOf<StorageException>());
|
||||
_clientDiscountStorageContract.Verify(
|
||||
x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CreateDocumentProductHistoryPrices_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var product1 = new ProductDataModel(Guid.NewGuid().ToString(), "Product 1", "description Product 1", 10,
|
||||
ProductType.Cake);
|
||||
var product2 = new ProductDataModel(Guid.NewGuid().ToString(), "Product 2", "description Product 2", 20,
|
||||
ProductType.Cake);
|
||||
_productStorageContract.Setup(x => x.GetListAsync(It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.FromResult(new List<ProductDataModel> { product1, product2 }));
|
||||
_productStorageContract.Setup(x => x.GetHistoryByProductId(product1.Id)).Returns(
|
||||
new List<ProductHistoryDataModel>
|
||||
{
|
||||
new(product1.Id, 15, DateTime.UtcNow.AddDays(-2), product1),
|
||||
new(product1.Id, 12, DateTime.UtcNow.AddDays(-1), product1)
|
||||
});
|
||||
_productStorageContract.Setup(x => x.GetHistoryByProductId(product2.Id)).Returns(
|
||||
new List<ProductHistoryDataModel>
|
||||
{
|
||||
new(product2.Id, 25, DateTime.UtcNow.AddDays(-3), product2)
|
||||
});
|
||||
_baseWordBuilder.Setup(x => x.AddHeader(It.IsAny<string>())).Returns(_baseWordBuilder.Object);
|
||||
_baseWordBuilder.Setup(x => x.AddParagraph(It.IsAny<string>())).Returns(_baseWordBuilder.Object);
|
||||
var countRows = 0;
|
||||
string[] firstRow = [];
|
||||
string[] secondRow = [];
|
||||
string[] thirdRow = [];
|
||||
_baseWordBuilder.Setup(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>()))
|
||||
.Callback((int[] widths, List<string[]> data) =>
|
||||
{
|
||||
countRows = data.Count;
|
||||
firstRow = data[0];
|
||||
secondRow = data[1];
|
||||
thirdRow = data[2];
|
||||
})
|
||||
.Returns(_baseWordBuilder.Object);
|
||||
//Act
|
||||
var result = await _reportContract.CreateDocumentProductHistoryPricesAsync(CancellationToken.None);
|
||||
//Assert
|
||||
_productStorageContract.Verify(x => x.GetListAsync(It.IsAny<CancellationToken>()), Times.Once);
|
||||
_baseWordBuilder.Verify(x => x.AddHeader(It.IsAny<string>()), Times.Once);
|
||||
_baseWordBuilder.Verify(x => x.AddParagraph(It.IsAny<string>()), Times.Once);
|
||||
_baseWordBuilder.Verify(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>()), Times.Once);
|
||||
_baseWordBuilder.Verify(x => x.Build(), Times.Once);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(countRows, Is.EqualTo(6));
|
||||
Assert.That(firstRow, Has.Length.EqualTo(3));
|
||||
Assert.That(secondRow, Has.Length.EqualTo(3));
|
||||
Assert.That(thirdRow, Has.Length.EqualTo(3));
|
||||
});
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(firstRow[0], Is.EqualTo("Продукт"));
|
||||
Assert.That(firstRow[1], Is.EqualTo("Цена"));
|
||||
Assert.That(firstRow[2], Is.EqualTo("Дата"));
|
||||
Assert.That(secondRow[0], Is.EqualTo(product1.ProductName));
|
||||
Assert.That(secondRow[1], Is.Empty);
|
||||
Assert.That(secondRow[2], Is.Empty);
|
||||
Assert.That(thirdRow[0], Is.Empty);
|
||||
Assert.That(thirdRow[1], Is.EqualTo(12.ToString("N2")));
|
||||
Assert.That(thirdRow[2], Is.EqualTo(DateTime.UtcNow.AddDays(-1).ToString("dd.MM.yyyy")));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CreateDocumentSalesByPeriod_ShouldSuccess_Test()
|
||||
{
|
||||
var porduct1 =
|
||||
new ProductDataModel(Guid.NewGuid().ToString(), "name 1", "description 1", 10, ProductType.Candy);
|
||||
var porduct2 =
|
||||
new ProductDataModel(Guid.NewGuid().ToString(), "name 2", "description 2", 10, ProductType.Candy);
|
||||
_saleStorageContract
|
||||
.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.FromResult(new List<SaleDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.RegularCustomer, false,
|
||||
[
|
||||
new SaleProductDataModel("", porduct1.Id, 10, 10, porduct1),
|
||||
new SaleProductDataModel("", porduct2.Id, 10, 10, porduct2)
|
||||
]),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, DiscountType.RegularCustomer, false,
|
||||
[new SaleProductDataModel("", porduct2.Id, 10, 10, porduct2)])
|
||||
}));
|
||||
_baseExcelBuilder.Setup(x => x.AddHeader(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()))
|
||||
.Returns(_baseExcelBuilder.Object);
|
||||
_baseExcelBuilder.Setup(x => x.AddParagraph(It.IsAny<string>(), It.IsAny<int>()))
|
||||
.Returns(_baseExcelBuilder.Object);
|
||||
var countRows = 0;
|
||||
string[] firstRow = [];
|
||||
string[] secondRow = [];
|
||||
_baseExcelBuilder.Setup(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>()))
|
||||
.Callback((int[] widths, List<string[]> data) =>
|
||||
{
|
||||
countRows = data.Count;
|
||||
firstRow = data[0];
|
||||
secondRow = data[1];
|
||||
})
|
||||
.Returns(_baseExcelBuilder.Object);
|
||||
//Act
|
||||
var data = await _reportContract.CreateDocumentSalesByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow,
|
||||
CancellationToken.None);
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(countRows, Is.EqualTo(7));
|
||||
Assert.That(firstRow, Is.Not.EqualTo(default));
|
||||
Assert.That(secondRow, Is.Not.EqualTo(default));
|
||||
});
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(firstRow[0], Is.EqualTo("Дата"));
|
||||
Assert.That(firstRow[1], Is.EqualTo("Сумма"));
|
||||
Assert.That(firstRow[2], Is.EqualTo("Скидка"));
|
||||
Assert.That(firstRow[3], Is.EqualTo("Продавец"));
|
||||
Assert.That(firstRow[4], Is.EqualTo("Товар"));
|
||||
Assert.That(firstRow[5], Is.EqualTo("Кол-во"));
|
||||
Assert.That(secondRow[0], Is.EqualTo(DateTime.UtcNow.ToString("dd.MM.yyyy")));
|
||||
Assert.That(secondRow[1], Is.EqualTo(200.ToString("N2")));
|
||||
Assert.That(secondRow[2], Is.EqualTo(100.ToString("N2")));
|
||||
});
|
||||
_saleStorageContract.Verify(
|
||||
x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
_baseExcelBuilder.Verify(x => x.AddHeader(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()), Times.Once);
|
||||
_baseExcelBuilder.Verify(x => x.AddParagraph(It.IsAny<string>(), It.IsAny<int>()), Times.Once);
|
||||
_baseExcelBuilder.Verify(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>()), Times.Once);
|
||||
_baseExcelBuilder.Verify(x => x.Build(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CreateDocumentClientDiscountByPeriod_ShouldeSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var startDate = DateTime.UtcNow.AddDays(-20);
|
||||
var endDate = DateTime.UtcNow.AddDays(5);
|
||||
var client1 = new ClientDataModel(Guid.NewGuid().ToString(), "fio 1", "+7-111-111-11-13", 0.1d);
|
||||
var client2 = new ClientDataModel(Guid.NewGuid().ToString(), "fio 2", "+7-111-111-11-15", 0.1d);
|
||||
_clientDiscountStorageContract
|
||||
.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.FromResult(new List<ClientDiscountDataModel>()
|
||||
{
|
||||
new(client1.Id, DateTime.UtcNow.AddDays(-10), 100, client1),
|
||||
new(client1.Id, endDate, 1000, client1),
|
||||
new(client1.Id, startDate, 1000, client1),
|
||||
new(client2.Id, DateTime.UtcNow.AddDays(-10), 100, client2),
|
||||
new(client2.Id, DateTime.UtcNow.AddDays(-5), 200, client2)
|
||||
}));
|
||||
_basePdfBuilder.Setup(x => x.AddHeader(It.IsAny<string>())).Returns(_basePdfBuilder.Object);
|
||||
_basePdfBuilder.Setup(x => x.AddParagraph(It.IsAny<string>())).Returns(_basePdfBuilder.Object);
|
||||
var countRows = 0;
|
||||
(string, double) firstRow = default;
|
||||
(string, double) secondRow = default;
|
||||
_basePdfBuilder.Setup(x => x.AddPieChart(It.IsAny<string>(), It.IsAny<List<(string, double)>>()))
|
||||
.Callback((string header, List<(string, double)> data) =>
|
||||
{
|
||||
countRows = data.Count;
|
||||
firstRow = data[0];
|
||||
secondRow = data[1];
|
||||
})
|
||||
.Returns(_basePdfBuilder.Object);
|
||||
//Act
|
||||
var data = await _reportContract.CreateDocumentClientDiscountByPeriodAsync(DateTime.UtcNow.AddDays(-1),
|
||||
DateTime.UtcNow, CancellationToken.None);
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(countRows, Is.EqualTo(2));
|
||||
Assert.That(firstRow, Is.Not.EqualTo(default));
|
||||
Assert.That(secondRow, Is.Not.EqualTo(default));
|
||||
});
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(firstRow.Item1, Is.EqualTo(client1.FIO));
|
||||
Assert.That(firstRow.Item2, Is.EqualTo(2100));
|
||||
Assert.That(secondRow.Item1, Is.EqualTo(client2.FIO));
|
||||
Assert.That(secondRow.Item2, Is.EqualTo(300));
|
||||
});
|
||||
_clientDiscountStorageContract.Verify(
|
||||
x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
_basePdfBuilder.Verify(x => x.AddHeader(It.IsAny<string>()), Times.Once);
|
||||
_basePdfBuilder.Verify(x => x.AddParagraph(It.IsAny<string>()), Times.Once);
|
||||
_basePdfBuilder.Verify(x => x.AddPieChart(It.IsAny<string>(), It.IsAny<List<(string, double)>>()), Times.Once);
|
||||
_basePdfBuilder.Verify(x => x.Build(), Times.Once);
|
||||
}
|
||||
}
|
||||
@@ -58,14 +58,14 @@ internal class ClientDataModelTests
|
||||
var fio = "Fio";
|
||||
var phoneNumber = "+7-777-777-77-77";
|
||||
var discountSize = 11;
|
||||
var buyer = CreateDataModel(clientId, fio, phoneNumber, discountSize);
|
||||
Assert.That(() => buyer.Validate(), Throws.Nothing);
|
||||
var client = CreateDataModel(clientId, fio, phoneNumber, discountSize);
|
||||
Assert.That(() => client.Validate(), Throws.Nothing);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(buyer.Id, Is.EqualTo(clientId));
|
||||
Assert.That(buyer.FIO, Is.EqualTo(fio));
|
||||
Assert.That(buyer.PhoneNumber, Is.EqualTo(phoneNumber));
|
||||
Assert.That(buyer.DiscountSize, Is.EqualTo(discountSize));
|
||||
Assert.That(client.Id, Is.EqualTo(clientId));
|
||||
Assert.That(client.FIO, Is.EqualTo(fio));
|
||||
Assert.That(client.PhoneNumber, Is.EqualTo(phoneNumber));
|
||||
Assert.That(client.DiscountSize, Is.EqualTo(discountSize));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -14,73 +14,73 @@ internal class EmployeeDataModelTests
|
||||
[Test]
|
||||
public void IdIsNullOrEmptyTest()
|
||||
{
|
||||
var employee = CreateDataModel(null, "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
|
||||
var employee = CreateDataModel(null, "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
|
||||
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
|
||||
employee = CreateDataModel(string.Empty, "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
|
||||
employee = CreateDataModel(string.Empty, "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
|
||||
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void IdIsNotGuidTest()
|
||||
{
|
||||
var employee = CreateDataModel("id", "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
|
||||
var employee = CreateDataModel("id", "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
|
||||
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FIOIsNullOrEmptyTest()
|
||||
{
|
||||
var employee = CreateDataModel(Guid.NewGuid().ToString(), null, "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
|
||||
var employee = CreateDataModel(Guid.NewGuid().ToString(), null, "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
|
||||
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
|
||||
employee = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
|
||||
employee = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
|
||||
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EmailIsNullOrEmptyTest()
|
||||
{
|
||||
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", null, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
|
||||
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", null, Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
|
||||
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
|
||||
employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", string.Empty, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
|
||||
employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", string.Empty, Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
|
||||
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EmailIsIncorrectTest()
|
||||
{
|
||||
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now, false);
|
||||
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
|
||||
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PostIdIsNullOrEmptyTest()
|
||||
{
|
||||
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", null, DateTime.Now.AddYears(-18), DateTime.Now, false);
|
||||
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", null, DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
|
||||
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
|
||||
employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", string.Empty, DateTime.Now.AddYears(-18), DateTime.Now, false);
|
||||
employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", string.Empty, DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
|
||||
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PostIdIsNotGuidTest()
|
||||
{
|
||||
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", "postId", DateTime.Now.AddYears(-18), DateTime.Now, false);
|
||||
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", "postId", DateTime.UtcNow.AddYears(-18), DateTime.UtcNow, false);
|
||||
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void BirthDateIsNotCorrectTest()
|
||||
{
|
||||
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-16).AddDays(1), DateTime.Now, false);
|
||||
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-16).AddDays(1), DateTime.UtcNow, false);
|
||||
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void BirthDateAndEmploymentDateIsNotCorrectTest()
|
||||
{
|
||||
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now.AddYears(-18).AddDays(-1), false);
|
||||
var employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18), DateTime.UtcNow.AddYears(-18).AddDays(-1), false);
|
||||
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
|
||||
employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18), DateTime.Now.AddYears(-16), false);
|
||||
employee = CreateDataModel(Guid.NewGuid().ToString(), "fio", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-18), DateTime.UtcNow.AddYears(-16), false);
|
||||
Assert.That(() => employee.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
@@ -91,8 +91,8 @@ internal class EmployeeDataModelTests
|
||||
var fio = "fio";
|
||||
var employeeEmail = "abc@gmail.com";
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
var birthDate = DateTime.Now.AddYears(-18).AddDays(-1);
|
||||
var employmentDate = DateTime.Now;
|
||||
var birthDate = DateTime.UtcNow.AddYears(-18).AddDays(-1);
|
||||
var employmentDate = DateTime.UtcNow;
|
||||
var isDelete = false;
|
||||
var employee = CreateDataModel(employeeId, fio, employeeEmail, postId, birthDate, employmentDate, isDelete);
|
||||
Assert.That(() => employee.Validate(), Throws.Nothing);
|
||||
|
||||
@@ -14,25 +14,25 @@ internal class SalaryDataModelTests
|
||||
[Test]
|
||||
public void EmployeeIdIsEmptyTest()
|
||||
{
|
||||
var salary = CreateDataModel(null, DateTime.Now, 10);
|
||||
var salary = CreateDataModel(null, DateTime.UtcNow, 10);
|
||||
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
|
||||
salary = CreateDataModel(string.Empty, DateTime.Now, 10);
|
||||
salary = CreateDataModel(string.Empty, DateTime.UtcNow, 10);
|
||||
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EmployeeIdIsNotGuidTest()
|
||||
{
|
||||
var salary = CreateDataModel("employeeId", DateTime.Now, 10);
|
||||
var salary = CreateDataModel("employeeId", DateTime.UtcNow, 10);
|
||||
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SalaryIsLessOrZeroTest()
|
||||
{
|
||||
var salary = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now, 0);
|
||||
var salary = CreateDataModel(Guid.NewGuid().ToString(), DateTime.UtcNow, 0);
|
||||
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
|
||||
salary = CreateDataModel(Guid.NewGuid().ToString(), DateTime.Now, -10);
|
||||
salary = CreateDataModel(Guid.NewGuid().ToString(), DateTime.UtcNow, -10);
|
||||
Assert.That(() => salary.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ internal class SalaryDataModelTests
|
||||
public void AllFieldsIsCorrectTest()
|
||||
{
|
||||
var employeeId = Guid.NewGuid().ToString();
|
||||
var salaryDate = DateTime.Now.AddDays(-3).AddMinutes(-5);
|
||||
var salaryDate = DateTime.UtcNow.AddDays(-3).AddMinutes(-5);
|
||||
var enployeeSalary = 10;
|
||||
var salary = CreateDataModel(employeeId, salaryDate, enployeeSalary);
|
||||
Assert.That(() => salary.Validate(), Throws.Nothing);
|
||||
|
||||
@@ -75,6 +75,13 @@ internal static class CandyHouseDbContextExtensions
|
||||
dbContext.SaveChanges();
|
||||
return employee;
|
||||
}
|
||||
public static ClientDiscount InsertClientDiscountToDatabaseAndReturn(this CandyHouseDbContext dbContext, string clientId, double discountAmount = 1, DateTime? discountDate = null)
|
||||
{
|
||||
var clientDiscount = new ClientDiscount() { ClientId = clientId, DiscountAmount = discountAmount, DiscountDate = discountDate ?? DateTime.UtcNow };
|
||||
dbContext.ClientDiscounts.Add(clientDiscount);
|
||||
dbContext.SaveChanges();
|
||||
return clientDiscount;
|
||||
}
|
||||
|
||||
public static Client? GetClientFromDatabase(this CandyHouseDbContext dbContext, string id) => dbContext.Clients.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
@@ -91,6 +98,7 @@ internal static class CandyHouseDbContextExtensions
|
||||
public static Sale[] GetSalesByClientId(this CandyHouseDbContext dbContext, string? clientId) => [.. dbContext.Sales.Include(x => x.SaleProducts).Where(x => x.ClientId == clientId)];
|
||||
|
||||
public static Employee? GetEmployeeFromDatabaseById(this CandyHouseDbContext dbContext, string id) => dbContext.Employees.FirstOrDefault(x => x.Id == id);
|
||||
public static ClientDiscount[] GetClientDiscountsFromDatabaseByClientId(this CandyHouseDbContext dbContext, string id) => [.. dbContext.ClientDiscounts.Where(x => x.ClientId == id)];
|
||||
|
||||
public static void RemoveClientsFromDatabase(this CandyHouseDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Clients\" CASCADE;");
|
||||
|
||||
@@ -103,6 +111,7 @@ internal static class CandyHouseDbContextExtensions
|
||||
public static void RemoveSalesFromDatabase(this CandyHouseDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Sales\" CASCADE;");
|
||||
|
||||
public static void RemoveEmployeesFromDatabase(this CandyHouseDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"Employees\" CASCADE;");
|
||||
public static void RemoveClientDiscountsFromDatabase(this CandyHouseDbContext dbContext) => dbContext.ExecuteSqlRaw("TRUNCATE \"ClientDiscounts\" CASCADE;");
|
||||
|
||||
private static void ExecuteSqlRaw(this CandyHouseDbContext dbContext, string command) => dbContext.Database.ExecuteSqlRaw(command);
|
||||
}
|
||||
@@ -149,7 +149,7 @@ internal class ClientStorageContractTests : BaseStorageContractTest
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenHaveSalesByThisBuyer_Test()
|
||||
public void Try_DelElement_WhenHaveSalesByThisEmploeer_Test()
|
||||
{
|
||||
var client = InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var employeeId = Guid.NewGuid().ToString();
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
using System.Net;
|
||||
using CandyHouseContracts.ViewModels;
|
||||
using CandyHouseTests.Infrastructure;
|
||||
|
||||
namespace CandyHouseTests.WebApiControllersTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class ReportControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
CandyHouseDbContext.RemoveClientDiscountsFromDatabase();
|
||||
CandyHouseDbContext.RemoveSalesFromDatabase();
|
||||
CandyHouseDbContext.RemoveClientsFromDatabase();
|
||||
CandyHouseDbContext.RemoveProductsFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetProductHistoryPrices_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var product1 = CandyHouseDbContext.InsertProductToDatabaseAndReturn(productName: "Product 1", price: 10);
|
||||
var product2 = CandyHouseDbContext.InsertProductToDatabaseAndReturn(productName: "Product 2", price: 20);
|
||||
CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product1.Id, 17, DateTime.UtcNow.AddDays(-3));
|
||||
CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product1.Id, 15, DateTime.UtcNow.AddDays(-2));
|
||||
CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product1.Id, 12, DateTime.UtcNow.AddDays(-1));
|
||||
CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product2.Id, 25, DateTime.UtcNow.AddDays(-4));
|
||||
CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product2.Id, 26, DateTime.UtcNow.AddDays(-3));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/report/getproducthistoryprices");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ProductHistoryPricesViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
Assert.That(data.First(x => x.ProductName == product1.ProductName).Prices, Has.Count.EqualTo(3));
|
||||
Assert.That(data.First(x => x.ProductName == product2.ProductName).Prices, Has.Count.EqualTo(2));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetSales_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = CandyHouseDbContext.InsertEmployeeToDatabaseAndReturn();
|
||||
var product1 = CandyHouseDbContext.InsertProductToDatabaseAndReturn(productName: "name 1");
|
||||
var product2 = CandyHouseDbContext.InsertProductToDatabaseAndReturn(productName: "name 2");
|
||||
CandyHouseDbContext.InsertSaleToDatabaseAndReturn(worker.Id,
|
||||
products: [(product1.Id, 10, 1.1), (product2.Id, 10, 1.1)]);
|
||||
CandyHouseDbContext.InsertSaleToDatabaseAndReturn(worker.Id, products: [(product1.Id, 10, 1.1)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync(
|
||||
$"/api/report/getsales?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() => { Assert.That(data, Has.Count.EqualTo(2)); });
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetSales_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync(
|
||||
$"/api/report/getsales?fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetClientDiscount_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var client1 = CandyHouseDbContext.InsertClientToDatabaseAndReturn(fio: "fio 1", phoneNumber: "+5-555-555-55-55");
|
||||
var client2 = CandyHouseDbContext.InsertClientToDatabaseAndReturn(fio: "fio 2", phoneNumber: "+5-555-555-57-56");
|
||||
CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client1.Id, discountAmount: 100,
|
||||
discountDate: DateTime.UtcNow.AddDays(-10));
|
||||
CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client1.Id, discountAmount: 1000,
|
||||
discountDate: DateTime.UtcNow.AddDays(-5));
|
||||
CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client1.Id, discountAmount: 200,
|
||||
discountDate: DateTime.UtcNow.AddDays(5));
|
||||
CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client2.Id, discountAmount: 500,
|
||||
discountDate: DateTime.UtcNow.AddDays(-5));
|
||||
CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client2.Id, discountAmount: 300,
|
||||
discountDate: DateTime.UtcNow.AddDays(-3));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync(
|
||||
$"/api/report/GetClientDiscount?fromDate={DateTime.UtcNow.AddDays(-7):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ClientDiscountByPeriodViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data.First(x => x.ClientFIO == client1.FIO).TotalDiscount, Is.EqualTo(1000));
|
||||
Assert.That(data.First(x => x.ClientFIO == client2.FIO).TotalDiscount, Is.EqualTo(800));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetClientDiscount_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync(
|
||||
$"/api/report/GetClientDiscount?fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task LoadProductHistoryPrices_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var product1 = CandyHouseDbContext.InsertProductToDatabaseAndReturn(productName: "Product 1", price: 10);
|
||||
var product2 = CandyHouseDbContext.InsertProductToDatabaseAndReturn(productName: "Product 2", price: 20);
|
||||
CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product1.Id, 17, DateTime.UtcNow.AddDays(-3));
|
||||
CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product1.Id, 15, DateTime.UtcNow.AddDays(-2));
|
||||
CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product1.Id, 12, DateTime.UtcNow.AddDays(-1));
|
||||
CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product2.Id, 25, DateTime.UtcNow.AddDays(-4));
|
||||
CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product2.Id, 26, DateTime.UtcNow.AddDays(-3));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/report/LoadProductHistoryPrices");
|
||||
//Assert
|
||||
await AssertStreamAsync(response, "file.docx");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task LoadSales_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = CandyHouseDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio_worker");
|
||||
var product1 = CandyHouseDbContext.InsertProductToDatabaseAndReturn(productName: "name 1");
|
||||
var product2 = CandyHouseDbContext.InsertProductToDatabaseAndReturn(productName: "name 2");
|
||||
CandyHouseDbContext.InsertSaleToDatabaseAndReturn(worker.Id, sum: 60,
|
||||
products: [(product1.Id, 10, 2), (product2.Id, 10, 4)]);
|
||||
CandyHouseDbContext.InsertSaleToDatabaseAndReturn(worker.Id, sum: 20, products: [(product1.Id, 10, 2)]);
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync(
|
||||
$"/api/report/loadsales?fromDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
await AssertStreamAsync(response, "file.xlsx");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task LoadSales_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync(
|
||||
$"/api/report/loadsales?fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task LoadSalary_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var client1 = CandyHouseDbContext.InsertClientToDatabaseAndReturn(fio: "fio 1", phoneNumber: "+5-555-555-55-55");
|
||||
var client2 = CandyHouseDbContext.InsertClientToDatabaseAndReturn(fio: "fio 2", phoneNumber: "+5-555-555-57-56");
|
||||
CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client1.Id, discountAmount: 100,
|
||||
discountDate: DateTime.UtcNow.AddDays(-10));
|
||||
CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client1.Id, discountAmount: 1000,
|
||||
discountDate: DateTime.UtcNow.AddDays(-5));
|
||||
CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client1.Id, discountAmount: 200,
|
||||
discountDate: DateTime.UtcNow.AddDays(5));
|
||||
CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client2.Id, discountAmount: 500,
|
||||
discountDate: DateTime.UtcNow.AddDays(-5));
|
||||
CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client2.Id, discountAmount: 300,
|
||||
discountDate: DateTime.UtcNow.AddDays(-3));
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync(
|
||||
$"/api/report/LoadClientDiscount?fromDate={DateTime.UtcNow.AddDays(-7):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
await AssertStreamAsync(response, "file.pdf");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task LoadClientDiscount_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync(
|
||||
$"/api/report/loadclientdiscount?fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
private static async Task AssertStreamAsync(HttpResponseMessage response, string fileNameForSave = "")
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
using var data = await response.Content.ReadAsStreamAsync();
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data.Length, Is.GreaterThan(0));
|
||||
await SaveStreamAsync(data, fileNameForSave);
|
||||
}
|
||||
|
||||
private static async Task SaveStreamAsync(Stream stream, string fileName)
|
||||
{
|
||||
if (string.IsNullOrEmpty(fileName))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var path = Path.Combine(Directory.GetCurrentDirectory(), fileName);
|
||||
if (File.Exists(path))
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
|
||||
stream.Position = 0;
|
||||
using var fileStream = new FileStream(path, FileMode.OpenOrCreate);
|
||||
await stream.CopyToAsync(fileStream);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ using CandyHouseContracts.AdapterContracts;
|
||||
using CandyHouseContracts.AdapterContracts.OperationResponses;
|
||||
using CandyHouseContracts.BindingModels;
|
||||
using CandyHouseContracts.BuisnessLogicContracts;
|
||||
using CandyHouseContracts.BusinessLogicContracts;
|
||||
using CandyHouseContracts.DataModels;
|
||||
using CandyHouseContracts.Exceptions;
|
||||
using CandyHouseContracts.ViewModels;
|
||||
|
||||
208
CandyHouseSolution/CandyHouseWebApi/Adapters/ReportAdapter.cs
Normal file
208
CandyHouseSolution/CandyHouseWebApi/Adapters/ReportAdapter.cs
Normal file
@@ -0,0 +1,208 @@
|
||||
using AutoMapper;
|
||||
using CandyHouseContracts.AdapterContracts;
|
||||
using CandyHouseContracts.AdapterContracts.OperationResponses;
|
||||
using CandyHouseContracts.BusinessLogicContracts;
|
||||
using CandyHouseContracts.DataModels;
|
||||
using CandyHouseContracts.Exceptions;
|
||||
using CandyHouseContracts.ViewModels;
|
||||
|
||||
namespace CandyHouseWebApi.Adapters;
|
||||
|
||||
public class ReportAdapter : IReportAdapter
|
||||
{
|
||||
private readonly IReportContract _reportContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public ReportAdapter(IReportContract reportContract, ILogger<ProductAdapter> logger)
|
||||
{
|
||||
_reportContract = reportContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<ProductHistoryPricesDataModel, ProductHistoryPricesViewModel>();
|
||||
cfg.CreateMap<SaleDataModel, SaleViewModel>();
|
||||
cfg.CreateMap<SaleProductDataModel, SaleProductViewModel>();
|
||||
cfg.CreateMap<ClientDiscountByPeriodDataModel, ClientDiscountByPeriodViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public async Task<ReportOperationResponse> GetDataProductHistoryPricesAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ReportOperationResponse.OK([.. (await _reportContract.GetDataProductHistoryPricesAsync(ct)).Select(x => _mapper.Map<ProductHistoryPricesViewModel>(x))]);
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "InvalidOperationException");
|
||||
var errorMessage = ex.InnerException?.Message ?? ex.Message;
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {errorMessage}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
var errorMessage = ex.InnerException?.Message ?? ex.Message;
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {errorMessage}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ReportOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ReportOperationResponse> GetDataSaleByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ReportOperationResponse.OK((await _reportContract.GetDataSaleByPeriodAsync(dateStart, dateFinish, ct)).Select(x => _mapper.Map<SaleViewModel>(x)).ToList());
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "InvalidOperationException");
|
||||
var errorMessage = ex.InnerException?.Message ?? ex.Message;
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {errorMessage}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
var errorMessage = ex.InnerException?.Message ?? ex.Message;
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {errorMessage}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ReportOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ReportOperationResponse> GetDataClientDiscountByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ReportOperationResponse.OK((await _reportContract.GetDataClientDiscountByPeriodAsync(dateStart, dateFinish, ct)).Select(x => _mapper.Map<ClientDiscountByPeriodViewModel>(x)).ToList());
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "InvalidOperationException");
|
||||
var errorMessage = ex.InnerException?.Message ?? ex.Message;
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {errorMessage}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
var errorMessage = ex.InnerException?.Message ?? ex.Message;
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {errorMessage}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ReportOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ReportOperationResponse> CreateDocumentProductHistoryPricesAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SendStream(await _reportContract.CreateDocumentProductHistoryPricesAsync(ct), "producthistoryprices.docx");
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "InvalidOperationException");
|
||||
var errorMessage = ex.InnerException?.Message ?? ex.Message;
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {errorMessage}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
var errorMessage = ex.InnerException?.Message ?? ex.Message;
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {errorMessage}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ReportOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ReportOperationResponse> CreateDocumentSalesByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SendStream(await _reportContract.CreateDocumentSalesByPeriodAsync(dateStart, dateFinish, ct), "sales.xslx");
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "InvalidOperationException");
|
||||
var errorMessage = ex.InnerException?.Message ?? ex.Message;
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {errorMessage}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
var errorMessage = ex.InnerException?.Message ?? ex.Message;
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {errorMessage}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ReportOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ReportOperationResponse> CreateDocumentClientDiscountByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SendStream(await _reportContract.CreateDocumentClientDiscountByPeriodAsync(dateStart, dateFinish, ct), "file.pdf");
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "InvalidOperationException");
|
||||
var errorMessage = ex.InnerException?.Message ?? ex.Message;
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {errorMessage}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
var errorMessage = ex.InnerException?.Message ?? ex.Message;
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {errorMessage}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ReportOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private static ReportOperationResponse SendStream(Stream stream, string fileName)
|
||||
{
|
||||
stream.Position = 0;
|
||||
return ReportOperationResponse.OK(stream, fileName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using CandyHouseContracts.AdapterContracts;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace CandyHouseWebApi.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[Route("api/[controller]/[action]")]
|
||||
[ApiController]
|
||||
public class ReportController(IReportAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly IReportAdapter _adapter = adapter;
|
||||
|
||||
[HttpGet]
|
||||
[Consumes("application/json")]
|
||||
public async Task<IActionResult> GetProductHistoryPrices(CancellationToken ct)
|
||||
{
|
||||
return (await _adapter.GetDataProductHistoryPricesAsync(ct)).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Consumes("application/json")]
|
||||
public async Task<IActionResult> GetSales(DateTime fromDate, DateTime toDate, CancellationToken cancellationToken)
|
||||
{
|
||||
return (await _adapter.GetDataSaleByPeriodAsync(fromDate, toDate, cancellationToken)).GetResponse(Request,
|
||||
Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Consumes("application/json")]
|
||||
public async Task<IActionResult> GetClientDiscount(DateTime fromDate, DateTime toDate,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return (await _adapter.GetDataClientDiscountByPeriodAsync(fromDate, toDate, cancellationToken)).GetResponse(
|
||||
Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Consumes("application/octet-stream")]
|
||||
public async Task<IActionResult> LoadProductHistoryPrices(CancellationToken cancellationToken)
|
||||
{
|
||||
return (await _adapter.CreateDocumentProductHistoryPricesAsync(cancellationToken)).GetResponse(Request,
|
||||
Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Consumes("application/octet-stream")]
|
||||
public async Task<IActionResult> LoadSales(DateTime fromDate, DateTime toDate, CancellationToken cancellationToken)
|
||||
{
|
||||
return (await _adapter.CreateDocumentSalesByPeriodAsync(fromDate, toDate, cancellationToken)).GetResponse(
|
||||
Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Consumes("application/octet-stream")]
|
||||
public async Task<IActionResult> LoadClientDiscount(DateTime fromDate, DateTime toDate,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return (await _adapter.CreateDocumentClientDiscountByPeriodAsync(fromDate, toDate, cancellationToken))
|
||||
.GetResponse(Request, Response);
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ public class WeatherForecastController : ControllerBase
|
||||
{
|
||||
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
|
||||
{
|
||||
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
|
||||
Date = DateOnly.FromDateTime(DateTime.UtcNow.AddDays(index)),
|
||||
TemperatureC = Random.Shared.Next(-20, 55),
|
||||
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
|
||||
})
|
||||
|
||||
@@ -14,9 +14,15 @@ using Microsoft.IdentityModel.Tokens;
|
||||
using Serilog;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using CandyHouseBusinessLogic.OfficePackage;
|
||||
using CandyHouseContracts.BusinessLogicContracts;
|
||||
using PdfSharp.Fonts;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Configure PDFSharp to use Windows system fonts
|
||||
GlobalFontSettings.UseWindowsFontsUnderWindows = true;
|
||||
|
||||
// Add services to the container.
|
||||
|
||||
builder.Services.AddControllers();
|
||||
@@ -31,7 +37,6 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
{
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
|
||||
ValidateIssuer = true,
|
||||
|
||||
ValidIssuer = AuthOptions.ISSUER,
|
||||
@@ -65,6 +70,8 @@ builder.Services.AddTransient<ISalaryStorageContract, SalaryStorageContract>();
|
||||
builder.Services.AddTransient<ISaleStorageContract, SaleStorageContract>();
|
||||
builder.Services.AddTransient<IEmployeeStorageContract, EmployeeStorageContract>();
|
||||
|
||||
builder.Services.AddTransient<IClientDiscountStorageContract, ClientDiscountStorageContract>();
|
||||
|
||||
builder.Services.AddTransient<IClientAdapter, ClientAdapter>();
|
||||
builder.Services.AddTransient<IPostAdapter, PostAdapter>();
|
||||
builder.Services.AddTransient<IProductAdapter, ProductAdapter>();
|
||||
@@ -73,6 +80,12 @@ builder.Services.AddTransient<IEmployeeAdapter, EmployeeAdapter>();
|
||||
builder.Services.AddTransient<ISalaryAdapter, SalaryAdapter>();
|
||||
builder.Services.AddSingleton<IConfigurationSalary, ConfigurationSalary>();
|
||||
|
||||
|
||||
builder.Services.AddTransient<IReportContract, ReportContract>();
|
||||
builder.Services.AddTransient<BaseWordBuilder, OpenXmlWordBuilder>();
|
||||
builder.Services.AddTransient<BaseExcelBuilder, OpenXmlExcelBuilder>();
|
||||
builder.Services.AddTransient<BasePdfBuilder, MigraDocPdfBuilder>();
|
||||
builder.Services.AddTransient<IReportAdapter, ReportAdapter>();
|
||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||
builder.Services.AddOpenApi();
|
||||
|
||||
@@ -82,6 +95,7 @@ if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.MapOpenApi();
|
||||
}
|
||||
|
||||
if (app.Environment.IsProduction())
|
||||
{
|
||||
var dbContext = app.Services.GetRequiredService<CandyHouseDbContext>();
|
||||
@@ -99,11 +113,12 @@ app.UseAuthorization();
|
||||
app.Map("/login/{username}", (string username) =>
|
||||
{
|
||||
return new JwtSecurityTokenHandler().WriteToken(new JwtSecurityToken(
|
||||
issuer: AuthOptions.ISSUER,
|
||||
audience: AuthOptions.AUDIENCE,
|
||||
claims: [new(ClaimTypes.Name, username)],
|
||||
expires: DateTime.UtcNow.Add(TimeSpan.FromMinutes(2)),
|
||||
signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)));
|
||||
issuer: AuthOptions.ISSUER,
|
||||
audience: AuthOptions.AUDIENCE,
|
||||
claims: [new(ClaimTypes.Name, username)],
|
||||
expires: DateTime.UtcNow.Add(TimeSpan.FromMinutes(2)),
|
||||
signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(),
|
||||
SecurityAlgorithms.HmacSha256)));
|
||||
});
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
Reference in New Issue
Block a user