Pibd-21_Semin_D.A._SmallSoftware_LabWork06 #6
@@ -0,0 +1,152 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SmallSoftwareBusinessLogic.OfficePackage;
|
||||
using SmallSoftwareContracts.BusinessLogicsContracts;
|
||||
using SmallSoftwareContracts.DataModels;
|
||||
using SmallSoftwareContracts.Exceptions;
|
||||
using SmallSoftwareContracts.Extensions;
|
||||
using SmallSoftwareContracts.StoragesContracts;
|
||||
|
||||
namespace SmallSoftwareBusinessLogic.Implementations;
|
||||
|
||||
internal class ReportContract(ISoftwareStorageContract softwareStorageContract,
|
||||
IRequestStorageContract requestStorageContract,
|
||||
ISalaryStorageContract salaryStorageContract,
|
||||
BaseWordBuilder baseWordBuilder,
|
||||
BaseExcelBuilder baseExcelBuilder,
|
||||
BasePdfBuilder basePdfBuilder, ILogger logger) : IReportContract
|
||||
{
|
||||
private readonly ISoftwareStorageContract _softwareStorageContract = softwareStorageContract;
|
||||
private readonly ILogger _logger = logger;
|
||||
private readonly IRequestStorageContract _requestStorageContract = requestStorageContract;
|
||||
private readonly ISalaryStorageContract _salaryStorageContract = salaryStorageContract;
|
||||
private readonly BaseWordBuilder _baseWordBuilder = baseWordBuilder;
|
||||
private readonly BaseExcelBuilder _baseExcelBuilder = baseExcelBuilder;
|
||||
|
||||
private readonly BasePdfBuilder _basePdfBuilder = basePdfBuilder;
|
||||
|
||||
internal static readonly string[] tableHeader = ["Дата", "Сумма", "Товар", "Кол-во"];
|
||||
internal static readonly string[] documentHeader = ["Название ПО", "Старая цена", "Дата"];
|
||||
|
||||
public Task<List<HistoryOfSoftwareDataModel>> GetDataSoftwaresByHistoryAsync(CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Get data SoftwaresByManufacturer");
|
||||
return GetDataBySoftwaresAsync(ct);
|
||||
}
|
||||
private async Task<List<HistoryOfSoftwareDataModel>> GetDataBySoftwaresAsync(CancellationToken ct)
|
||||
=> [.. (await _softwareStorageContract.GetListAsync(ct)).GroupBy(x => x.SoftwareName).Select(x => new HistoryOfSoftwareDataModel {
|
||||
SoftwareName = x.Key, Histories = [.. x.Select(y => y.OldPrice.ToString())], Data = [.. x.Select(y => y.ChangeDate.ToString())] })];
|
||||
|
||||
|
||||
public async Task<Stream> CreateDocumentSoftwaresByHistoryAsync(CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Create report HistoryBySoftware");
|
||||
var data = await GetDataBySoftwaresAsync(ct) ?? throw new InvalidOperationException("No found data");
|
||||
|
||||
var tableData = new List<string[]>
|
||||
{
|
||||
documentHeader
|
||||
};
|
||||
|
||||
foreach (var software in data)
|
||||
{
|
||||
tableData.Add(new string[] { software.SoftwareName, "", "" });
|
||||
|
||||
var pairs = software.Histories.Zip(software.Data,
|
||||
(price, date) => new string[] { "", price, date });
|
||||
|
||||
tableData.AddRange(pairs);
|
||||
}
|
||||
|
||||
return _baseWordBuilder
|
||||
.AddHeader("Истории ПО")
|
||||
.AddParagraph($"Сформировано на дату {DateTime.Now}")
|
||||
.AddTable(
|
||||
widths: new[] { 3000, 3000, 3000 },
|
||||
data: tableData
|
||||
)
|
||||
.Build();
|
||||
}
|
||||
|
||||
public Task<List<RequestDataModel>> GetDataRequestByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Get data RequestsByPeriod from {dateStart} to {dateFinish}", dateStart, dateFinish);
|
||||
return GetDataByRequestsAsync(dateStart, dateFinish, ct);
|
||||
}
|
||||
|
||||
private async Task<List<RequestDataModel>> GetDataByRequestsAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
|
||||
{
|
||||
if (dateStart.IsDateNotOlder(dateFinish))
|
||||
{
|
||||
throw new IncorrectDatesException(dateStart, dateFinish);
|
||||
}
|
||||
return [.. (await _requestStorageContract.GetListAsync(dateStart, dateFinish, ct)).OrderBy(x => x.RequestDate)];
|
||||
}
|
||||
|
||||
public async Task<Stream> CreateDocumentRequestsByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
|
||||
{
|
||||
logger.LogInformation("Create report RequestsByPeriod from {dateStart} to {dateFinish}", dateStart, dateFinish);
|
||||
var data = await GetDataByRequestsAsync(dateStart, dateFinish, ct) ?? throw new InvalidOperationException("No found data");
|
||||
|
||||
var tableHeader = new string[] { "Дата", "Email", "Сумма", "ПО", "Количество" };
|
||||
|
||||
return _baseExcelBuilder
|
||||
.AddHeader("Requests за период", 0, 5)
|
||||
.AddParagraph($"c {dateStart.ToShortDateString()} по {dateFinish.ToShortDateString()}", 2)
|
||||
.AddTable(
|
||||
[10, 10, 10, 10, 10],
|
||||
[.. new List<string[]>() { tableHeader }
|
||||
.Union(data.SelectMany(x =>
|
||||
(new List<string[]>() {
|
||||
new string[] {
|
||||
x.RequestDate.ToShortDateString(),
|
||||
x.Email,
|
||||
x.Sum.ToString("N2"),
|
||||
"",
|
||||
""
|
||||
}
|
||||
})
|
||||
.Union(x.Softwares!.Select(y => new string[] {
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
y.SoftwareName,
|
||||
y.Count.ToString("N2")
|
||||
}))
|
||||
.ToArray()
|
||||
)
|
||||
.Union([[
|
||||
"Всего",
|
||||
"",
|
||||
data.Sum(x => x.Sum).ToString("N2"),
|
||||
"",
|
||||
""
|
||||
]]))
|
||||
])
|
||||
.Build();
|
||||
}
|
||||
|
||||
public Task<List<WorkerSalaryByPeriodDataModel>> GetDataSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
|
||||
{
|
||||
logger.LogInformation("Get data SalaryByPeriod from {dateStart} to { dateFinish}", dateStart, dateFinish);
|
||||
return GetDataBySalaryAsync(dateStart, dateFinish, ct);
|
||||
}
|
||||
|
||||
private async Task<List<WorkerSalaryByPeriodDataModel>> GetDataBySalaryAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
|
||||
{
|
||||
if (dateStart.IsDateNotOlder(dateFinish))
|
||||
{
|
||||
throw new IncorrectDatesException(dateStart, dateFinish);
|
||||
}
|
||||
return [.. (await _salaryStorageContract.GetListAsync(dateStart, dateFinish, ct)).GroupBy(x => x.WorkerFIO).Select(x => new
|
||||
WorkerSalaryByPeriodDataModel { WorkerFIO = x.Key, TotalSalary = x.Sum(y => y.Salary),
|
||||
FromPeriod = x.Min(y => y.SalaryDate), ToPeriod = x.Max(y => y.SalaryDate) }).OrderBy(x => x.WorkerFIO)];
|
||||
}
|
||||
|
||||
public async Task<Stream> CreateDocumentSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Create report SalaryByPeriod from {dateStart} to { dateFinish}", dateStart, dateFinish);
|
||||
var data = await GetDataBySalaryAsync(dateStart, dateFinish, ct) ?? throw new InvalidOperationException("No found data");
|
||||
return _basePdfBuilder.AddHeader("Зарплатная ведомость").AddParagraph($"за период с {dateStart.ToShortDateString()} по {dateFinish.ToShortDateString()}")
|
||||
.AddPieChart("Начисления", [.. data.Select(x => (x.WorkerFIO, x.TotalSalary))]).Build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace SmallSoftwareBusinessLogic.OfficePackage;
|
||||
|
||||
public abstract class BaseExcelBuilder
|
||||
{
|
||||
public abstract BaseExcelBuilder AddHeader(string header, int startIndex, int count);
|
||||
public abstract BaseExcelBuilder AddParagraph(string text, int columnIndex);
|
||||
public abstract BaseExcelBuilder AddTable(int[] columnsWidths, List<string[]> data);
|
||||
public abstract Stream Build();
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SmallSoftwareBusinessLogic.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,9 @@
|
||||
namespace SmallSoftwareBusinessLogic.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,76 @@
|
||||
using MigraDoc.DocumentObjectModel;
|
||||
using MigraDoc.DocumentObjectModel.Shapes.Charts;
|
||||
using MigraDoc.Rendering;
|
||||
using System.Text;
|
||||
|
||||
namespace SmallSoftwareBusinessLogic.OfficePackage;
|
||||
|
||||
|
||||
public class MigraDocPdfBuilder : BasePdfBuilder
|
||||
{
|
||||
private readonly Document _document;
|
||||
|
||||
public MigraDocPdfBuilder()
|
||||
{
|
||||
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
|
||||
_document = new Document();
|
||||
DefineStyles();
|
||||
}
|
||||
|
||||
public override BasePdfBuilder AddHeader(string header)
|
||||
{
|
||||
_document.AddSection().AddParagraph(header, "NormalBold");
|
||||
return this;
|
||||
}
|
||||
|
||||
public override BasePdfBuilder AddParagraph(string text)
|
||||
{
|
||||
_document.LastSection.AddParagraph(text, "Normal");
|
||||
return this;
|
||||
}
|
||||
|
||||
public override BasePdfBuilder AddPieChart(string title, List<(string Caption, double Value)> data)
|
||||
{
|
||||
if (data == null || data.Count == 0)
|
||||
{
|
||||
return this;
|
||||
}
|
||||
var chart = new Chart(ChartType.Pie2D);
|
||||
var series = chart.SeriesCollection.AddSeries();
|
||||
series.Add(data.Select(x => x.Value).ToArray());
|
||||
var xseries = chart.XValues.AddXSeries();
|
||||
xseries.Add(data.Select(x => x.Caption).ToArray());
|
||||
chart.DataLabel.Type = DataLabelType.Percent;
|
||||
chart.DataLabel.Position = DataLabelPosition.OutsideEnd;
|
||||
chart.Width = Unit.FromCentimeter(16);
|
||||
chart.Height = Unit.FromCentimeter(12);
|
||||
chart.TopArea.AddParagraph(title);
|
||||
chart.XAxis.MajorTickMark = TickMarkType.Outside;
|
||||
chart.YAxis.MajorTickMark = TickMarkType.Outside;
|
||||
chart.YAxis.HasMajorGridlines = true;
|
||||
chart.PlotArea.LineFormat.Width = 1;
|
||||
chart.PlotArea.LineFormat.Visible = true;
|
||||
chart.TopArea.AddLegend();
|
||||
_document.LastSection.Add(chart);
|
||||
return this;
|
||||
}
|
||||
|
||||
public override Stream Build()
|
||||
{
|
||||
var stream = new MemoryStream();
|
||||
var renderer = new PdfDocumentRenderer(true)
|
||||
{
|
||||
Document = _document
|
||||
};
|
||||
renderer.RenderDocument();
|
||||
renderer.PdfDocument.Save(stream);
|
||||
return stream;
|
||||
}
|
||||
|
||||
private void DefineStyles()
|
||||
{
|
||||
var headerStyle = _document.Styles.AddStyle("NormalBold", "Normal");
|
||||
headerStyle.Font.Bold = true;
|
||||
headerStyle.Font.Size = 14;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
using DocumentFormat.OpenXml.Packaging;
|
||||
using DocumentFormat.OpenXml.Spreadsheet;
|
||||
using DocumentFormat.OpenXml;
|
||||
|
||||
namespace SmallSoftwareBusinessLogic.OfficePackage;
|
||||
|
||||
public class OpenXmlExcelBuilder : BaseExcelBuilder
|
||||
{
|
||||
private readonly SheetData _sheetData;
|
||||
private readonly MergeCells _mergeCells;
|
||||
private readonly Columns _columns;
|
||||
private uint _rowIndex = 0;
|
||||
|
||||
public OpenXmlExcelBuilder()
|
||||
{
|
||||
_sheetData = new SheetData();
|
||||
_mergeCells = new MergeCells();
|
||||
_columns = new Columns();
|
||||
_rowIndex = 1;
|
||||
}
|
||||
|
||||
public override BaseExcelBuilder AddHeader(string header, int startIndex, int count)
|
||||
{
|
||||
CreateCell(startIndex, _rowIndex, header, StyleIndex.BoldTextWithBorders);
|
||||
for (int i = startIndex + 1; i < startIndex + count; ++i)
|
||||
{
|
||||
CreateCell(i, _rowIndex, "", StyleIndex.BoldTextWithBorders);
|
||||
}
|
||||
_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.BoldTextWithBorders);
|
||||
}
|
||||
_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.SimpleTextWithBorders);
|
||||
}
|
||||
_rowIndex++;
|
||||
}
|
||||
|
||||
for (var j = 0; j < data.Last().Length; ++j)
|
||||
{
|
||||
CreateCell(j, _rowIndex, data.Last()[j], StyleIndex.BoldTextWithBorders);
|
||||
}
|
||||
_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);
|
||||
|
||||
var fills = new Fills() { Count = 1 };
|
||||
fills.Append(new Fill
|
||||
{
|
||||
PatternFill = new PatternFill()
|
||||
{
|
||||
PatternType = new EnumValue<PatternValues>(PatternValues.None)
|
||||
}
|
||||
});
|
||||
workbookStylesPart.Stylesheet.Append(fills);
|
||||
|
||||
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 },
|
||||
DiagonalBorder = new DiagonalBorder()
|
||||
});
|
||||
workbookStylesPart.Stylesheet.Append(borders);
|
||||
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.Left,
|
||||
Vertical = VerticalAlignmentValues.Center,
|
||||
WrapText = true
|
||||
}
|
||||
});
|
||||
cellFormats.Append(new CellFormat
|
||||
{
|
||||
NumberFormatId = 0,
|
||||
FormatId = 0,
|
||||
FontId = 1,
|
||||
BorderId = 1,
|
||||
FillId = 0,
|
||||
Alignment = new Alignment()
|
||||
{
|
||||
Horizontal = HorizontalAlignmentValues.Left,
|
||||
Vertical = VerticalAlignmentValues.Center,
|
||||
WrapText = true
|
||||
}
|
||||
});
|
||||
workbookStylesPart.Stylesheet.Append(cellFormats);
|
||||
}
|
||||
|
||||
private enum StyleIndex
|
||||
{
|
||||
SimpleTextWithoutBorder = 0,
|
||||
SimpleTextWithBorders = 1,
|
||||
BoldTextWithoutBorders = 2,
|
||||
BoldTextWithBorders = 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,116 @@
|
||||
using DocumentFormat.OpenXml;
|
||||
using DocumentFormat.OpenXml.Packaging;
|
||||
using DocumentFormat.OpenXml.Wordprocessing;
|
||||
|
||||
namespace SmallSoftwareBusinessLogic.OfficePackage;
|
||||
|
||||
public class OpenXmlWordBuilder : BaseWordBuilder
|
||||
{
|
||||
private readonly Document _document;
|
||||
private readonly Body _body;
|
||||
|
||||
public OpenXmlWordBuilder()
|
||||
{
|
||||
;
|
||||
_document = new Document();
|
||||
_body = _document.AppendChild(new Body());
|
||||
}
|
||||
|
||||
public override BaseWordBuilder AddHeader(string header)
|
||||
{
|
||||
var paragraph = _body.AppendChild(new Paragraph());
|
||||
var run = paragraph.AppendChild(new Run());
|
||||
|
||||
var runProperties = new RunProperties();
|
||||
runProperties.AppendChild(new Bold());
|
||||
run.AppendChild(runProperties);
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,9 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="DocumentFormat.OpenXml" Version="3.3.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.2" />
|
||||
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
using SmallSoftwareContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
namespace SmallSoftwareContracts.AdapterContracts;
|
||||
|
||||
public interface IReportAdapter
|
||||
{
|
||||
Task<ReportOperationResponse> GetDataSoftwaresByManufacturerAsync(CancellationToken ct);
|
||||
Task<ReportOperationResponse> CreateDocumentSoftwaresByManufacturerAsync(CancellationToken ct);
|
||||
Task<ReportOperationResponse> GetDataRequestByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
Task<ReportOperationResponse> CreateDocumentRequestsByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
Task<ReportOperationResponse> GetDataSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
Task<ReportOperationResponse> CreateDocumentSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using SmallSoftwareContracts.DataModels;
|
||||
using SmallSoftwareContracts.Infrastructure;
|
||||
using SmallSoftwareContracts.ViewModels;
|
||||
|
||||
namespace SmallSoftwareContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class ReportOperationResponse : OperationResponse
|
||||
{
|
||||
public static ReportOperationResponse OK(List<HistoryOfSoftwareViewModel> data) => OK<ReportOperationResponse, List<HistoryOfSoftwareViewModel>>(data);
|
||||
public static ReportOperationResponse OK(List<RequestViewModel> data) => OK<ReportOperationResponse, List<RequestViewModel>>(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);
|
||||
public static ReportOperationResponse OK(List<WorkerSalaryByPeriodViewModel> data) => OK<ReportOperationResponse, List<WorkerSalaryByPeriodViewModel>>(data);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using SmallSoftwareContracts.DataModels;
|
||||
|
||||
namespace SmallSoftwareContracts.BusinessLogicsContracts;
|
||||
|
||||
public interface IReportContract
|
||||
{
|
||||
Task<List<HistoryOfSoftwareDataModel>> GetDataSoftwaresByHistoryAsync(CancellationToken ct);
|
||||
Task<List<RequestDataModel>> GetDataRequestByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
Task<Stream> CreateDocumentSoftwaresByHistoryAsync(CancellationToken ct);
|
||||
Task<Stream> CreateDocumentRequestsByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
Task<List<WorkerSalaryByPeriodDataModel>> GetDataSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
Task<Stream> CreateDocumentSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace SmallSoftwareContracts.DataModels;
|
||||
|
||||
public class HistoryOfSoftwareDataModel
|
||||
{
|
||||
public required string SoftwareName { get; set; }
|
||||
public required List<string> Histories { get; set; }
|
||||
public required List<string> Data { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace SmallSoftwareContracts.DataModels;
|
||||
|
||||
public class WorkerSalaryByPeriodDataModel
|
||||
{
|
||||
public required string WorkerFIO { get; set; }
|
||||
public double TotalSalary { get; set; }
|
||||
public DateTime FromPeriod { get; set; }
|
||||
public DateTime ToPeriod { get; set; }
|
||||
}
|
||||
|
||||
@@ -7,9 +7,12 @@ namespace SmallSoftwareContracts.Infrastructure;
|
||||
public class OperationResponse
|
||||
{
|
||||
protected HttpStatusCode StatusCode { get; set; }
|
||||
|
||||
protected object? Result { get; set; }
|
||||
public IActionResult GetResponse(HttpRequest request, HttpResponse
|
||||
response)
|
||||
|
||||
protected string? FileName { get; set; }
|
||||
|
||||
public IActionResult GetResponse(HttpRequest request, HttpResponse response)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
ArgumentNullException.ThrowIfNull(response);
|
||||
@@ -18,31 +21,46 @@ public class OperationResponse
|
||||
{
|
||||
return new StatusCodeResult((int)StatusCode);
|
||||
}
|
||||
if (Result is Stream stream)
|
||||
{
|
||||
return new FileStreamResult(stream, "application/octetstream")
|
||||
{
|
||||
FileDownloadName = FileName
|
||||
};
|
||||
}
|
||||
return new ObjectResult(Result);
|
||||
}
|
||||
protected static TResult OK<TResult, TData>(TData data) where TResult :
|
||||
OperationResponse, new() => new()
|
||||
|
||||
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
|
||||
Result = data,
|
||||
FileName = fileName
|
||||
};
|
||||
|
||||
protected static TResult NoContent<TResult>() where TResult :
|
||||
OperationResponse, new() => new() { StatusCode = HttpStatusCode.NoContent };
|
||||
protected static TResult BadRequest<TResult>(string? errorMessage = null)
|
||||
where TResult : OperationResponse, new() => new()
|
||||
{
|
||||
StatusCode = HttpStatusCode.BadRequest,
|
||||
StatusCode =
|
||||
HttpStatusCode.BadRequest,
|
||||
Result = errorMessage
|
||||
};
|
||||
protected static TResult NotFound<TResult>(string? errorMessage = null)
|
||||
where TResult : OperationResponse, new() => new()
|
||||
{
|
||||
StatusCode = HttpStatusCode.NotFound,
|
||||
StatusCode =
|
||||
HttpStatusCode.NotFound,
|
||||
Result = errorMessage
|
||||
};
|
||||
protected static TResult InternalServerError<TResult>(string? errorMessage = null) where TResult : OperationResponse, new() => new()
|
||||
protected static TResult InternalServerError<TResult>(string? errorMessage
|
||||
= null) where TResult : OperationResponse, new() => new()
|
||||
{
|
||||
StatusCode = HttpStatusCode.InternalServerError,
|
||||
StatusCode =
|
||||
HttpStatusCode.InternalServerError,
|
||||
Result = errorMessage
|
||||
};
|
||||
}
|
||||
@@ -4,6 +4,8 @@ namespace SmallSoftwareContracts.StoragesContracts;
|
||||
|
||||
public interface IRequestStorageContract
|
||||
{
|
||||
Task<List<RequestDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct);
|
||||
|
||||
List<RequestDataModel> GetList(DateTime? startDate = null,
|
||||
DateTime? endDate = null, string? workerId = null, string? softwareId = null);
|
||||
RequestDataModel? GetElementById(string id);
|
||||
|
||||
@@ -6,5 +6,6 @@ public interface ISalaryStorageContract
|
||||
{
|
||||
List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? workerId = null);
|
||||
void AddElement(SalaryDataModel salaryDataModel);
|
||||
Task<List<SalaryDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct);
|
||||
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ namespace SmallSoftwareContracts.StoragesContracts;
|
||||
|
||||
public interface ISoftwareStorageContract
|
||||
{
|
||||
Task<List<SoftwareHistoryDataModel>> GetListAsync(CancellationToken ct);
|
||||
List<SoftwareDataModel> GetList(bool onlyActive = true, string? manufacturerId = null);
|
||||
List<SoftwareHistoryDataModel> GetHistoryBySoftwareId(string softwareId);
|
||||
SoftwareDataModel? GetElementById(string id);
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace SmallSoftwareContracts.ViewModels;
|
||||
|
||||
public class HistoryOfSoftwareViewModel
|
||||
{
|
||||
public required string SoftwareName { get; set; }
|
||||
public required List<string> Histories { get; set; }
|
||||
public required List<string> Data { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace SmallSoftwareContracts.ViewModels;
|
||||
|
||||
public class WorkerSalaryByPeriodViewModel
|
||||
{
|
||||
public required string WorkerFIO { get; set; }
|
||||
public double TotalSalary { get; set; }
|
||||
public DateTime FromPeriod { get; set; }
|
||||
public DateTime ToPeriod { get; set; }
|
||||
}
|
||||
@@ -115,4 +115,20 @@ internal class RequestStorageContract : IRequestStorageContract
|
||||
.Include(x => x.InstallationRequests)!
|
||||
.ThenInclude(x => x.Software)
|
||||
.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
public async Task<List<RequestDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return [.. await _dbContext.Requests
|
||||
.Include(x => x.InstallationRequests)!.ThenInclude(x => x.Software)
|
||||
.Where(x => x.RequestDate >= startDate && x.RequestDate < endDate).Select(x => _mapper.Map<RequestDataModel>(x)).ToListAsync(ct)];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -53,4 +53,17 @@ internal class SalaryStorageContract : ISalaryStorageContract
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<List<SalaryDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return [.. await _dbContext.Salaries.Include(x => x.Worker).Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate).Select(x => _mapper.Map<SalaryDataModel>(x)).ToListAsync(ct)];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,8 +25,24 @@ internal class SoftwareStorageContract : ISoftwareStorageContract
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
public List<SoftwareDataModel> GetList(bool onlyActive = true, string?
|
||||
manufacturerId = null)
|
||||
|
||||
public async Task<List<SoftwareHistoryDataModel>> GetListAsync(CancellationToken ct)
|
||||
{
|
||||
|
||||
try
|
||||
{
|
||||
return [.. await _dbContext.SoftwareHistories.Include(x => x.Software).Select(x => _mapper.Map<SoftwareHistoryDataModel>(x)).ToListAsync(ct)];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
public List<SoftwareDataModel> GetList(bool onlyActive = true, string? manufacturerId = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
||||
@@ -0,0 +1,509 @@
|
||||
using DocumentFormat.OpenXml.Wordprocessing;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
using SmallSoftwareBusinessLogic.Implementations;
|
||||
using SmallSoftwareBusinessLogic.OfficePackage;
|
||||
using SmallSoftwareContracts.DataModels;
|
||||
using SmallSoftwareContracts.Enums;
|
||||
using SmallSoftwareContracts.Exceptions;
|
||||
using SmallSoftwareContracts.StoragesContracts;
|
||||
|
||||
namespace SmallSoftwareTests.BusinessLogicsContractsTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class ReportContractTests
|
||||
{
|
||||
private ReportContract _reportContract;
|
||||
private Mock<ISoftwareStorageContract> _softwareStorageContract;
|
||||
private Mock<IRequestStorageContract> _requestStorageContract;
|
||||
private Mock<ISalaryStorageContract> _salaryStorageContract;
|
||||
private Mock<BaseWordBuilder> _baseWordBuilder;
|
||||
private Mock<BaseExcelBuilder> _baseExcelBuilder;
|
||||
private Mock<BasePdfBuilder> _basePdfBuilder;
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
_softwareStorageContract = new Mock<ISoftwareStorageContract>();
|
||||
_requestStorageContract = new Mock<IRequestStorageContract>();
|
||||
_salaryStorageContract = new Mock<ISalaryStorageContract>();
|
||||
_baseWordBuilder = new Mock<BaseWordBuilder>();
|
||||
_baseExcelBuilder = new Mock<BaseExcelBuilder>();
|
||||
_basePdfBuilder = new Mock<BasePdfBuilder>();
|
||||
_reportContract = new ReportContract(_softwareStorageContract.Object, _requestStorageContract.Object, _salaryStorageContract.Object, _baseWordBuilder.Object, _baseExcelBuilder.Object, _basePdfBuilder.Object, new Mock<ILogger>().Object);
|
||||
}
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_softwareStorageContract.Reset();
|
||||
_requestStorageContract.Reset();
|
||||
_salaryStorageContract.Reset();
|
||||
}
|
||||
[Test]
|
||||
public async Task GetDataSoftwaresByManufacturer_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var manufacturer1 = new ManufacturerDataModel(Guid.NewGuid().ToString(), "name1");
|
||||
var manufacturer2 = new ManufacturerDataModel(Guid.NewGuid().ToString(), "name2");
|
||||
var softwareId1 = Guid.NewGuid().ToString();
|
||||
var softwareId2 = Guid.NewGuid().ToString();
|
||||
|
||||
var software1 = new SoftwareDataModel(softwareId1, "name1", SoftwareType.AudioDriver, manufacturer1.Id, 10, false);
|
||||
var software2 = new SoftwareDataModel(softwareId2, "name2", SoftwareType.AudioDriver, manufacturer2.Id, 10, false);
|
||||
|
||||
_softwareStorageContract.Setup(x => x.GetListAsync(It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.FromResult(new List<SoftwareHistoryDataModel>()
|
||||
{
|
||||
new(softwareId1, 22, DateTime.UtcNow, software1),
|
||||
new(softwareId2, 21, DateTime.UtcNow, software2),
|
||||
new(softwareId1, 33, DateTime.UtcNow, software1),
|
||||
new(softwareId1, 32, DateTime.UtcNow, software1),
|
||||
new(softwareId2, 65, DateTime.UtcNow, software2)
|
||||
}));
|
||||
|
||||
//Act
|
||||
var data = await _reportContract.GetDataSoftwaresByHistoryAsync(CancellationToken.None);
|
||||
|
||||
//Assert
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data.First(x => x.SoftwareName == software1.SoftwareName).Histories, Has.Count.EqualTo(3));
|
||||
Assert.That(data.First(x => x.SoftwareName == software2.SoftwareName).Histories, Has.Count.EqualTo(2));
|
||||
});
|
||||
_softwareStorageContract.Verify(x => x.GetListAsync(It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
[Test]
|
||||
public async Task GetDataSoftwaresByHistory_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
_softwareStorageContract.Setup(x =>
|
||||
x.GetListAsync(It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.FromResult(new List<SoftwareHistoryDataModel>()));
|
||||
//Act
|
||||
var data = await _reportContract.GetDataSoftwaresByHistoryAsync(CancellationToken.None);
|
||||
//Assert
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
_softwareStorageContract.Verify(x =>
|
||||
x.GetListAsync(It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
[Test]
|
||||
public void GetDataSoftwaresByHistory_WhenStorageThrowError_ShouldFail_Test()
|
||||
{
|
||||
//Arrange
|
||||
_softwareStorageContract.Setup(x => x.GetListAsync(It.IsAny<CancellationToken>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(async () => await _reportContract.GetDataSoftwaresByHistoryAsync(CancellationToken.None), Throws.TypeOf<StorageException>());
|
||||
_softwareStorageContract.Verify(x => x.GetListAsync(It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CreateDocumentSoftwaresByHistory_ShouldeSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var manufacturer1 = new
|
||||
ManufacturerDataModel(Guid.NewGuid().ToString(), "name1");
|
||||
var manufacturer2 = new
|
||||
ManufacturerDataModel(Guid.NewGuid().ToString(), "name2");
|
||||
var softwareId1 = Guid.NewGuid().ToString();
|
||||
var softwareId2 = Guid.NewGuid().ToString();
|
||||
|
||||
var software1 = new SoftwareDataModel(softwareId1, "name1", SoftwareType.AudioDriver, manufacturer1.Id, 10, false);
|
||||
var software2 = new SoftwareDataModel(softwareId2, "name2", SoftwareType.AudioDriver, manufacturer2.Id, 10, false);
|
||||
|
||||
var histories = new List<SoftwareHistoryDataModel>()
|
||||
{
|
||||
new(softwareId1, 22, DateTime.UtcNow, software1),
|
||||
new(softwareId1, 33, DateTime.UtcNow, software1),
|
||||
new(softwareId1, 32, DateTime.UtcNow, software1),
|
||||
new(softwareId2, 21, DateTime.UtcNow, software2),
|
||||
new(softwareId2, 65, DateTime.UtcNow, software2)
|
||||
};
|
||||
|
||||
_softwareStorageContract.Setup(x => x.GetListAsync(It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.FromResult(histories));
|
||||
|
||||
_baseWordBuilder.Setup(x => x.AddHeader(It.IsAny<string>())).Returns(_baseWordBuilder.Object);
|
||||
_baseWordBuilder.Setup(x => x.AddParagraph(It.IsAny<string>())).Returns(_baseWordBuilder.Object);
|
||||
|
||||
var countRows = 0;
|
||||
string[] firstRow = [];
|
||||
string[] secondRow = [];
|
||||
|
||||
_baseWordBuilder.Setup(x => x.AddTable(It.IsAny<int[]>(),
|
||||
It.IsAny<List<string[]>>()))
|
||||
.Callback((int[] widths, List<string[]> data) =>
|
||||
{
|
||||
countRows = data.Count;
|
||||
if (data.Count > 0) firstRow = data[0];
|
||||
if (data.Count > 1) secondRow = data[1];
|
||||
})
|
||||
.Returns(_baseWordBuilder.Object);
|
||||
|
||||
// Act
|
||||
var data = await _reportContract.CreateDocumentSoftwaresByHistoryAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
_softwareStorageContract.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(8));
|
||||
|
||||
Assert.That(firstRow, Has.Length.EqualTo(3));
|
||||
Assert.That(secondRow, Has.Length.EqualTo(3));
|
||||
|
||||
Assert.That(firstRow[0], Is.EqualTo("Название ПО"));
|
||||
Assert.That(firstRow[1], Is.EqualTo("Старая цена"));
|
||||
|
||||
Assert.That(secondRow[0], Is.EqualTo("name1"));
|
||||
Assert.That(secondRow[1], Is.EqualTo(""));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetDataByRequestsByPeriod_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
_requestStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(),
|
||||
It.IsAny<DateTime>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(new List<RequestDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "test@mail.ru", false, [new InstallationRequestDataModel("", Guid.NewGuid().ToString(), 10, 10)], DateTime.UtcNow),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "test@mail.ru", false, [new InstallationRequestDataModel("", Guid.NewGuid().ToString(), 10, 10)], DateTime.UtcNow)
|
||||
}));
|
||||
//Act
|
||||
var data = await
|
||||
_reportContract.GetDataRequestByPeriodAsync(DateTime.UtcNow.AddDays(-1),
|
||||
DateTime.UtcNow, CancellationToken.None);
|
||||
//Assert
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
_requestStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(),
|
||||
It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
[Test]
|
||||
public async Task GetDataByRequestsByPeriod_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
_requestStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(),
|
||||
It.IsAny<DateTime>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(new
|
||||
List<RequestDataModel>()));
|
||||
//Act
|
||||
var data = await
|
||||
_reportContract.GetDataRequestByPeriodAsync(DateTime.UtcNow.AddDays(-1),
|
||||
DateTime.UtcNow, CancellationToken.None);
|
||||
//Assert
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
_requestStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(),
|
||||
It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
[Test]
|
||||
public void GetDataByRequestsByPeriod_WhenIncorrectDates_ShouldFail_Test()
|
||||
{
|
||||
//Arrange
|
||||
var date = DateTime.UtcNow;
|
||||
//Act&Assert
|
||||
Assert.That(async () => await
|
||||
_reportContract.GetDataRequestByPeriodAsync(date, date, CancellationToken.None),
|
||||
Throws.TypeOf<IncorrectDatesException>());
|
||||
Assert.That(async () => await
|
||||
_reportContract.GetDataRequestByPeriodAsync(date, DateTime.UtcNow.AddDays(-1),
|
||||
CancellationToken.None), Throws.TypeOf<IncorrectDatesException>());
|
||||
}
|
||||
[Test]
|
||||
public void GetDataByRequestsByPeriod_WhenStorageThrowError_ShouldFail_Test()
|
||||
{
|
||||
//Arrange
|
||||
_requestStorageContract.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.GetDataRequestByPeriodAsync(DateTime.UtcNow.AddDays(-1),
|
||||
DateTime.UtcNow, CancellationToken.None), Throws.TypeOf<StorageException>());
|
||||
_requestStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(),
|
||||
It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetDataSalaryByPeriod_ShouldSuccess_Test()
|
||||
{
|
||||
// Arrange
|
||||
var startDate = DateTime.UtcNow.AddDays(-20);
|
||||
var endDate = DateTime.UtcNow.AddDays(5);
|
||||
|
||||
var worker1 = new WorkerDataModel(
|
||||
Guid.NewGuid().ToString(),
|
||||
"fio 1",
|
||||
Guid.NewGuid().ToString(),
|
||||
DateTime.UtcNow.AddYears(-20),
|
||||
DateTime.UtcNow.AddDays(-3));
|
||||
|
||||
var worker2 = new WorkerDataModel(
|
||||
Guid.NewGuid().ToString(),
|
||||
"fio 2",
|
||||
Guid.NewGuid().ToString(),
|
||||
DateTime.UtcNow.AddYears(-20),
|
||||
DateTime.UtcNow.AddDays(-3));
|
||||
|
||||
_salaryStorageContract.Setup(x =>
|
||||
x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new List<SalaryDataModel>()
|
||||
{
|
||||
new(worker1.Id, DateTime.UtcNow.AddDays(-10), 100),
|
||||
new(worker1.Id, endDate, 1000),
|
||||
new(worker1.Id, startDate, 1000),
|
||||
new(worker2.Id, DateTime.UtcNow.AddDays(-10), 100),
|
||||
new(worker2.Id, DateTime.UtcNow.AddDays(-5), 200)
|
||||
});
|
||||
|
||||
// Act
|
||||
var data = await _reportContract.GetDataSalaryByPeriodAsync(
|
||||
DateTime.UtcNow.AddDays(-1),
|
||||
DateTime.UtcNow,
|
||||
CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(1));
|
||||
|
||||
var totalSalary = data.First();
|
||||
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(totalSalary, Is.Not.Null);
|
||||
Assert.That(totalSalary.TotalSalary, Is.EqualTo(2400));
|
||||
});
|
||||
|
||||
_salaryStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(),
|
||||
It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetDataSalaryByPeriod_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
// Arrange
|
||||
_salaryStorageContract.Setup(x =>
|
||||
x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new List<SalaryDataModel>());
|
||||
|
||||
// Act
|
||||
var data = await _reportContract.GetDataSalaryByPeriodAsync(
|
||||
DateTime.UtcNow.AddDays(-1),
|
||||
DateTime.UtcNow,
|
||||
CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
|
||||
_salaryStorageContract.Verify(x =>
|
||||
x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetDataSalaryByPeriod_WhenIncorrectDates_ShouldFail_Test()
|
||||
{
|
||||
// Arrange
|
||||
var date = DateTime.UtcNow;
|
||||
|
||||
// Act & Assert
|
||||
Assert.That(async () => await _reportContract.GetDataSalaryByPeriodAsync(
|
||||
date, date, CancellationToken.None),
|
||||
Throws.TypeOf<IncorrectDatesException>());
|
||||
|
||||
Assert.That(async () => await _reportContract.GetDataSalaryByPeriodAsync(
|
||||
date, DateTime.UtcNow.AddDays(-1), CancellationToken.None),
|
||||
Throws.TypeOf<IncorrectDatesException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetDataBySalaryByPeriod_WhenStorageThrowError_ShouldFail_Test()
|
||||
{
|
||||
// Arrange
|
||||
_salaryStorageContract.Setup(x =>
|
||||
x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()))
|
||||
.ThrowsAsync(new StorageException(new InvalidOperationException()));
|
||||
|
||||
// Act & Assert
|
||||
Assert.That(async () => await _reportContract.GetDataSalaryByPeriodAsync(
|
||||
DateTime.UtcNow.AddDays(-1),
|
||||
DateTime.UtcNow,
|
||||
CancellationToken.None),
|
||||
Throws.TypeOf<StorageException>());
|
||||
|
||||
_salaryStorageContract.Verify(x =>
|
||||
x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CreateDocumentRequestsByPeriod_ShouldSuccess_Test()
|
||||
{
|
||||
// Arrange
|
||||
var manufacturer1 = new ManufacturerDataModel(Guid.NewGuid().ToString(), "name1");
|
||||
var software1 = new SoftwareDataModel(Guid.NewGuid().ToString(), "name1", SoftwareType.Windows, manufacturer1.Id, 10, false);
|
||||
var software2 = new SoftwareDataModel(Guid.NewGuid().ToString(), "name2", SoftwareType.Windows, manufacturer1.Id, 10, false);
|
||||
_requestStorageContract.Setup(x => x.GetListAsync(
|
||||
It.IsAny<DateTime>(),
|
||||
It.IsAny<DateTime>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new List<RequestDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(),
|
||||
Guid.NewGuid().ToString(),
|
||||
"test@mail.ru",
|
||||
false,
|
||||
new List<InstallationRequestDataModel>() {
|
||||
new("", software1.Id, 10, 10, software1),
|
||||
new("", software2.Id, 10, 10, software2)
|
||||
}, DateTime.UtcNow.AddDays(-1)),
|
||||
new(Guid.NewGuid().ToString(),
|
||||
Guid.NewGuid().ToString(),
|
||||
"qwerty@gmail.ru",
|
||||
false,
|
||||
new List<InstallationRequestDataModel>()
|
||||
{
|
||||
new("", software2.Id, 10, 10, software2)
|
||||
}, DateTime.UtcNow.AddDays(-1))
|
||||
});
|
||||
|
||||
_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[] headerRow = Array.Empty<string>();
|
||||
string[] firstDataRow = Array.Empty<string>();
|
||||
string[] firstSoftwareRow = Array.Empty<string>();
|
||||
|
||||
_baseExcelBuilder.Setup(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>()))
|
||||
.Callback((int[] widths, List<string[]> data) =>
|
||||
{
|
||||
countRows = data.Count;
|
||||
headerRow = data[0];
|
||||
firstDataRow = data[1];
|
||||
firstSoftwareRow = data[2];
|
||||
})
|
||||
.Returns(_baseExcelBuilder.Object);
|
||||
|
||||
// Act
|
||||
var result = await _reportContract.CreateDocumentRequestsByPeriodAsync(
|
||||
DateTime.UtcNow.AddDays(-1),
|
||||
DateTime.UtcNow,
|
||||
CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(countRows, Is.EqualTo(7));
|
||||
Assert.That(headerRow, Is.Not.Empty);
|
||||
Assert.That(firstDataRow, Is.Not.Empty);
|
||||
Assert.That(firstSoftwareRow, Is.Not.Empty);
|
||||
});
|
||||
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(headerRow[0], Is.EqualTo("Дата"));
|
||||
Assert.That(headerRow[1], Is.EqualTo("Email"));
|
||||
Assert.That(headerRow[2], Is.EqualTo("Сумма"));
|
||||
Assert.That(headerRow[3], Is.EqualTo("ПО"));
|
||||
Assert.That(headerRow[4], Is.EqualTo("Количество"));
|
||||
|
||||
Assert.That(firstDataRow[0], Is.EqualTo(DateTime.UtcNow.ToString("dd.MM.yyyy")));
|
||||
Assert.That(firstDataRow[1], Is.EqualTo("test@mail.ru"));
|
||||
Assert.That(firstDataRow[2], Is.EqualTo(200.ToString("N2")));
|
||||
Assert.That(firstDataRow[3], Is.Empty);
|
||||
Assert.That(firstDataRow[4], Is.Empty);
|
||||
|
||||
Assert.That(firstSoftwareRow[0], Is.Empty);
|
||||
Assert.That(firstSoftwareRow[1], Is.Empty);
|
||||
Assert.That(firstSoftwareRow[2], Is.Empty);
|
||||
Assert.That(firstSoftwareRow[3], Is.EqualTo(software1.SoftwareName));
|
||||
Assert.That(firstSoftwareRow[4], Is.EqualTo(10.ToString("N2")));
|
||||
});
|
||||
_requestStorageContract.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 CreateDocumentSalaryByPeriod_ShouldeSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var startDate = DateTime.UtcNow.AddDays(-20);
|
||||
var endDate = DateTime.UtcNow.AddDays(5);
|
||||
var worker1 = new WorkerDataModel(Guid.NewGuid().ToString(), "fio 1", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-20), DateTime.UtcNow.AddDays(-3));
|
||||
var worker2 = new WorkerDataModel(Guid.NewGuid().ToString(), "fio 2", Guid.NewGuid().ToString(), DateTime.UtcNow.AddYears(-20), DateTime.UtcNow.AddDays(-3));
|
||||
|
||||
_salaryStorageContract.Setup(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(),
|
||||
It.IsAny<CancellationToken>())).Returns(Task.FromResult(new List<SalaryDataModel>()
|
||||
{
|
||||
new(worker1.Id, DateTime.UtcNow.AddDays(-10), 100, worker1),
|
||||
new(worker1.Id, endDate, 1000, worker1),
|
||||
new(worker1.Id, startDate, 1000, worker1),
|
||||
new(worker2.Id, DateTime.UtcNow.AddDays(-10), 100, worker2),
|
||||
new(worker2.Id, DateTime.UtcNow.AddDays(-5), 200, worker2)
|
||||
}));
|
||||
|
||||
_basePdfBuilder.Setup(x => x.AddHeader(It.IsAny<string>())).Returns(_basePdfBuilder.Object);
|
||||
_basePdfBuilder.Setup(x => x.AddParagraph(It.IsAny<string>())).Returns(_basePdfBuilder.Object);
|
||||
var countRows = 0;
|
||||
(string, double) firstRow = default;
|
||||
(string, double) secondRow = default;
|
||||
_basePdfBuilder.Setup(x => x.AddPieChart(It.IsAny<string>(), It.IsAny<List<(string, double)>>())).Callback((string header, List<(string, double)> data) =>
|
||||
{
|
||||
countRows = data.Count;
|
||||
firstRow = data[0];
|
||||
secondRow = data[1];
|
||||
}).Returns(_basePdfBuilder.Object);
|
||||
|
||||
//Act
|
||||
var data = await _reportContract.CreateDocumentSalaryByPeriodAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, CancellationToken.None);
|
||||
|
||||
//Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(countRows, Is.EqualTo(2));
|
||||
Assert.That(firstRow, Is.Not.EqualTo(default));
|
||||
Assert.That(secondRow, Is.Not.EqualTo(default));
|
||||
});
|
||||
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(firstRow.Item1, Is.EqualTo(worker1.FIO));
|
||||
Assert.That(firstRow.Item2, Is.EqualTo(2100));
|
||||
Assert.That(secondRow.Item1, Is.EqualTo(worker2.FIO));
|
||||
Assert.That(secondRow.Item2, Is.EqualTo(300));
|
||||
});
|
||||
|
||||
_salaryStorageContract.Verify(x => x.GetListAsync(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
_basePdfBuilder.Verify(x => x.AddHeader(It.IsAny<string>()), Times.Once);
|
||||
_basePdfBuilder.Verify(x => x.AddParagraph(It.IsAny<string>()), Times.Once);
|
||||
_basePdfBuilder.Verify(x => x.AddPieChart(It.IsAny<string>(), It.IsAny<List<(string, double)>>()), Times.Once);
|
||||
_basePdfBuilder.Verify(x => x.Build(), Times.Once);
|
||||
}
|
||||
}
|
||||
@@ -62,6 +62,35 @@ internal class RequestStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(4));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Try_GetListAsync_ByPeriod_Test()
|
||||
{
|
||||
SmallSoftwareDbContext.InsertRequestToDatabaseAndReturn
|
||||
(_worker.Id, requestDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-3), softwares: [(_software.Id, 1, 1.2)]);
|
||||
SmallSoftwareDbContext.InsertRequestToDatabaseAndReturn
|
||||
(_worker.Id, requestDate: DateTime.UtcNow.AddDays(-1).AddMinutes(3), softwares:[(_software.Id, 1, 1.2)]);
|
||||
SmallSoftwareDbContext.InsertRequestToDatabaseAndReturn
|
||||
(_worker.Id, requestDate: DateTime.UtcNow.AddDays(1).AddMinutes(-3), softwares: [(_software.Id, 1,1.2)]);
|
||||
SmallSoftwareDbContext.InsertRequestToDatabaseAndReturn
|
||||
(_worker.Id, requestDate: DateTime.UtcNow.AddDays(1).AddMinutes(3), softwares: [(_software.Id, 1, 1.2)]);
|
||||
var list = await _requesttStorageContract.GetListAsync(startDate:
|
||||
DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1),
|
||||
CancellationToken.None);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
}
|
||||
[Test]
|
||||
public async Task Try_GetListAsync_WhenNoRecords_Test()
|
||||
{
|
||||
var list = await _requesttStorageContract.GetListAsync(startDate:
|
||||
DateTime.UtcNow.AddDays(-1), endDate: DateTime.UtcNow.AddDays(1),
|
||||
CancellationToken.None);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByWorkerId_Test()
|
||||
{
|
||||
|
||||
@@ -114,6 +114,34 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(list.All(x => x.WorkerId == _worker.Id));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Try_GetListAsync_ByPeriod_Test()
|
||||
{
|
||||
SmallSoftwareDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
SmallSoftwareDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-5));
|
||||
SmallSoftwareDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
SmallSoftwareDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
SmallSoftwareDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(5));
|
||||
SmallSoftwareDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
var list = await _salaryStorageContract.GetListAsync(DateTime.UtcNow.AddDays(-1),
|
||||
DateTime.UtcNow.AddDays(1), CancellationToken.None);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() => {
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Try_GetListAsync_WhenNoRecords_Test()
|
||||
{
|
||||
var list = await _salaryStorageContract.GetListAsync(DateTime.UtcNow.AddDays(-10),
|
||||
DateTime.UtcNow.AddDays(10), CancellationToken.None);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
|
||||
@@ -28,6 +28,33 @@ internal class SoftwareStorageContractTests : BaseStorageContractTest
|
||||
SmallSoftwareDbContext.RemoveManufacturersFromDatabase();
|
||||
}
|
||||
|
||||
|
||||
[Test]
|
||||
public async Task Try_GetListAsync_WhenHaveRecords_Test()
|
||||
{
|
||||
var manufacturer1 = new ManufacturerDataModel(Guid.NewGuid().ToString(), "name1");
|
||||
|
||||
var software1 = new SoftwareDataModel(Guid.NewGuid().ToString(), "name1", SoftwareType.AudioDriver, manufacturer1.Id, 10, false);
|
||||
|
||||
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, software1.Id, softwareName: "name 1");
|
||||
|
||||
SmallSoftwareDbContext.InsertSoftwareHistoryToDatabaseAndReturn(software1.Id, 11);
|
||||
SmallSoftwareDbContext.InsertSoftwareHistoryToDatabaseAndReturn(software1.Id, 12);
|
||||
SmallSoftwareDbContext.InsertSoftwareHistoryToDatabaseAndReturn(software1.Id, 13);
|
||||
var list = await _softwareStorageContract.GetListAsync(CancellationToken.None);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Try_GetListAsync_WhenNoRecords_Test()
|
||||
{
|
||||
var list = await _softwareStorageContract.GetListAsync(CancellationToken.None);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,336 @@
|
||||
using SmallSoftwareContracts.DataModels;
|
||||
using SmallSoftwareContracts.Enums;
|
||||
using SmallSoftwareContracts.ViewModels;
|
||||
using SmallSoftwareDatabase.Models;
|
||||
using SmallSoftwareTests.Infrastructure;
|
||||
using System.Net;
|
||||
|
||||
namespace SmallSoftwareTests.WebApiControllersApi;
|
||||
|
||||
[TestFixture]
|
||||
internal class ReportControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
|
||||
SmallSoftwareDbContext.RemoveRequestsFromDatabase();
|
||||
SmallSoftwareDbContext.RemoveWorkersFromDatabase();
|
||||
SmallSoftwareDbContext.RemovePostsFromDatabase();
|
||||
SmallSoftwareDbContext.RemoveSoftwaresFromDatabase();
|
||||
SmallSoftwareDbContext.RemoveManufacturersFromDatabase();
|
||||
}
|
||||
[Test]
|
||||
public async Task GetSoftwares_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
// Arrange
|
||||
var manufacturer1 = new ManufacturerDataModel(Guid.NewGuid().ToString(), "name1");
|
||||
var manufacturer2 = new ManufacturerDataModel(Guid.NewGuid().ToString(), "name2");
|
||||
SmallSoftwareDbContext.InsertManufacturerToDatabaseAndReturn(manufacturer1.Id, manufacturerName: manufacturer1.ManufacturerName);
|
||||
SmallSoftwareDbContext.InsertManufacturerToDatabaseAndReturn(manufacturer2.Id, manufacturerName: manufacturer2.ManufacturerName);
|
||||
|
||||
var software1 = new SoftwareDataModel(Guid.NewGuid().ToString(), "soft1", SoftwareType.AudioDriver, manufacturer1.Id, 10, false);
|
||||
var software2 = new SoftwareDataModel(Guid.NewGuid().ToString(), "soft2", SoftwareType.AudioDriver, manufacturer2.Id, 10, false);
|
||||
|
||||
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(manufacturer1.Id, software1.Id, softwareName: software1.SoftwareName);
|
||||
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(manufacturer2.Id, software2.Id, softwareName: software2.SoftwareName);
|
||||
|
||||
SmallSoftwareDbContext.InsertSoftwareHistoryToDatabaseAndReturn(software1.Id, 11);
|
||||
SmallSoftwareDbContext.InsertSoftwareHistoryToDatabaseAndReturn(software1.Id, 12);
|
||||
SmallSoftwareDbContext.InsertSoftwareHistoryToDatabaseAndReturn(software1.Id, 13);
|
||||
|
||||
SmallSoftwareDbContext.InsertSoftwareHistoryToDatabaseAndReturn(software2.Id, 11);
|
||||
SmallSoftwareDbContext.InsertSoftwareHistoryToDatabaseAndReturn(software2.Id, 12);
|
||||
|
||||
// Act
|
||||
var response = await HttpClient.GetAsync("/api/report/getsoftwares");
|
||||
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<HistoryOfSoftwareViewModel>>(response);
|
||||
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
Assert.That(data.First(x => x.SoftwareName == software1.SoftwareName).Histories, Has.Count.EqualTo(3));
|
||||
Assert.That(data.First(x => x.SoftwareName == software2.SoftwareName).Histories, Has.Count.EqualTo(2));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetRequests_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var worker = SmallSoftwareDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
var manufacturerId = SmallSoftwareDbContext.InsertManufacturerToDatabaseAndReturn();
|
||||
var software1 = SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(manufacturerId.Id, softwareName: "name 1");
|
||||
var software2 = SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(manufacturerId.Id, softwareName: "name 2");
|
||||
SmallSoftwareDbContext.InsertRequestToDatabaseAndReturn(worker.Id, softwares: [(software1.Id, 10, 1.1), (software2.Id, 10, 1.1)]);
|
||||
SmallSoftwareDbContext.InsertRequestToDatabaseAndReturn(worker.Id, softwares: [(software1.Id, 10, 1.1)]);
|
||||
//Act
|
||||
var response = await
|
||||
HttpClient.GetAsync($"/api/report/getrequests?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<RequestViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
});
|
||||
}
|
||||
[Test]
|
||||
public async Task GetRequests_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
//Act
|
||||
var response = await
|
||||
HttpClient.GetAsync($"/api/report/getrequests?fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
//Assert
|
||||
Assert.That(response.StatusCode,
|
||||
Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetSalary_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
// Arrange
|
||||
var post = SmallSoftwareDbContext.InsertPostToDatabaseAndReturn();
|
||||
|
||||
var worker1 = SmallSoftwareDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 1", postId: post.PostId).AddPost(post);
|
||||
var worker2 = SmallSoftwareDbContext.InsertWorkerToDatabaseAndReturn(fio: "fio 2", postId: post.PostId).AddPost(post);
|
||||
|
||||
SmallSoftwareDbContext.InsertSalaryToDatabaseAndReturn(
|
||||
worker1.Id,
|
||||
workerSalary: 100,
|
||||
salaryDate: DateTime.UtcNow.AddDays(-10));
|
||||
|
||||
SmallSoftwareDbContext.InsertSalaryToDatabaseAndReturn(
|
||||
worker1.Id,
|
||||
workerSalary: 1000,
|
||||
salaryDate: DateTime.UtcNow.AddDays(-5));
|
||||
|
||||
SmallSoftwareDbContext.InsertSalaryToDatabaseAndReturn(
|
||||
worker1.Id,
|
||||
workerSalary: 200,
|
||||
salaryDate: DateTime.UtcNow.AddDays(5));
|
||||
|
||||
SmallSoftwareDbContext.InsertSalaryToDatabaseAndReturn(
|
||||
worker2.Id,
|
||||
workerSalary: 500,
|
||||
salaryDate: DateTime.UtcNow.AddDays(-5));
|
||||
|
||||
SmallSoftwareDbContext.InsertSalaryToDatabaseAndReturn(
|
||||
worker2.Id,
|
||||
workerSalary: 300,
|
||||
salaryDate: DateTime.UtcNow.AddDays(-3));
|
||||
|
||||
// Act
|
||||
var response = await HttpClient.GetAsync(
|
||||
$"/api/report/getsalary?" +
|
||||
$"fromDate={DateTime.UtcNow.AddDays(-7):MM/dd/yyyy 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<WorkerSalaryByPeriodViewModel>>(response);
|
||||
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(
|
||||
data.First(x => x.WorkerFIO == worker1.FIO).TotalSalary,
|
||||
Is.EqualTo(1000));
|
||||
|
||||
Assert.That(
|
||||
data.First(x => x.WorkerFIO == worker2.FIO).TotalSalary,
|
||||
Is.EqualTo(800));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetSalary_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
// Act
|
||||
var response = await HttpClient.GetAsync(
|
||||
$"/api/report/getsalary?" +
|
||||
$"fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&" +
|
||||
$"toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task LoadSoftwares_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var manufacturer1 = new ManufacturerDataModel(Guid.NewGuid().ToString(), "name1");
|
||||
var manufacturer2 = new ManufacturerDataModel(Guid.NewGuid().ToString(), "name2");
|
||||
SmallSoftwareDbContext.InsertManufacturerToDatabaseAndReturn(manufacturer1.Id, manufacturerName: manufacturer1.ManufacturerName);
|
||||
SmallSoftwareDbContext.InsertManufacturerToDatabaseAndReturn(manufacturer2.Id, manufacturerName: manufacturer2.ManufacturerName);
|
||||
|
||||
var softwareId1 = Guid.NewGuid().ToString();
|
||||
var softwareId2 = Guid.NewGuid().ToString();
|
||||
|
||||
var software1 = SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(manufacturer1.Id,softwareId1, "name1", SoftwareType.Windows, 10, false);
|
||||
var software2 = SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(manufacturer2.Id, softwareId2, "name2", SoftwareType.Windows, 10, false);
|
||||
|
||||
SmallSoftwareDbContext.InsertSoftwareHistoryToDatabaseAndReturn(softwareId1, 22, DateTime.UtcNow);
|
||||
SmallSoftwareDbContext.InsertSoftwareHistoryToDatabaseAndReturn(softwareId2, 21, DateTime.UtcNow);
|
||||
SmallSoftwareDbContext.InsertSoftwareHistoryToDatabaseAndReturn(softwareId1, 33, DateTime.UtcNow);
|
||||
SmallSoftwareDbContext.InsertSoftwareHistoryToDatabaseAndReturn(softwareId1, 32, DateTime.UtcNow);
|
||||
SmallSoftwareDbContext.InsertSoftwareHistoryToDatabaseAndReturn(softwareId2, 65, DateTime.UtcNow);
|
||||
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/report/LoadSoftwares");
|
||||
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
using var data = await response.Content.ReadAsStreamAsync();
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data.Length, Is.GreaterThan(0));
|
||||
await AssertStreamAsync(response, "file.docx");
|
||||
}
|
||||
[Test]
|
||||
public async Task LoadRequests_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
// Arrange
|
||||
var manufacturer1 = SmallSoftwareDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerName: "name 1");
|
||||
var manufacturer2 = SmallSoftwareDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerName: "name 2");
|
||||
|
||||
var worker1 = SmallSoftwareDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
var worker2 = SmallSoftwareDbContext.InsertWorkerToDatabaseAndReturn();
|
||||
|
||||
var software1 = SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn( manufacturer1.Id,
|
||||
softwareName: "name 1");
|
||||
var software2 = SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn( manufacturer2.Id,
|
||||
softwareName: "name 2");
|
||||
|
||||
SmallSoftwareDbContext.InsertRequestToDatabaseAndReturn(
|
||||
worker1.Id,
|
||||
sum: 100,
|
||||
email: "cdsfs@dd.ru",
|
||||
softwares: [(software1.Id, 10, 1.1), (software2.Id, 10, 1.1)]);
|
||||
|
||||
SmallSoftwareDbContext.InsertRequestToDatabaseAndReturn(
|
||||
worker2.Id,
|
||||
sum: 200,
|
||||
email: "cdswws@dd.ru",
|
||||
softwares: [(software1.Id, 10, 1.1)]);
|
||||
|
||||
// Act
|
||||
var response = await HttpClient.GetAsync(
|
||||
$"/api/report/loadrequests?" +
|
||||
$"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 LoadRequests_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
// Act
|
||||
var response = await HttpClient.GetAsync(
|
||||
$"/api/report/loadrequests?" +
|
||||
$"fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&" +
|
||||
$"toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task LoadSalary_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
// Arrange
|
||||
var post = SmallSoftwareDbContext.InsertPostToDatabaseAndReturn();
|
||||
|
||||
var worker1 = SmallSoftwareDbContext.InsertWorkerToDatabaseAndReturn(
|
||||
fio: "fio 1",
|
||||
postId: post.PostId).AddPost(post);
|
||||
|
||||
var worker2 = SmallSoftwareDbContext.InsertWorkerToDatabaseAndReturn(
|
||||
fio: "fio 2",
|
||||
postId: post.PostId).AddPost(post);
|
||||
|
||||
SmallSoftwareDbContext.InsertSalaryToDatabaseAndReturn(
|
||||
worker1.Id,
|
||||
workerSalary: 100,
|
||||
salaryDate: DateTime.UtcNow.AddDays(-10));
|
||||
|
||||
SmallSoftwareDbContext.InsertSalaryToDatabaseAndReturn(
|
||||
worker1.Id,
|
||||
workerSalary: 1000,
|
||||
salaryDate: DateTime.UtcNow.AddDays(-5));
|
||||
|
||||
SmallSoftwareDbContext.InsertSalaryToDatabaseAndReturn(
|
||||
worker1.Id,
|
||||
workerSalary: 200,
|
||||
salaryDate: DateTime.UtcNow.AddDays(5));
|
||||
|
||||
SmallSoftwareDbContext.InsertSalaryToDatabaseAndReturn(
|
||||
worker2.Id,
|
||||
workerSalary: 500,
|
||||
salaryDate: DateTime.UtcNow.AddDays(-5));
|
||||
|
||||
SmallSoftwareDbContext.InsertSalaryToDatabaseAndReturn(
|
||||
worker2.Id,
|
||||
workerSalary: 300,
|
||||
salaryDate: DateTime.UtcNow.AddDays(-3));
|
||||
|
||||
// Act
|
||||
var response = await HttpClient.GetAsync(
|
||||
$"/api/report/loadsalary?" +
|
||||
$"fromDate={DateTime.UtcNow.AddDays(-7):MM/dd/yyyy HH:mm:ss}&" +
|
||||
$"toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
|
||||
// Assert
|
||||
await AssertStreamAsync(response, "file.pdf");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task LoadSalary_WhenDateIsIncorrect_ShouldBadRequest_Test()
|
||||
{
|
||||
// Act
|
||||
var response = await HttpClient.GetAsync(
|
||||
$"/api/report/loadsalary?" +
|
||||
$"fromDate={DateTime.UtcNow.AddDays(1):MM/dd/yyyy HH:mm:ss}&" +
|
||||
$"toDate={DateTime.UtcNow.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
|
||||
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
private static async Task AssertStreamAsync(HttpResponseMessage response, string fileNameForSave = "")
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
using var data = await response.Content.ReadAsStreamAsync();
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data.Length, Is.GreaterThan(0));
|
||||
await SaveStreamAsync(data, fileNameForSave);
|
||||
}
|
||||
private static async Task SaveStreamAsync(Stream stream, string fileName)
|
||||
{
|
||||
if (string.IsNullOrEmpty(fileName))
|
||||
{
|
||||
return;
|
||||
}
|
||||
var path = Path.Combine(Directory.GetCurrentDirectory(), fileName);
|
||||
if (File.Exists(path))
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
stream.Position = 0;
|
||||
using var fileStream = new FileStream(path, FileMode.OpenOrCreate);
|
||||
await stream.CopyToAsync(fileStream);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
using AutoMapper;
|
||||
using SmallSoftwareContracts.AdapterContracts;
|
||||
using SmallSoftwareContracts.AdapterContracts.OperationResponses;
|
||||
using SmallSoftwareContracts.BusinessLogicsContracts;
|
||||
using SmallSoftwareContracts.DataModels;
|
||||
using SmallSoftwareContracts.Exceptions;
|
||||
using SmallSoftwareContracts.ViewModels;
|
||||
|
||||
namespace SmallSoftwareWebApi.Adapters;
|
||||
|
||||
public class ReportAdapter : IReportAdapter
|
||||
{
|
||||
|
||||
private readonly IReportContract _reportContract;
|
||||
private readonly ILogger _logger;
|
||||
private readonly Mapper _mapper;
|
||||
public ReportAdapter(IReportContract reportContract, ILogger<SoftwareAdapter> logger)
|
||||
{
|
||||
_reportContract = reportContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<HistoryOfSoftwareDataModel, HistoryOfSoftwareViewModel>();
|
||||
cfg.CreateMap<RequestDataModel, RequestViewModel>();
|
||||
cfg.CreateMap<InstallationRequestDataModel, InstallationRequestViewModel>();
|
||||
cfg.CreateMap<WorkerSalaryByPeriodDataModel, WorkerSalaryByPeriodViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
|
||||
}
|
||||
public async Task<ReportOperationResponse> GetDataSoftwaresByManufacturerAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ReportOperationResponse.OK([.. (await _reportContract
|
||||
.GetDataSoftwaresByHistoryAsync(ct)).Select(x => _mapper.Map<HistoryOfSoftwareViewModel>(x))]);
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "InvalidOperationException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: { ex.InnerException!.Message}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: { ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return
|
||||
ReportOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ReportOperationResponse> CreateDocumentSoftwaresByManufacturerAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var stream = await _reportContract.CreateDocumentSoftwaresByHistoryAsync(ct);
|
||||
stream.Position = 0;
|
||||
return ReportOperationResponse.OK(stream, "products.docx");
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "InvalidOperationException");
|
||||
return ReportOperationResponse
|
||||
.InternalServerError($"Error while working with data storage: { ex.InnerException!.Message}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ReportOperationResponse
|
||||
.InternalServerError($"Error while working with data storage: { ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return
|
||||
ReportOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ReportOperationResponse> GetDataRequestByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ReportOperationResponse.OK((await _reportContract.GetDataRequestByPeriodAsync(dateStart, dateFinish, ct)).Select(x =>
|
||||
_mapper.Map<RequestViewModel>(x)).ToList());
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return ReportOperationResponse.BadRequest($"Incorrect dates:{ ex.Message} ");
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "InvalidOperationException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: { ex.InnerException!.Message}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: { ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return
|
||||
ReportOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public async Task<ReportOperationResponse> CreateDocumentRequestsByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SendStream(await _reportContract.CreateDocumentRequestsByPeriodAsync(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");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return
|
||||
ReportOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
private static ReportOperationResponse SendStream(Stream stream, string fileName)
|
||||
{
|
||||
stream.Position = 0;
|
||||
return ReportOperationResponse.OK(stream, fileName);
|
||||
}
|
||||
|
||||
public async Task<ReportOperationResponse> GetDataSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ReportOperationResponse.OK((await _reportContract.GetDataSalaryByPeriodAsync(dateStart, dateFinish, ct))
|
||||
.Select(x => _mapper.Map<WorkerSalaryByPeriodViewModel>(x)).ToList());
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "InvalidOperationException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return
|
||||
ReportOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
public async Task<ReportOperationResponse> CreateDocumentSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SendStream(await _reportContract.CreateDocumentSalaryByPeriodAsync(dateStart, dateFinish, ct), "salary.pdf");
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message} ");
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "InvalidOperationException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return
|
||||
ReportOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SmallSoftwareContracts.AdapterContracts;
|
||||
|
||||
namespace SmallSoftwareWebApi.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> GetSoftwares(CancellationToken ct)
|
||||
{
|
||||
return (await
|
||||
_adapter.GetDataSoftwaresByManufacturerAsync(ct)).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Consumes("application/octet-stream")]
|
||||
public async Task<IActionResult> LoadSoftwares(CancellationToken cancellationToken)
|
||||
{
|
||||
return (await
|
||||
_adapter.CreateDocumentSoftwaresByManufacturerAsync(cancellationToken)).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Consumes("application/json")]
|
||||
public async Task<IActionResult> GetRequests(DateTime fromDate, DateTime toDate, CancellationToken cancellationToken)
|
||||
{
|
||||
return (await _adapter.GetDataRequestByPeriodAsync(fromDate, toDate,
|
||||
cancellationToken)).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Consumes("application/octet-stream")]
|
||||
public async Task<IActionResult> LoadRequests(DateTime fromDate, DateTime toDate, CancellationToken cancellationToken)
|
||||
{
|
||||
return (await _adapter.CreateDocumentRequestsByPeriodAsync(fromDate,
|
||||
toDate, cancellationToken)).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Consumes("application/json")]
|
||||
public async Task<IActionResult> GetSalary(DateTime fromDate, DateTime toDate, CancellationToken cancellationToken)
|
||||
{
|
||||
return (await _adapter.GetDataSalaryByPeriodAsync(fromDate, toDate,
|
||||
cancellationToken)).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Consumes("application/octet-stream")]
|
||||
public async Task<IActionResult> LoadSalary(DateTime fromDate, DateTime toDate, CancellationToken cancellationToken)
|
||||
{
|
||||
return (await _adapter.CreateDocumentSalaryByPeriodAsync(fromDate, toDate, cancellationToken)).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -3,6 +3,7 @@ using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Serilog;
|
||||
using SmallSoftwareBusinessLogic.Implementations;
|
||||
using SmallSoftwareBusinessLogic.OfficePackage;
|
||||
using SmallSoftwareContracts.AdapterContracts;
|
||||
using SmallSoftwareContracts.BusinessLogicsContracts;
|
||||
using SmallSoftwareContracts.Infrastructure;
|
||||
@@ -73,6 +74,12 @@ builder.Services.AddTransient<IRequestAdapter, RequestAdapter>();
|
||||
builder.Services.AddTransient<IWorkerAdapter, WorkerAdapter>();
|
||||
builder.Services.AddTransient<ISalaryAdapter, SalaryAdapter>();
|
||||
|
||||
builder.Services.AddTransient<IReportContract, ReportContract>();
|
||||
builder.Services.AddTransient<IReportAdapter, ReportAdapter>();
|
||||
builder.Services.AddTransient<BaseWordBuilder, OpenXmlWordBuilder>();
|
||||
builder.Services.AddTransient<BaseExcelBuilder, OpenXmlExcelBuilder>();
|
||||
builder.Services.AddTransient<BasePdfBuilder, MigraDocPdfBuilder>();
|
||||
|
||||
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
|
||||
builder.Services.AddOpenApi();
|
||||
|
||||
|
||||
Reference in New Issue
Block a user