From 68bb9245ac8e0d93ca79eb2d2e02a8420794383e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D1=81=D0=B5=D0=BD=D0=B8=D1=8F?= Date: Sun, 15 Dec 2024 10:29:22 +0400 Subject: [PATCH 1/3] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=203?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CompShop/CompShop/CompShop.csproj | 2 + .../CompShop/DocumentsBuilder/ChartReport.cs | 55 ++++ .../CompShop/DocumentsBuilder/DocReport.cs | 93 +++++++ .../CompShop/DocumentsBuilder/ExcelBuilder.cs | 257 ++++++++++++++++++ .../CompShop/DocumentsBuilder/PdfBuilder.cs | 106 ++++++++ .../CompShop/DocumentsBuilder/TableReport.cs | 77 ++++++ .../CompShop/DocumentsBuilder/WordBuilder.cs | 145 ++++++++++ CompShop/CompShop/Entites/Check.cs | 2 +- CompShop/CompShop/Entites/Client.cs | 1 - CompShop/CompShop/Entites/Enums/ClientType.cs | 8 +- .../CompShop/Entites/Enums/ProductType.cs | 8 +- CompShop/CompShop/Entites/Product.cs | 7 +- CompShop/CompShop/Entites/ProductInCheck.cs | 2 +- CompShop/CompShop/Entites/Storage.cs | 2 +- CompShop/CompShop/Forms/Form1.Designer.cs | 43 ++- CompShop/CompShop/Forms/Form1.cs | 21 ++ .../ProductsOnStorageForm.Designer.cs | 2 +- .../ProductsOnStorageSettingsForm.cs | 6 +- .../WordDocReport/DocReportForm.Designer.cs | 86 ++++++ .../Forms/WordDocReport/DocReportForm.cs | 71 +++++ .../Forms/WordDocReport/DocReportForm.resx | 60 ++++ .../WordDocReport/ExcelReportForm.Designer.cs | 165 +++++++++++ .../Forms/WordDocReport/ExcelReportForm.cs | 90 ++++++ .../Forms/WordDocReport/ExcelReportForm.resx | 60 ++++ .../WordDocReport/PdfReportForm.Designer.cs | 109 ++++++++ .../Forms/WordDocReport/PdfReportForm.cs | 71 +++++ .../Forms/WordDocReport/PdfReportForm.resx | 60 ++++ .../Repos/IProductOnStorageRepository.cs | 8 +- CompShop/CompShop/Repos/IStorageRepository.cs | 5 + .../CompShop/Repos/Impements/CheckRepo.cs | 1 + .../Repos/Impements/ProductInCheckRepo.cs | 2 +- .../CompShop/Repos/Impements/ProductRepo.cs | 2 +- .../Repos/Impements/ProductsOnStorageRepo.cs | 1 - .../CompShop/Repos/Impements/StorageRepo.cs | 2 +- 34 files changed, 1607 insertions(+), 23 deletions(-) create mode 100644 CompShop/CompShop/DocumentsBuilder/ChartReport.cs create mode 100644 CompShop/CompShop/DocumentsBuilder/DocReport.cs create mode 100644 CompShop/CompShop/DocumentsBuilder/ExcelBuilder.cs create mode 100644 CompShop/CompShop/DocumentsBuilder/PdfBuilder.cs create mode 100644 CompShop/CompShop/DocumentsBuilder/TableReport.cs create mode 100644 CompShop/CompShop/DocumentsBuilder/WordBuilder.cs create mode 100644 CompShop/CompShop/Forms/WordDocReport/DocReportForm.Designer.cs create mode 100644 CompShop/CompShop/Forms/WordDocReport/DocReportForm.cs create mode 100644 CompShop/CompShop/Forms/WordDocReport/DocReportForm.resx create mode 100644 CompShop/CompShop/Forms/WordDocReport/ExcelReportForm.Designer.cs create mode 100644 CompShop/CompShop/Forms/WordDocReport/ExcelReportForm.cs create mode 100644 CompShop/CompShop/Forms/WordDocReport/ExcelReportForm.resx create mode 100644 CompShop/CompShop/Forms/WordDocReport/PdfReportForm.Designer.cs create mode 100644 CompShop/CompShop/Forms/WordDocReport/PdfReportForm.cs create mode 100644 CompShop/CompShop/Forms/WordDocReport/PdfReportForm.resx diff --git a/CompShop/CompShop/CompShop.csproj b/CompShop/CompShop/CompShop.csproj index 36bb7a7..2cee04d 100644 --- a/CompShop/CompShop/CompShop.csproj +++ b/CompShop/CompShop/CompShop.csproj @@ -10,9 +10,11 @@ + + diff --git a/CompShop/CompShop/DocumentsBuilder/ChartReport.cs b/CompShop/CompShop/DocumentsBuilder/ChartReport.cs new file mode 100644 index 0000000..163a597 --- /dev/null +++ b/CompShop/CompShop/DocumentsBuilder/ChartReport.cs @@ -0,0 +1,55 @@ +using CompShop.DocumentsBuilder; +using CompShop.Repos; +using Microsoft.Extensions.Logging; + +internal class ChartReport +{ + private readonly ICheckRepository _checkRepository; // Репозиторий для получения данных о чеках + private readonly IProductRepository _productRepository; // Репозиторий для получения данных о продуктах + private readonly ILogger _logger; + + public ChartReport(ICheckRepository checkRepository, IProductRepository productRepository, ILoggerFactory loggerFactory) + { + _checkRepository = checkRepository ?? throw new ArgumentNullException(nameof(checkRepository)); + _productRepository = productRepository ?? throw new ArgumentNullException(nameof(productRepository)); + _logger = loggerFactory.CreateLogger(); + } + + public bool CreateChart(string filePath, DateTime dateTime) + { + try + { + new PdfBuilder(filePath) + .AddHeader("Отчет по продажам товаров") + .AddPieChart("Проданные товары", GetData(dateTime)) // Диаграмма с продуктами + .Build(); + + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + } + + private List<(string Caption, double Value)> GetData(DateTime dateTime) + { + // Получаем все чеки, которые были оформлены в указанную дату + var checkData = _checkRepository + .ReadAll() + .Where(x => x.PurchaseDate.Date == dateTime.Date) // Фильтрация по дате + .SelectMany(x => x.Products) // Получаем все продукты из всех чеков + .GroupBy(p => p.ProductID) // Группируем по ID продукта + .Select(g => + { + // Получаем продукт по ProductID + var product = _productRepository.Read(g.Key); + return (Caption: product.Name, Value: (double)g.Sum(p => p.Count)); // Преобразуем Count в double + }) + .ToList(); + + return checkData; + } + +} diff --git a/CompShop/CompShop/DocumentsBuilder/DocReport.cs b/CompShop/CompShop/DocumentsBuilder/DocReport.cs new file mode 100644 index 0000000..4cfb11d --- /dev/null +++ b/CompShop/CompShop/DocumentsBuilder/DocReport.cs @@ -0,0 +1,93 @@ +using CompShop.Repos; +using CompShop.Repos.Impements; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CompShop.DocumentsBuilder +{ + internal class DocReport + { + private readonly IClientRepository _clientRepository; + + private readonly IProductRepository _productRepository; + + private readonly IStorageRepository _storageRepository; + + private readonly ILogger _logger; + + public DocReport(IClientRepository clientRepository, IProductRepository productRepository, IStorageRepository storageRepository, ILoggerFactory loggerFactory) + { + _clientRepository = clientRepository ?? + throw new ArgumentNullException(nameof(clientRepository)); + _productRepository = productRepository ?? + throw new ArgumentNullException(nameof(productRepository)); + _storageRepository = storageRepository ?? + throw new ArgumentNullException(nameof(storageRepository)); + _logger = loggerFactory.CreateLogger(); + } + public bool CreateDoc(string filePath, bool includeClients, bool includeProducts, bool includeStorage) + { + try + { + var builder = new WordBuilder(filePath) + .AddHeader("Документ со справочниками"); + + if (includeClients) + { + builder.AddParagraph("Клиенты") + .AddTable(new int[] { 2400, 2400, 3200, 1200 }, GetClients()); + } + + if (includeProducts) + { + builder.AddParagraph("Товары") + .AddTable(new int[] { 2400, 2400, 2400, 2400, 2400 }, GetProducts()); + } + + if (includeStorage) + { + builder.AddParagraph("Склады") + .AddTable(new int[] { 2400, 2400, 1200 }, GetStorage()); + } + + builder.Build(); + + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + } + + private List GetClients() + { + List result = _clientRepository.ReadAll().Select(x => new string[] { x.Id.ToString(), x.Name, x.PhoneNumber, x.ClientType.ToString() }).ToList(); + + result.Insert(0, new string[] { "ID", "Имя", "Номер телефона", "Тип клиента" }); + + return result; + } + private List GetProducts() + { + List result = _productRepository.ReadAll().Select(x => new string[] { x.ID.ToString(), x.Name, x.Description, x.ProductType.ToString(), x.Price.ToString() + " р." }).ToList(); + + result.Insert(0, new string[] { "ID", "Имя", "Описание", "Тип товара", "Цена" }); + + return result; + } + private List GetStorage() + { + List result = _storageRepository.ReadAll().Select(x => new string[] { x.Id.ToString(), x.Adress, x.Size.ToString()}).ToList(); + + result.Insert(0, new string[] { "ID", "Адрес", "Вместимость"}); + + return result; + } + } +} diff --git a/CompShop/CompShop/DocumentsBuilder/ExcelBuilder.cs b/CompShop/CompShop/DocumentsBuilder/ExcelBuilder.cs new file mode 100644 index 0000000..b8aac0f --- /dev/null +++ b/CompShop/CompShop/DocumentsBuilder/ExcelBuilder.cs @@ -0,0 +1,257 @@ +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Spreadsheet; +using DocumentFormat.OpenXml; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace CompShop.DocumentsBuilder +{ + internal class ExcelBuilder + { + private readonly string _filePath; + private readonly SheetData _sheetData; + private readonly MergeCells _mergeCells; + private readonly Columns _columns; + private uint _rowIndex = 0; + + public ExcelBuilder(string filePath) + { + if (string.IsNullOrWhiteSpace(filePath)) + { + throw new ArgumentNullException(nameof(filePath)); + } + if (File.Exists(filePath)) + { + File.Delete(filePath); + } + + _filePath = filePath; + _sheetData = new SheetData(); + _mergeCells = new MergeCells(); + _columns = new Columns(); + _rowIndex = 1; + } + + public ExcelBuilder 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 ExcelBuilder AddParagraph(string text, int columnIndex) + { + CreateCell(columnIndex, _rowIndex++, text, StyleIndex.SimpleTextWithBorders); + return this; + } + + public ExcelBuilder AddTable(int[] columnsWidths, List 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 (int i = 0; i < data.Count; ++i) + { + var isBoldRow = i == 0 || i == data.Count - 1; // Только заголовок и последняя строка жирные + var styleIndex = isBoldRow ? StyleIndex.BoldTextWithBorders : StyleIndex.SimpleTextWithBorders; + + for (int j = 0; j < data[i].Length; ++j) + { + CreateCell(j, _rowIndex, data[i][j], styleIndex); + } + + _rowIndex++; + } + + return this; + } + + private enum StyleIndex + { + SimpleTextWithoutBorder = 0, + BoldText = 1, + SimpleTextWithBorders = 2, + BoldTextWithBorders = 3 + } + + public void Build() + { + using var spreadsheetDocument = SpreadsheetDocument.Create(_filePath, SpreadsheetDocumentType.Workbook); + var workbookpart = spreadsheetDocument.AddWorkbookPart(); + GenerateStyle(workbookpart); + workbookpart.Workbook = new Workbook(); + var worksheetPart = workbookpart.AddNewPart(); + 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().First()); + } + } + + private static void GenerateStyle(WorkbookPart workbookPart) + { + var workbookStylesPart = workbookPart.AddNewPart(); + workbookStylesPart.Stylesheet = new Stylesheet(); + + // Шрифты + var fonts = new Fonts() { Count = 2 }; + fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font + { + FontSize = new FontSize() { Val = 11 }, + FontName = new FontName() { Val = "Calibri" } + }); + fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font + { + Bold = new Bold(), + FontSize = new FontSize() { Val = 11 }, + FontName = new FontName() { Val = "Calibri" } + }); + + // Заполнение + var fills = new Fills() { Count = 1 }; + fills.Append(new Fill + { + PatternFill = new PatternFill { PatternType = PatternValues.None } + }); + + // Границы + var borders = new Borders() { Count = 2 }; + borders.Append(new Border()); // Без границ + 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 } + }); + + // Форматы ячеек + var cellFormats = new CellFormats() { Count = 4 }; + cellFormats.Append(new CellFormat + { + FontId = 0, + FillId = 0, + BorderId = 0, + ApplyFont = true + }); // Обычный текст без границ + cellFormats.Append(new CellFormat + { + FontId = 1, + FillId = 0, + BorderId = 0, + ApplyFont = true + }); // Жирный текст без границ + cellFormats.Append(new CellFormat + { + FontId = 0, + FillId = 0, + BorderId = 1, + ApplyFont = true, + ApplyBorder = true + }); // Обычный текст с границами + cellFormats.Append(new CellFormat + { + FontId = 1, + FillId = 0, + BorderId = 1, + ApplyFont = true, + ApplyBorder = true + }); // Жирный текст с границами + + workbookStylesPart.Stylesheet.Append(fonts); + workbookStylesPart.Stylesheet.Append(fills); + workbookStylesPart.Stylesheet.Append(borders); + workbookStylesPart.Stylesheet.Append(cellFormats); + } + + + + + private void CreateCell(int columnIndex, uint rowIndex, string text, StyleIndex styleIndex) + { + var columnName = GetExcelColumnName(columnIndex); + var cellReference = columnName + rowIndex; + + var row = _sheetData.Elements().FirstOrDefault(r => r.RowIndex == rowIndex); + if (row == null) + { + row = new Row() { RowIndex = rowIndex }; + _sheetData.Append(row); + } + + var cell = new Cell + { + CellReference = cellReference, + StyleIndex = (UInt32Value)(uint)styleIndex, + CellValue = new CellValue(text), + DataType = new EnumValue(CellValues.String) + }; + + row.Append(cell); + } + + private static string GetExcelColumnName(int index) + { + int div = index; + string columnName = string.Empty; + while (div >= 0) + { + columnName = (char)(div % 26 + 65) + columnName; + div = div / 26 - 1; + } + return columnName; + } + } +} + + diff --git a/CompShop/CompShop/DocumentsBuilder/PdfBuilder.cs b/CompShop/CompShop/DocumentsBuilder/PdfBuilder.cs new file mode 100644 index 0000000..edb7136 --- /dev/null +++ b/CompShop/CompShop/DocumentsBuilder/PdfBuilder.cs @@ -0,0 +1,106 @@ +using MigraDoc.DocumentObjectModel; +using MigraDoc.DocumentObjectModel.Shapes.Charts; +using MigraDoc.Rendering; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Chart = MigraDoc.DocumentObjectModel.Shapes.Charts.Chart; + +namespace CompShop.DocumentsBuilder +{ + internal class PdfBuilder + { + private readonly string _filePath; + + private readonly Document _document; + + public PdfBuilder(string filePath) + { + if (string.IsNullOrWhiteSpace(filePath)) + { + throw new ArgumentNullException(nameof(filePath)); + } + + if (File.Exists(filePath)) + { + File.Delete(filePath); + } + + _filePath = filePath; + _document = new Document(); + DefineStyles(); + } + + public PdfBuilder AddHeader(string header) + { + _document.AddSection().AddParagraph(header, "NormalBold"); + return this;//подпись, число + } + + public PdfBuilder 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 void Build() + { + var renderer = new PdfDocumentRenderer(true) + { + Document = _document + }; + + renderer.RenderDocument(); + renderer.PdfDocument.Save(_filePath); + } + + private void DefineStyles() + { + // Получаем стандартный стиль Normal + var normalStyle = _document.Styles["Normal"]; + normalStyle.Font.Name = "Arial"; + normalStyle.Font.Size = 12; + + // Создаем стиль для жирного заголовка + var boldStyle = _document.Styles.AddStyle("NormalBold", "Normal"); + boldStyle.Font.Bold = true; + boldStyle.Font.Size = 14; // Например, чуть больше стандартного текста + boldStyle.ParagraphFormat.Alignment = ParagraphAlignment.Center; // Опционально, выравнивание по центру + } + + } +} diff --git a/CompShop/CompShop/DocumentsBuilder/TableReport.cs b/CompShop/CompShop/DocumentsBuilder/TableReport.cs new file mode 100644 index 0000000..938cfb1 --- /dev/null +++ b/CompShop/CompShop/DocumentsBuilder/TableReport.cs @@ -0,0 +1,77 @@ +using CompShop.DocumentsBuilder; +using CompShop.Repos; +using Microsoft.Extensions.Logging; + +internal class TableReport +{ + private readonly ICheckRepository _checkRepository; + private readonly IProductRepository _productRepository; + private readonly ILogger _logger; + + internal static readonly string[] Headers = { "Клиент", "Дата", "Количество" }; + + public TableReport(ICheckRepository checkRepository, IProductRepository productRepository, ILoggerFactory loggerFactory) + { + _checkRepository = checkRepository ?? throw new ArgumentNullException(nameof(checkRepository)); + _productRepository = productRepository ?? throw new ArgumentNullException(nameof(productRepository)); + _logger = loggerFactory.CreateLogger(); + } + + public bool CreateTable(string filePath, int productId, DateTime startDate, DateTime endDate) + { + try + { + new ExcelBuilder(filePath) + .AddHeader("Отчет по продажам товара", 0, 3) + .AddParagraph($"за период с {startDate.ToShortDateString()} по {endDate.ToShortDateString()}", 0) + .AddTable(new[] { 20, 20, 15 }, GetData(productId, startDate, endDate)) + .Build(); + + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании отчета"); + return false; + } + } + + private List GetData(int productId, DateTime startDate, DateTime endDate) + { + // Получение данных о чеках, содержащих указанный товар + var checksWithProduct = _checkRepository + .ReadAll() + .Where(c => c.PurchaseDate >= startDate && c.PurchaseDate <= endDate + && c.Products.Any(p => p.ProductID == productId)) + .Select(c => new + { + ClientName = c.Client?.ToString() ?? "Неизвестно", + Date = c.PurchaseDate, + Quantity = c.Products + .Where(p => p.ProductID == productId) + .Sum(p => p.Count) + }) + .OrderBy(x => x.Date); + + // Формирование итоговой таблицы + return new List { Headers } + .Union( + checksWithProduct.Select(x => new string[] + { + x.ClientName, + x.Date.ToShortDateString(), + x.Quantity.ToString() + }) + ) + .Union(new[] + { + new string[] + { + "Всего", + "", + checksWithProduct.Sum(x => x.Quantity).ToString() + } + }) + .ToList(); + } +} diff --git a/CompShop/CompShop/DocumentsBuilder/WordBuilder.cs b/CompShop/CompShop/DocumentsBuilder/WordBuilder.cs new file mode 100644 index 0000000..ba919d3 --- /dev/null +++ b/CompShop/CompShop/DocumentsBuilder/WordBuilder.cs @@ -0,0 +1,145 @@ +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Wordprocessing; +using System; +using System.Collections.Generic; +using System.Linq; + + +namespace CompShop.DocumentsBuilder +{ + internal class WordBuilder + { + private readonly string _filePath; + private readonly Document _document; + private readonly Body _body; + public WordBuilder(string filePath) + { + if (string.IsNullOrWhiteSpace(filePath)) + { + throw new ArgumentNullException(nameof(filePath)); + } + + if (File.Exists(filePath)) + { + File.Delete(filePath); + } + + _filePath = filePath; + _document = new Document(); + _body = _document.AppendChild(new Body()); + } + + public WordBuilder AddHeader(string header) + { + var paragraph = _body.AppendChild(new Paragraph()); + var run = paragraph.AppendChild(new Run()); + + // Добавляем свойства для жирного текста + var runProperties = new RunProperties(); + runProperties.AppendChild(new Bold()); + run.PrependChild(runProperties); + + // Добавляем текст заголовка + run.AppendChild(new Text(header)); + + return this; + } + + + public WordBuilder AddParagraph(string text) + { + var paragraph = _body.AppendChild(new Paragraph()); + var run = paragraph.AppendChild(new Run()); + run.AppendChild(new Text(text)); + + return this; + } + + public WordBuilder AddTable(int[] widths, List 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.Single), + Size = 12 + }, + new BottomBorder() + { + Val = new EnumValue(BorderValues.Single), + Size = 12 + }, + new LeftBorder() + { + Val = new EnumValue(BorderValues.Single), + Size = 12 + }, + new RightBorder() + { + Val = new EnumValue(BorderValues.Single), + Size = 12 + }, + new InsideHorizontalBorder() + { + Val = new EnumValue(BorderValues.Single), + Size = 12 + }, + new InsideVerticalBorder() + { + Val = new EnumValue(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 void Build() + { + using var wordDocument = WordprocessingDocument.Create(_filePath, + WordprocessingDocumentType.Document); + var mainPart = wordDocument.AddMainDocumentPart(); + mainPart.Document = _document; + } + } +} diff --git a/CompShop/CompShop/Entites/Check.cs b/CompShop/CompShop/Entites/Check.cs index 2f4d40c..6802aca 100644 --- a/CompShop/CompShop/Entites/Check.cs +++ b/CompShop/CompShop/Entites/Check.cs @@ -9,7 +9,7 @@ namespace CompShop.Entites public Client Client { get; set; } [System.ComponentModel.Browsable(false)] - public int ClientId { get; set; } + public int ClientId { get; set; } public DateTime PurchaseDate { get; set; } public static Check CreateEntity(int id, List products, Client client, DateTime purchaseDate) diff --git a/CompShop/CompShop/Entites/Client.cs b/CompShop/CompShop/Entites/Client.cs index 55103ea..0bc9180 100644 --- a/CompShop/CompShop/Entites/Client.cs +++ b/CompShop/CompShop/Entites/Client.cs @@ -31,4 +31,3 @@ namespace CompShop.Entites } } } - diff --git a/CompShop/CompShop/Entites/Enums/ClientType.cs b/CompShop/CompShop/Entites/Enums/ClientType.cs index ecc7aad..19956cf 100644 --- a/CompShop/CompShop/Entites/Enums/ClientType.cs +++ b/CompShop/CompShop/Entites/Enums/ClientType.cs @@ -1,4 +1,10 @@ -namespace CompShop.Entites.Enums +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CompShop.Entites.Enums { public enum ClientType { diff --git a/CompShop/CompShop/Entites/Enums/ProductType.cs b/CompShop/CompShop/Entites/Enums/ProductType.cs index a30a50b..51abd3e 100644 --- a/CompShop/CompShop/Entites/Enums/ProductType.cs +++ b/CompShop/CompShop/Entites/Enums/ProductType.cs @@ -1,4 +1,10 @@ -namespace CompShop.Entites.Enums +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CompShop.Entites.Enums { [Flags] public enum ProductType diff --git a/CompShop/CompShop/Entites/Product.cs b/CompShop/CompShop/Entites/Product.cs index 9951bf4..d339bb4 100644 --- a/CompShop/CompShop/Entites/Product.cs +++ b/CompShop/CompShop/Entites/Product.cs @@ -12,14 +12,11 @@ namespace CompShop.Entites public static Product CreateEntity(int id, string name, string desc, decimal price, ProductType productType) { - return new Product - { - ID = id, + return new Product { ID = id, Name = name ?? string.Empty, Description = desc ?? string.Empty, Price = price, - ProductType = productType - }; + ProductType = productType }; } public override string ToString() { diff --git a/CompShop/CompShop/Entites/ProductInCheck.cs b/CompShop/CompShop/Entites/ProductInCheck.cs index 15e9a5c..d88b584 100644 --- a/CompShop/CompShop/Entites/ProductInCheck.cs +++ b/CompShop/CompShop/Entites/ProductInCheck.cs @@ -14,7 +14,7 @@ namespace CompShop.Entites public int Count { get; set; } public static ProductInCheck CreateElement(int id, int count) { - return new ProductInCheck { ProductID = id, Count = count }; + return new ProductInCheck { ProductID = id, Count = count}; } } } diff --git a/CompShop/CompShop/Entites/Storage.cs b/CompShop/CompShop/Entites/Storage.cs index ecdfe9f..5e937b4 100644 --- a/CompShop/CompShop/Entites/Storage.cs +++ b/CompShop/CompShop/Entites/Storage.cs @@ -23,4 +23,4 @@ namespace CompShop.Entites return Adress; } } -} \ No newline at end of file +} diff --git a/CompShop/CompShop/Forms/Form1.Designer.cs b/CompShop/CompShop/Forms/Form1.Designer.cs index 8ab7949..5f9f807 100644 --- a/CompShop/CompShop/Forms/Form1.Designer.cs +++ b/CompShop/CompShop/Forms/Form1.Designer.cs @@ -37,13 +37,17 @@ операцииToolStripMenuItem = new ToolStripMenuItem(); товарыНаСкаледToolStripMenuItem = new ToolStripMenuItem(); чекиToolStripMenuItem = new ToolStripMenuItem(); + отчетToolStripMenuItem = new ToolStripMenuItem(); + документсправочникToolStripMenuItem = new ToolStripMenuItem(); + продажиТоваровToolStripMenuItem = new ToolStripMenuItem(); + отчетграфикToolStripMenuItem = new ToolStripMenuItem(); menuStrip1.SuspendLayout(); SuspendLayout(); // // menuStrip1 // menuStrip1.ImageScalingSize = new Size(20, 20); - menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, операцииToolStripMenuItem }); + menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, операцииToolStripMenuItem, отчетToolStripMenuItem }); menuStrip1.Location = new Point(0, 0); menuStrip1.Name = "menuStrip1"; menuStrip1.Size = new Size(800, 28); @@ -88,17 +92,45 @@ // товарыНаСкаледToolStripMenuItem // товарыНаСкаледToolStripMenuItem.Name = "товарыНаСкаледToolStripMenuItem"; - товарыНаСкаледToolStripMenuItem.Size = new Size(224, 26); + товарыНаСкаледToolStripMenuItem.Size = new Size(216, 26); товарыНаСкаледToolStripMenuItem.Text = "Товары на складе"; товарыНаСкаледToolStripMenuItem.Click += товарыНаСкаледToolStripMenuItem_Click; // // чекиToolStripMenuItem // чекиToolStripMenuItem.Name = "чекиToolStripMenuItem"; - чекиToolStripMenuItem.Size = new Size(224, 26); + чекиToolStripMenuItem.Size = new Size(216, 26); чекиToolStripMenuItem.Text = "Чеки..."; чекиToolStripMenuItem.Click += чекиToolStripMenuItem_Click; // + // отчетToolStripMenuItem + // + отчетToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { документсправочникToolStripMenuItem, продажиТоваровToolStripMenuItem, отчетграфикToolStripMenuItem }); + отчетToolStripMenuItem.Name = "отчетToolStripMenuItem"; + отчетToolStripMenuItem.Size = new Size(82, 24); + отчетToolStripMenuItem.Text = "Отчеты..."; + // + // документсправочникToolStripMenuItem + // + документсправочникToolStripMenuItem.Name = "документсправочникToolStripMenuItem"; + документсправочникToolStripMenuItem.Size = new Size(248, 26); + документсправочникToolStripMenuItem.Text = "Документ-справочник"; + документсправочникToolStripMenuItem.Click += документсправочникToolStripMenuItem_Click; + // + // продажиТоваровToolStripMenuItem + // + продажиТоваровToolStripMenuItem.Name = "продажиТоваровToolStripMenuItem"; + продажиТоваровToolStripMenuItem.Size = new Size(248, 26); + продажиТоваровToolStripMenuItem.Text = "Продажи товаров"; + продажиТоваровToolStripMenuItem.Click += продажиТоваровToolStripMenuItem_Click; + // + // отчетграфикToolStripMenuItem + // + отчетграфикToolStripMenuItem.Name = "отчетграфикToolStripMenuItem"; + отчетграфикToolStripMenuItem.Size = new Size(248, 26); + отчетграфикToolStripMenuItem.Text = "Отчет-график"; + отчетграфикToolStripMenuItem.Click += отчетграфикToolStripMenuItem_Click; + // // ShopForm // AutoScaleDimensions = new SizeF(8F, 20F); @@ -110,6 +142,7 @@ MainMenuStrip = menuStrip1; Name = "ShopForm"; Text = "Магазин электроники"; + Load += ShopForm_Load; menuStrip1.ResumeLayout(false); menuStrip1.PerformLayout(); ResumeLayout(false); @@ -126,5 +159,9 @@ private ToolStripMenuItem операцииToolStripMenuItem; private ToolStripMenuItem товарыНаСкаледToolStripMenuItem; private ToolStripMenuItem чекиToolStripMenuItem; + private ToolStripMenuItem отчетToolStripMenuItem; + private ToolStripMenuItem документсправочникToolStripMenuItem; + private ToolStripMenuItem продажиТоваровToolStripMenuItem; + private ToolStripMenuItem отчетграфикToolStripMenuItem; } } \ No newline at end of file diff --git a/CompShop/CompShop/Forms/Form1.cs b/CompShop/CompShop/Forms/Form1.cs index f81a502..4bcf541 100644 --- a/CompShop/CompShop/Forms/Form1.cs +++ b/CompShop/CompShop/Forms/Form1.cs @@ -2,6 +2,7 @@ using CompShop.Forms; using CompShop.Forms.ProductsOnStorage; using CompShop.Forms.Receipt; using CompShop.Forms.Storage; +using CompShop.Forms.WordDocReport; using Unity; namespace CompShop @@ -44,5 +45,25 @@ namespace CompShop _container.Resolve().ShowDialog(); } + + private void ToolStripMenuItem_Click(object sender, EventArgs e) + { + _container.Resolve().ShowDialog(); + } + + private void ToolStripMenuItem_Click(object sender, EventArgs e) + { + _container.Resolve().ShowDialog(); + } + + private void ShopForm_Load(object sender, EventArgs e) + { + + } + + private void ToolStripMenuItem_Click(object sender, EventArgs e) + { + _container.Resolve().ShowDialog(); + } } } \ No newline at end of file diff --git a/CompShop/CompShop/Forms/ProductsOnStorage/ProductsOnStorageForm.Designer.cs b/CompShop/CompShop/Forms/ProductsOnStorage/ProductsOnStorageForm.Designer.cs index 1a7406a..a4986ff 100644 --- a/CompShop/CompShop/Forms/ProductsOnStorage/ProductsOnStorageForm.Designer.cs +++ b/CompShop/CompShop/Forms/ProductsOnStorage/ProductsOnStorageForm.Designer.cs @@ -56,7 +56,7 @@ productsDataGridView.Size = new Size(851, 400); productsDataGridView.TabIndex = 8; // - // deleteButton + // editButton // editButton.Location = new Point(881, 78); editButton.Name = "editButton"; diff --git a/CompShop/CompShop/Forms/ProductsOnStorage/ProductsOnStorageSettingsForm.cs b/CompShop/CompShop/Forms/ProductsOnStorage/ProductsOnStorageSettingsForm.cs index 9311c3c..6b6e22a 100644 --- a/CompShop/CompShop/Forms/ProductsOnStorage/ProductsOnStorageSettingsForm.cs +++ b/CompShop/CompShop/Forms/ProductsOnStorage/ProductsOnStorageSettingsForm.cs @@ -32,9 +32,9 @@ namespace CompShop.Forms.ProductsOnStorage throw new InvalidDataException("Record not found"); } //ProductComboBox - foreach (var item in _productRepository.ReadAll()) + foreach(var item in _productRepository.ReadAll() ) { - if (item.ID == record.ProductId) + if(item.ID == record.ProductId) { productCombobox.SelectedItem = item; } @@ -114,4 +114,4 @@ namespace CompShop.Forms.ProductsOnStorage return Entites.ProductsOnStorage.CreateEntity(id, product, storage, count); } } -} \ No newline at end of file +} diff --git a/CompShop/CompShop/Forms/WordDocReport/DocReportForm.Designer.cs b/CompShop/CompShop/Forms/WordDocReport/DocReportForm.Designer.cs new file mode 100644 index 0000000..9da38cc --- /dev/null +++ b/CompShop/CompShop/Forms/WordDocReport/DocReportForm.Designer.cs @@ -0,0 +1,86 @@ +namespace CompShop.Forms.WordDocReport +{ + partial class DocReportForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + label1 = new Label(); + buildReportButton = new Button(); + entitiesCheckedListBox = new CheckedListBox(); + SuspendLayout(); + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(12, 9); + label1.Name = "label1"; + label1.Size = new Size(164, 20); + label1.TabIndex = 0; + label1.Text = "Что включить в отчет?"; + // + // buildReportButton + // + buildReportButton.Anchor = AnchorStyles.Bottom; + buildReportButton.Location = new Point(81, 174); + buildReportButton.Name = "buildReportButton"; + buildReportButton.Size = new Size(143, 29); + buildReportButton.TabIndex = 1; + buildReportButton.Text = "Сформировать"; + buildReportButton.UseVisualStyleBackColor = true; + buildReportButton.Click += buildReportButton_Click; + // + // entitiesCheckedListBox + // + entitiesCheckedListBox.FormattingEnabled = true; + entitiesCheckedListBox.Items.AddRange(new object[] { "Клиенты", "Товары", "Склады" }); + entitiesCheckedListBox.Location = new Point(12, 42); + entitiesCheckedListBox.Name = "entitiesCheckedListBox"; + entitiesCheckedListBox.Size = new Size(273, 114); + entitiesCheckedListBox.TabIndex = 2; + // + // DocReportForm + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(311, 215); + Controls.Add(entitiesCheckedListBox); + Controls.Add(buildReportButton); + Controls.Add(label1); + Name = "DocReportForm"; + Text = "DocReportForm"; + Load += DocReportForm_Load; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Label label1; + private Button buildReportButton; + private CheckedListBox entitiesCheckedListBox; + } +} \ No newline at end of file diff --git a/CompShop/CompShop/Forms/WordDocReport/DocReportForm.cs b/CompShop/CompShop/Forms/WordDocReport/DocReportForm.cs new file mode 100644 index 0000000..28a2df5 --- /dev/null +++ b/CompShop/CompShop/Forms/WordDocReport/DocReportForm.cs @@ -0,0 +1,71 @@ +using CompShop.DocumentsBuilder; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using Unity; + +namespace CompShop.Forms.WordDocReport +{ + public partial class DocReportForm : Form + { + private readonly IUnityContainer _container; + + public DocReportForm(IUnityContainer container) + { + InitializeComponent(); + + _container = container ?? throw new ArgumentNullException(nameof(container)); + } + + private void DocReportForm_Load(object sender, EventArgs e) + { + + } + + private void buildReportButton_Click(object sender, EventArgs e) + { + try + { + if (!entitiesCheckedListBox.GetItemChecked(0) && !entitiesCheckedListBox.GetItemChecked(1) && !entitiesCheckedListBox.GetItemChecked(2)) + { + throw new Exception("Не выбран ни один справочник для выгрузки"); + } + + var sfd = new SaveFileDialog() + { + Filter = "Docx Files | *.docx" + }; + + if (sfd.ShowDialog() != DialogResult.OK) + { + throw new Exception("Не выбран файла для отчета"); + } + + if (_container.Resolve().CreateDoc(sfd.FileName, entitiesCheckedListBox.GetItemChecked(0), + entitiesCheckedListBox.GetItemChecked(1), + entitiesCheckedListBox.GetItemChecked(2))) + { + MessageBox.Show("Документ сформирован", + "Формирование документа", + MessageBoxButtons.OK, + MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Возникли ошибки при документа.Подробности в логах", + "Формирование документа", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при создании отчета", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } +} diff --git a/CompShop/CompShop/Forms/WordDocReport/DocReportForm.resx b/CompShop/CompShop/Forms/WordDocReport/DocReportForm.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/CompShop/CompShop/Forms/WordDocReport/DocReportForm.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/CompShop/CompShop/Forms/WordDocReport/ExcelReportForm.Designer.cs b/CompShop/CompShop/Forms/WordDocReport/ExcelReportForm.Designer.cs new file mode 100644 index 0000000..221421c --- /dev/null +++ b/CompShop/CompShop/Forms/WordDocReport/ExcelReportForm.Designer.cs @@ -0,0 +1,165 @@ +namespace CompShop.Forms.WordDocReport +{ + partial class ExcelReportForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + formButton = new Button(); + dateTimePickerDo = new DateTimePicker(); + label4 = new Label(); + dateTimePickerOt = new DateTimePicker(); + label3 = new Label(); + productCombobox = new ComboBox(); + label2 = new Label(); + pathChoiceButton = new Button(); + pathTextbox = new TextBox(); + label1 = new Label(); + SuspendLayout(); + // + // formButton + // + formButton.Anchor = AnchorStyles.Bottom; + formButton.Location = new Point(178, 240); + formButton.Name = "formButton"; + formButton.Size = new Size(138, 29); + formButton.TabIndex = 29; + formButton.Text = "Формировать"; + formButton.UseVisualStyleBackColor = true; + formButton.Click += formButton_Click; + // + // dateTimePickerDo + // + dateTimePickerDo.Location = new Point(156, 161); + dateTimePickerDo.Name = "dateTimePickerDo"; + dateTimePickerDo.Size = new Size(250, 27); + dateTimePickerDo.TabIndex = 28; + // + // label4 + // + label4.AutoSize = true; + label4.Location = new Point(19, 166); + label4.Name = "label4"; + label4.Size = new Size(31, 20); + label4.TabIndex = 27; + label4.Text = "До:"; + // + // dateTimePickerOt + // + dateTimePickerOt.Location = new Point(156, 117); + dateTimePickerOt.Name = "dateTimePickerOt"; + dateTimePickerOt.Size = new Size(250, 27); + dateTimePickerOt.TabIndex = 26; + // + // label3 + // + label3.AutoSize = true; + label3.Location = new Point(19, 122); + label3.Name = "label3"; + label3.Size = new Size(29, 20); + label3.TabIndex = 25; + label3.Text = "От:"; + // + // productCombobox + // + productCombobox.FormattingEnabled = true; + productCombobox.Location = new Point(156, 68); + productCombobox.Name = "productCombobox"; + productCombobox.Size = new Size(251, 28); + productCombobox.TabIndex = 24; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(19, 71); + label2.Name = "label2"; + label2.Size = new Size(54, 20); + label2.TabIndex = 23; + label2.Text = "Товар:"; + // + // pathChoiceButton + // + pathChoiceButton.Location = new Point(372, 14); + pathChoiceButton.Name = "pathChoiceButton"; + pathChoiceButton.Size = new Size(35, 29); + pathChoiceButton.TabIndex = 22; + pathChoiceButton.Text = "..."; + pathChoiceButton.UseVisualStyleBackColor = true; + pathChoiceButton.Click += pathChoiceButton_Click; + // + // pathTextbox + // + pathTextbox.Location = new Point(156, 15); + pathTextbox.Name = "pathTextbox"; + pathTextbox.ReadOnly = true; + pathTextbox.Size = new Size(210, 27); + pathTextbox.TabIndex = 21; + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(19, 18); + label1.Name = "label1"; + label1.Size = new Size(116, 20); + label1.TabIndex = 20; + label1.Text = "Путь до файла: "; + // + // ExcelReportForm + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(478, 281); + Controls.Add(formButton); + Controls.Add(dateTimePickerDo); + Controls.Add(label4); + Controls.Add(dateTimePickerOt); + Controls.Add(label3); + Controls.Add(productCombobox); + Controls.Add(label2); + Controls.Add(pathChoiceButton); + Controls.Add(pathTextbox); + Controls.Add(label1); + Name = "ExcelReportForm"; + Text = "ExcelReportForm"; + Load += ExcelReportForm_Load; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Button formButton; + private DateTimePicker dateTimePickerDo; + private Label label4; + private DateTimePicker dateTimePickerOt; + private Label label3; + private ComboBox productCombobox; + private Label label2; + private Button pathChoiceButton; + private TextBox pathTextbox; + private Label label1; + } +} \ No newline at end of file diff --git a/CompShop/CompShop/Forms/WordDocReport/ExcelReportForm.cs b/CompShop/CompShop/Forms/WordDocReport/ExcelReportForm.cs new file mode 100644 index 0000000..503ff74 --- /dev/null +++ b/CompShop/CompShop/Forms/WordDocReport/ExcelReportForm.cs @@ -0,0 +1,90 @@ +using CompShop.Repos; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using Unity; + +namespace CompShop.Forms.WordDocReport +{ + public partial class ExcelReportForm : Form + { + private readonly IUnityContainer _container; + + public ExcelReportForm(IUnityContainer container, IProductRepository productRepository) + { + InitializeComponent(); + + _container = container ?? throw new ArgumentNullException(nameof(container)); + + productCombobox.DataSource = productRepository.ReadAll(); + productCombobox.DisplayMember = "Name"; + productCombobox.ValueMember = "Id"; + } + + private void ExcelReportForm_Load(object sender, EventArgs e) + { + + } + + private void formButton_Click(object sender, EventArgs e) + { + try + { + if (string.IsNullOrWhiteSpace(pathTextbox.Text)) + { + throw new Exception("Отсутствует имя файла для отчета"); + } + + if (productCombobox.SelectedIndex < 0) + { + throw new Exception("Не выбран товар"); + } + + if (dateTimePickerDo.Value <= dateTimePickerOt.Value) + { + throw new Exception("Дата начала должна быть раньше даты окончания"); + } + + if (_container.Resolve().CreateTable(pathTextbox.Text, + (int)productCombobox.SelectedValue!, + dateTimePickerOt.Value, dateTimePickerDo.Value)) + { + MessageBox.Show("Документ сформирован", "Формирование документа", + MessageBoxButtons.OK, + MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах", "Формирование документа", + MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при создании очета", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void pathChoiceButton_Click(object sender, EventArgs e) + { + var sfd = new SaveFileDialog() + { + Filter = "Excel Files | *.xlsx" + }; + + if (sfd.ShowDialog() != DialogResult.OK) + { + return; + } + + pathTextbox.Text = sfd.FileName; + } + } +} diff --git a/CompShop/CompShop/Forms/WordDocReport/ExcelReportForm.resx b/CompShop/CompShop/Forms/WordDocReport/ExcelReportForm.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/CompShop/CompShop/Forms/WordDocReport/ExcelReportForm.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/CompShop/CompShop/Forms/WordDocReport/PdfReportForm.Designer.cs b/CompShop/CompShop/Forms/WordDocReport/PdfReportForm.Designer.cs new file mode 100644 index 0000000..5a06bcd --- /dev/null +++ b/CompShop/CompShop/Forms/WordDocReport/PdfReportForm.Designer.cs @@ -0,0 +1,109 @@ +namespace CompShop.Forms.WordDocReport +{ + partial class PdfReportForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + formButton = new Button(); + fileDialogButton = new Button(); + fileLabel = new Label(); + label1 = new Label(); + dateTimePicker = new DateTimePicker(); + SuspendLayout(); + // + // formButton + // + formButton.Anchor = AnchorStyles.Bottom; + formButton.Location = new Point(106, 138); + formButton.Name = "formButton"; + formButton.Size = new Size(138, 29); + formButton.TabIndex = 30; + formButton.Text = "Формировать"; + formButton.UseVisualStyleBackColor = true; + formButton.Click += formButton_Click; + // + // fileDialogButton + // + fileDialogButton.Location = new Point(41, 23); + fileDialogButton.Name = "fileDialogButton"; + fileDialogButton.Size = new Size(94, 29); + fileDialogButton.TabIndex = 31; + fileDialogButton.Text = "Выбрать"; + fileDialogButton.UseVisualStyleBackColor = true; + fileDialogButton.Click += button1_Click; + // + // fileLabel + // + fileLabel.AutoSize = true; + fileLabel.Location = new Point(141, 28); + fileLabel.Name = "fileLabel"; + fileLabel.Size = new Size(45, 20); + fileLabel.TabIndex = 32; + fileLabel.Text = "Файл"; + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(41, 80); + label1.Name = "label1"; + label1.Size = new Size(44, 20); + label1.TabIndex = 33; + label1.Text = "Дата:"; + // + // dateTimePicker + // + dateTimePicker.Location = new Point(91, 78); + dateTimePicker.Name = "dateTimePicker"; + dateTimePicker.Size = new Size(250, 27); + dateTimePicker.TabIndex = 34; + // + // PdfReportForm + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(362, 179); + Controls.Add(dateTimePicker); + Controls.Add(label1); + Controls.Add(fileLabel); + Controls.Add(fileDialogButton); + Controls.Add(formButton); + Name = "PdfReportForm"; + Text = "PdfReportForm"; + Load += PdfReportForm_Load; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Button formButton; + private Button fileDialogButton; + private Label fileLabel; + private Label label1; + private DateTimePicker dateTimePicker; + } +} \ No newline at end of file diff --git a/CompShop/CompShop/Forms/WordDocReport/PdfReportForm.cs b/CompShop/CompShop/Forms/WordDocReport/PdfReportForm.cs new file mode 100644 index 0000000..3411e7d --- /dev/null +++ b/CompShop/CompShop/Forms/WordDocReport/PdfReportForm.cs @@ -0,0 +1,71 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using Unity; + +namespace CompShop.Forms.WordDocReport +{ + public partial class PdfReportForm : Form + { + private string _fileName = string.Empty; + private readonly IUnityContainer _container; + + public PdfReportForm(IUnityContainer container) + { + InitializeComponent(); + + _container = container ?? throw new ArgumentNullException(nameof(container)); + } + + private void PdfReportForm_Load(object sender, EventArgs e) + { + + } + + private void button1_Click(object sender, EventArgs e) + { + var sfd = new SaveFileDialog() + { + Filter = "Pdf Files | *.pdf" + }; + + if (sfd.ShowDialog() == DialogResult.OK) + { + _fileName = sfd.FileName; + fileLabel.Text = Path.GetFileName(_fileName); + } + } + + private void formButton_Click(object sender, EventArgs e) + { + try + { + if (string.IsNullOrWhiteSpace(_fileName)) + { + throw new Exception("Отсутствует имя файла для отчета"); + } + + if (_container.Resolve().CreateChart(_fileName, dateTimePicker.Value)) + { + MessageBox.Show("Документ сформирован", "Формирование документа", + MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах", + "Формирование документа", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при создании очета", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } +} diff --git a/CompShop/CompShop/Forms/WordDocReport/PdfReportForm.resx b/CompShop/CompShop/Forms/WordDocReport/PdfReportForm.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/CompShop/CompShop/Forms/WordDocReport/PdfReportForm.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/CompShop/CompShop/Repos/IProductOnStorageRepository.cs b/CompShop/CompShop/Repos/IProductOnStorageRepository.cs index 3f36270..3640efe 100644 --- a/CompShop/CompShop/Repos/IProductOnStorageRepository.cs +++ b/CompShop/CompShop/Repos/IProductOnStorageRepository.cs @@ -1,4 +1,10 @@ using CompShop.Entites; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + namespace CompShop.Repos { public interface IProductOnStorageRepository @@ -8,4 +14,4 @@ namespace CompShop.Repos void Create(ProductsOnStorage ps); void Delete(int id); } -} \ No newline at end of file +} diff --git a/CompShop/CompShop/Repos/IStorageRepository.cs b/CompShop/CompShop/Repos/IStorageRepository.cs index 92093bd..927b835 100644 --- a/CompShop/CompShop/Repos/IStorageRepository.cs +++ b/CompShop/CompShop/Repos/IStorageRepository.cs @@ -1,4 +1,9 @@ using CompShop.Entites; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; namespace CompShop.Repos { diff --git a/CompShop/CompShop/Repos/Impements/CheckRepo.cs b/CompShop/CompShop/Repos/Impements/CheckRepo.cs index 48c2cc6..207582f 100644 --- a/CompShop/CompShop/Repos/Impements/CheckRepo.cs +++ b/CompShop/CompShop/Repos/Impements/CheckRepo.cs @@ -21,6 +21,7 @@ namespace CompShop.Repos.Impements _logger = loggerFactory.CreateLogger(); _clientRepository = clientRepository ?? throw new ArgumentNullException(nameof(clientRepository)); } + private IDbConnection CreateConnection() => new NpgsqlConnection(_connectionString.ConnectionString); diff --git a/CompShop/CompShop/Repos/Impements/ProductInCheckRepo.cs b/CompShop/CompShop/Repos/Impements/ProductInCheckRepo.cs index 24a258a..0d42f28 100644 --- a/CompShop/CompShop/Repos/Impements/ProductInCheckRepo.cs +++ b/CompShop/CompShop/Repos/Impements/ProductInCheckRepo.cs @@ -132,4 +132,4 @@ namespace CompShop.Repos.Impements } } } -} \ No newline at end of file +} diff --git a/CompShop/CompShop/Repos/Impements/ProductRepo.cs b/CompShop/CompShop/Repos/Impements/ProductRepo.cs index b5fef52..7f24268 100644 --- a/CompShop/CompShop/Repos/Impements/ProductRepo.cs +++ b/CompShop/CompShop/Repos/Impements/ProductRepo.cs @@ -108,7 +108,7 @@ namespace CompShop.Repos.Impements _logger.LogError(ex, "Ошибка при чтении объектов"); throw; } - + } public Product Update(Product product) diff --git a/CompShop/CompShop/Repos/Impements/ProductsOnStorageRepo.cs b/CompShop/CompShop/Repos/Impements/ProductsOnStorageRepo.cs index 81138df..dd307a4 100644 --- a/CompShop/CompShop/Repos/Impements/ProductsOnStorageRepo.cs +++ b/CompShop/CompShop/Repos/Impements/ProductsOnStorageRepo.cs @@ -134,4 +134,3 @@ namespace CompShop.Repos.Impements } } } - diff --git a/CompShop/CompShop/Repos/Impements/StorageRepo.cs b/CompShop/CompShop/Repos/Impements/StorageRepo.cs index 944abe2..79d44e0 100644 --- a/CompShop/CompShop/Repos/Impements/StorageRepo.cs +++ b/CompShop/CompShop/Repos/Impements/StorageRepo.cs @@ -137,4 +137,4 @@ namespace CompShop.Repos.Impements } } } -} \ No newline at end of file +} -- 2.25.1 From 995ad1931049017b0889d926ea2d433a88919cff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D1=81=D0=B5=D0=BD=D0=B8=D1=8F?= Date: Sun, 15 Dec 2024 10:34:08 +0400 Subject: [PATCH 2/3] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=203=20(=D1=81=D0=BE=20=D0=B2=D1=81=D0=B5=D0=BC=D0=B8=20?= =?UTF-8?q?=D0=B8=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5=D0=BD=D0=B8=D1=8F=D0=BC?= =?UTF-8?q?=D0=B8)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CompShop/DocumentsBuilder/ChartReport.cs | 18 ++++++++-------- .../CompShop/DocumentsBuilder/ExcelBuilder.cs | 21 +++++++++---------- .../CompShop/DocumentsBuilder/PdfBuilder.cs | 4 ---- .../CompShop/DocumentsBuilder/TableReport.cs | 4 ++-- .../CompShop/DocumentsBuilder/WordBuilder.cs | 8 +++---- 5 files changed, 25 insertions(+), 30 deletions(-) diff --git a/CompShop/CompShop/DocumentsBuilder/ChartReport.cs b/CompShop/CompShop/DocumentsBuilder/ChartReport.cs index 163a597..060f1cb 100644 --- a/CompShop/CompShop/DocumentsBuilder/ChartReport.cs +++ b/CompShop/CompShop/DocumentsBuilder/ChartReport.cs @@ -4,8 +4,8 @@ using Microsoft.Extensions.Logging; internal class ChartReport { - private readonly ICheckRepository _checkRepository; // Репозиторий для получения данных о чеках - private readonly IProductRepository _productRepository; // Репозиторий для получения данных о продуктах + private readonly ICheckRepository _checkRepository; + private readonly IProductRepository _productRepository; private readonly ILogger _logger; public ChartReport(ICheckRepository checkRepository, IProductRepository productRepository, ILoggerFactory loggerFactory) @@ -21,7 +21,7 @@ internal class ChartReport { new PdfBuilder(filePath) .AddHeader("Отчет по продажам товаров") - .AddPieChart("Проданные товары", GetData(dateTime)) // Диаграмма с продуктами + .AddPieChart("Проданные товары", GetData(dateTime)) .Build(); return true; @@ -35,17 +35,17 @@ internal class ChartReport private List<(string Caption, double Value)> GetData(DateTime dateTime) { - // Получаем все чеки, которые были оформлены в указанную дату + var checkData = _checkRepository .ReadAll() - .Where(x => x.PurchaseDate.Date == dateTime.Date) // Фильтрация по дате - .SelectMany(x => x.Products) // Получаем все продукты из всех чеков - .GroupBy(p => p.ProductID) // Группируем по ID продукта + .Where(x => x.PurchaseDate.Date == dateTime.Date) + .SelectMany(x => x.Products) + .GroupBy(p => p.ProductID) .Select(g => { - // Получаем продукт по ProductID + var product = _productRepository.Read(g.Key); - return (Caption: product.Name, Value: (double)g.Sum(p => p.Count)); // Преобразуем Count в double + return (Caption: product.Name, Value: (double)g.Sum(p => p.Count)); }) .ToList(); diff --git a/CompShop/CompShop/DocumentsBuilder/ExcelBuilder.cs b/CompShop/CompShop/DocumentsBuilder/ExcelBuilder.cs index b8aac0f..3ebbae9 100644 --- a/CompShop/CompShop/DocumentsBuilder/ExcelBuilder.cs +++ b/CompShop/CompShop/DocumentsBuilder/ExcelBuilder.cs @@ -84,10 +84,10 @@ namespace CompShop.DocumentsBuilder CustomWidth = true })); - // Добавляем строки таблицы + for (int i = 0; i < data.Count; ++i) { - var isBoldRow = i == 0 || i == data.Count - 1; // Только заголовок и последняя строка жирные + var isBoldRow = i == 0 || i == data.Count - 1; var styleIndex = isBoldRow ? StyleIndex.BoldTextWithBorders : StyleIndex.SimpleTextWithBorders; for (int j = 0; j < data[i].Length; ++j) @@ -143,7 +143,6 @@ namespace CompShop.DocumentsBuilder var workbookStylesPart = workbookPart.AddNewPart(); workbookStylesPart.Stylesheet = new Stylesheet(); - // Шрифты var fonts = new Fonts() { Count = 2 }; fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font { @@ -157,16 +156,16 @@ namespace CompShop.DocumentsBuilder FontName = new FontName() { Val = "Calibri" } }); - // Заполнение + var fills = new Fills() { Count = 1 }; fills.Append(new Fill { PatternFill = new PatternFill { PatternType = PatternValues.None } }); - // Границы + var borders = new Borders() { Count = 2 }; - borders.Append(new Border()); // Без границ + borders.Append(new Border()); borders.Append(new Border { LeftBorder = new LeftBorder { Style = BorderStyleValues.Thin }, @@ -175,7 +174,7 @@ namespace CompShop.DocumentsBuilder BottomBorder = new BottomBorder { Style = BorderStyleValues.Thin } }); - // Форматы ячеек + var cellFormats = new CellFormats() { Count = 4 }; cellFormats.Append(new CellFormat { @@ -183,14 +182,14 @@ namespace CompShop.DocumentsBuilder FillId = 0, BorderId = 0, ApplyFont = true - }); // Обычный текст без границ + }); cellFormats.Append(new CellFormat { FontId = 1, FillId = 0, BorderId = 0, ApplyFont = true - }); // Жирный текст без границ + }); cellFormats.Append(new CellFormat { FontId = 0, @@ -198,7 +197,7 @@ namespace CompShop.DocumentsBuilder BorderId = 1, ApplyFont = true, ApplyBorder = true - }); // Обычный текст с границами + }); cellFormats.Append(new CellFormat { FontId = 1, @@ -206,7 +205,7 @@ namespace CompShop.DocumentsBuilder BorderId = 1, ApplyFont = true, ApplyBorder = true - }); // Жирный текст с границами + }); workbookStylesPart.Stylesheet.Append(fonts); workbookStylesPart.Stylesheet.Append(fills); diff --git a/CompShop/CompShop/DocumentsBuilder/PdfBuilder.cs b/CompShop/CompShop/DocumentsBuilder/PdfBuilder.cs index edb7136..73f21e2 100644 --- a/CompShop/CompShop/DocumentsBuilder/PdfBuilder.cs +++ b/CompShop/CompShop/DocumentsBuilder/PdfBuilder.cs @@ -1,10 +1,6 @@ using MigraDoc.DocumentObjectModel; using MigraDoc.DocumentObjectModel.Shapes.Charts; using MigraDoc.Rendering; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Threading.Tasks; using Chart = MigraDoc.DocumentObjectModel.Shapes.Charts.Chart; diff --git a/CompShop/CompShop/DocumentsBuilder/TableReport.cs b/CompShop/CompShop/DocumentsBuilder/TableReport.cs index 938cfb1..03b476b 100644 --- a/CompShop/CompShop/DocumentsBuilder/TableReport.cs +++ b/CompShop/CompShop/DocumentsBuilder/TableReport.cs @@ -38,7 +38,7 @@ internal class TableReport private List GetData(int productId, DateTime startDate, DateTime endDate) { - // Получение данных о чеках, содержащих указанный товар + var checksWithProduct = _checkRepository .ReadAll() .Where(c => c.PurchaseDate >= startDate && c.PurchaseDate <= endDate @@ -53,7 +53,7 @@ internal class TableReport }) .OrderBy(x => x.Date); - // Формирование итоговой таблицы + return new List { Headers } .Union( checksWithProduct.Select(x => new string[] diff --git a/CompShop/CompShop/DocumentsBuilder/WordBuilder.cs b/CompShop/CompShop/DocumentsBuilder/WordBuilder.cs index ba919d3..df01cbe 100644 --- a/CompShop/CompShop/DocumentsBuilder/WordBuilder.cs +++ b/CompShop/CompShop/DocumentsBuilder/WordBuilder.cs @@ -35,12 +35,12 @@ namespace CompShop.DocumentsBuilder var paragraph = _body.AppendChild(new Paragraph()); var run = paragraph.AppendChild(new Run()); - // Добавляем свойства для жирного текста + var runProperties = new RunProperties(); runProperties.AppendChild(new Bold()); run.PrependChild(runProperties); - // Добавляем текст заголовка + run.AppendChild(new Text(header)); return this; @@ -109,7 +109,7 @@ namespace CompShop.DocumentsBuilder ) )); - // Заголовок + var tr = new TableRow(); for (var j = 0; j < widths.Length; ++j) { @@ -124,7 +124,7 @@ namespace CompShop.DocumentsBuilder } table.Append(tr); - // Данные + table.Append(data.Skip(1).Select(x => new TableRow(x.Select(y => new TableCell(new Paragraph(new Run(new Text(y)))))))); -- 2.25.1 From 6e8e5acbd83f4161dc0a9a41049c67f8f5290581 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D1=81=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=90=D0=BD=D0=B4?= =?UTF-8?q?=D1=80=D0=B8=D0=B0=D0=BD=D0=BE=D0=B2=D0=B0?= Date: Sun, 15 Dec 2024 10:41:47 +0400 Subject: [PATCH 3/3] revert 995ad1931049017b0889d926ea2d433a88919cff MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit revert Лабораторная работа 3 (со всеми изменениями) --- .../CompShop/DocumentsBuilder/ChartReport.cs | 18 ++++++++-------- .../CompShop/DocumentsBuilder/ExcelBuilder.cs | 21 ++++++++++--------- .../CompShop/DocumentsBuilder/PdfBuilder.cs | 4 ++++ .../CompShop/DocumentsBuilder/TableReport.cs | 4 ++-- .../CompShop/DocumentsBuilder/WordBuilder.cs | 8 +++---- 5 files changed, 30 insertions(+), 25 deletions(-) diff --git a/CompShop/CompShop/DocumentsBuilder/ChartReport.cs b/CompShop/CompShop/DocumentsBuilder/ChartReport.cs index 060f1cb..163a597 100644 --- a/CompShop/CompShop/DocumentsBuilder/ChartReport.cs +++ b/CompShop/CompShop/DocumentsBuilder/ChartReport.cs @@ -4,8 +4,8 @@ using Microsoft.Extensions.Logging; internal class ChartReport { - private readonly ICheckRepository _checkRepository; - private readonly IProductRepository _productRepository; + private readonly ICheckRepository _checkRepository; // Репозиторий для получения данных о чеках + private readonly IProductRepository _productRepository; // Репозиторий для получения данных о продуктах private readonly ILogger _logger; public ChartReport(ICheckRepository checkRepository, IProductRepository productRepository, ILoggerFactory loggerFactory) @@ -21,7 +21,7 @@ internal class ChartReport { new PdfBuilder(filePath) .AddHeader("Отчет по продажам товаров") - .AddPieChart("Проданные товары", GetData(dateTime)) + .AddPieChart("Проданные товары", GetData(dateTime)) // Диаграмма с продуктами .Build(); return true; @@ -35,17 +35,17 @@ internal class ChartReport private List<(string Caption, double Value)> GetData(DateTime dateTime) { - + // Получаем все чеки, которые были оформлены в указанную дату var checkData = _checkRepository .ReadAll() - .Where(x => x.PurchaseDate.Date == dateTime.Date) - .SelectMany(x => x.Products) - .GroupBy(p => p.ProductID) + .Where(x => x.PurchaseDate.Date == dateTime.Date) // Фильтрация по дате + .SelectMany(x => x.Products) // Получаем все продукты из всех чеков + .GroupBy(p => p.ProductID) // Группируем по ID продукта .Select(g => { - + // Получаем продукт по ProductID var product = _productRepository.Read(g.Key); - return (Caption: product.Name, Value: (double)g.Sum(p => p.Count)); + return (Caption: product.Name, Value: (double)g.Sum(p => p.Count)); // Преобразуем Count в double }) .ToList(); diff --git a/CompShop/CompShop/DocumentsBuilder/ExcelBuilder.cs b/CompShop/CompShop/DocumentsBuilder/ExcelBuilder.cs index 3ebbae9..b8aac0f 100644 --- a/CompShop/CompShop/DocumentsBuilder/ExcelBuilder.cs +++ b/CompShop/CompShop/DocumentsBuilder/ExcelBuilder.cs @@ -84,10 +84,10 @@ namespace CompShop.DocumentsBuilder CustomWidth = true })); - + // Добавляем строки таблицы for (int i = 0; i < data.Count; ++i) { - var isBoldRow = i == 0 || i == data.Count - 1; + var isBoldRow = i == 0 || i == data.Count - 1; // Только заголовок и последняя строка жирные var styleIndex = isBoldRow ? StyleIndex.BoldTextWithBorders : StyleIndex.SimpleTextWithBorders; for (int j = 0; j < data[i].Length; ++j) @@ -143,6 +143,7 @@ namespace CompShop.DocumentsBuilder var workbookStylesPart = workbookPart.AddNewPart(); workbookStylesPart.Stylesheet = new Stylesheet(); + // Шрифты var fonts = new Fonts() { Count = 2 }; fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font { @@ -156,16 +157,16 @@ namespace CompShop.DocumentsBuilder FontName = new FontName() { Val = "Calibri" } }); - + // Заполнение var fills = new Fills() { Count = 1 }; fills.Append(new Fill { PatternFill = new PatternFill { PatternType = PatternValues.None } }); - + // Границы var borders = new Borders() { Count = 2 }; - borders.Append(new Border()); + borders.Append(new Border()); // Без границ borders.Append(new Border { LeftBorder = new LeftBorder { Style = BorderStyleValues.Thin }, @@ -174,7 +175,7 @@ namespace CompShop.DocumentsBuilder BottomBorder = new BottomBorder { Style = BorderStyleValues.Thin } }); - + // Форматы ячеек var cellFormats = new CellFormats() { Count = 4 }; cellFormats.Append(new CellFormat { @@ -182,14 +183,14 @@ namespace CompShop.DocumentsBuilder FillId = 0, BorderId = 0, ApplyFont = true - }); + }); // Обычный текст без границ cellFormats.Append(new CellFormat { FontId = 1, FillId = 0, BorderId = 0, ApplyFont = true - }); + }); // Жирный текст без границ cellFormats.Append(new CellFormat { FontId = 0, @@ -197,7 +198,7 @@ namespace CompShop.DocumentsBuilder BorderId = 1, ApplyFont = true, ApplyBorder = true - }); + }); // Обычный текст с границами cellFormats.Append(new CellFormat { FontId = 1, @@ -205,7 +206,7 @@ namespace CompShop.DocumentsBuilder BorderId = 1, ApplyFont = true, ApplyBorder = true - }); + }); // Жирный текст с границами workbookStylesPart.Stylesheet.Append(fonts); workbookStylesPart.Stylesheet.Append(fills); diff --git a/CompShop/CompShop/DocumentsBuilder/PdfBuilder.cs b/CompShop/CompShop/DocumentsBuilder/PdfBuilder.cs index 73f21e2..edb7136 100644 --- a/CompShop/CompShop/DocumentsBuilder/PdfBuilder.cs +++ b/CompShop/CompShop/DocumentsBuilder/PdfBuilder.cs @@ -1,6 +1,10 @@ using MigraDoc.DocumentObjectModel; using MigraDoc.DocumentObjectModel.Shapes.Charts; using MigraDoc.Rendering; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; using System.Threading.Tasks; using Chart = MigraDoc.DocumentObjectModel.Shapes.Charts.Chart; diff --git a/CompShop/CompShop/DocumentsBuilder/TableReport.cs b/CompShop/CompShop/DocumentsBuilder/TableReport.cs index 03b476b..938cfb1 100644 --- a/CompShop/CompShop/DocumentsBuilder/TableReport.cs +++ b/CompShop/CompShop/DocumentsBuilder/TableReport.cs @@ -38,7 +38,7 @@ internal class TableReport private List GetData(int productId, DateTime startDate, DateTime endDate) { - + // Получение данных о чеках, содержащих указанный товар var checksWithProduct = _checkRepository .ReadAll() .Where(c => c.PurchaseDate >= startDate && c.PurchaseDate <= endDate @@ -53,7 +53,7 @@ internal class TableReport }) .OrderBy(x => x.Date); - + // Формирование итоговой таблицы return new List { Headers } .Union( checksWithProduct.Select(x => new string[] diff --git a/CompShop/CompShop/DocumentsBuilder/WordBuilder.cs b/CompShop/CompShop/DocumentsBuilder/WordBuilder.cs index df01cbe..ba919d3 100644 --- a/CompShop/CompShop/DocumentsBuilder/WordBuilder.cs +++ b/CompShop/CompShop/DocumentsBuilder/WordBuilder.cs @@ -35,12 +35,12 @@ namespace CompShop.DocumentsBuilder var paragraph = _body.AppendChild(new Paragraph()); var run = paragraph.AppendChild(new Run()); - + // Добавляем свойства для жирного текста var runProperties = new RunProperties(); runProperties.AppendChild(new Bold()); run.PrependChild(runProperties); - + // Добавляем текст заголовка run.AppendChild(new Text(header)); return this; @@ -109,7 +109,7 @@ namespace CompShop.DocumentsBuilder ) )); - + // Заголовок var tr = new TableRow(); for (var j = 0; j < widths.Length; ++j) { @@ -124,7 +124,7 @@ namespace CompShop.DocumentsBuilder } table.Append(tr); - + // Данные table.Append(data.Skip(1).Select(x => new TableRow(x.Select(y => new TableCell(new Paragraph(new Run(new Text(y)))))))); -- 2.25.1