From 81d1463e37169e0b70f03c6aa99761cd26b4dcb4 Mon Sep 17 00:00:00 2001 From: Yourdax Date: Mon, 27 May 2024 01:13:11 +0400 Subject: [PATCH] =?UTF-8?q?+=D0=BE=D1=82=D1=87=D0=B5=D1=82=20excel?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BusinessLogic/ReportLogic.cs | 36 ++- .../OfficePackage/AbstractSaveToExcel.cs | 117 +++++++ .../OfficePackage/AbstractSaveToPdf.cs | 69 ++++ .../OfficePackage/AbstractSaveToWord.cs | 59 ++++ .../HelperEnums/ExcelStyleInfoType.cs | 11 + .../HelperEnums/PdfParagraphAlignmentType.cs | 11 + .../HelperEnums/WordJustificationType.cs | 9 + .../HelperModels/ExcelCellParameters.cs | 17 + .../OfficePackage/HelperModels/ExcelInfo.cs | 13 + .../HelperModels/ExcelMergeParameters.cs | 11 + .../OfficePackage/HelperModels/PdfInfo.cs | 17 + .../HelperModels/PdfParagraph.cs | 13 + .../HelperModels/PdfRowParameters.cs | 13 + .../OfficePackage/HelperModels/WordInfo.cs | 13 + .../HelperModels/WordParagraph.cs | 9 + .../HelperModels/WordTextProperties.cs | 13 + .../OfficePackage/Implements/SaveToExcel.cs | 294 ++++++++++++++++++ .../OfficePackage/Implements/SaveToPdf.cs | 114 +++++++ .../OfficePackage/Implements/SaveToWord.cs | 135 ++++++++ .../BusinessLogicContracts/IReportLogic.cs | 2 +- .../ReportComponentOrderViewModel.cs | 15 +- .../ViewModels/ReportOrdersViewModel.cs | 16 + .../Implements/ComponentStorage.cs | 31 +- .../DiningRoomView/DiningRoomView.csproj | 1 + .../FormComponentSelection.Designer.cs | 74 +++++ .../DiningRoomView/FormComponentSelection.cs | 90 ++++++ ...nents.resx => FormComponentSelection.resx} | 50 +-- .../DiningRoomView/FormMain.Designer.cs | 37 ++- DiningRoom/DiningRoomView/FormMain.cs | 14 + .../FormReportOrders.Designer.cs | 141 --------- DiningRoom/DiningRoomView/FormReportOrders.cs | 101 ------ .../FormReportProductComponents.Designer.cs | 113 +++++++ .../FormReportProductComponents.cs | 121 +++++++ ....resx => FormReportProductComponents.resx} | 50 +-- .../FormReportWoodComponents.Designer.cs | 114 ------- .../FormReportWoodComponents.cs | 79 ----- DiningRoom/DiningRoomView/Program.cs | 10 +- 37 files changed, 1511 insertions(+), 522 deletions(-) create mode 100644 DiningRoom/DiningRoomBusinessLogic/OfficePackage/AbstractSaveToExcel.cs create mode 100644 DiningRoom/DiningRoomBusinessLogic/OfficePackage/AbstractSaveToPdf.cs create mode 100644 DiningRoom/DiningRoomBusinessLogic/OfficePackage/AbstractSaveToWord.cs create mode 100644 DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperEnums/ExcelStyleInfoType.cs create mode 100644 DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperEnums/PdfParagraphAlignmentType.cs create mode 100644 DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperEnums/WordJustificationType.cs create mode 100644 DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/ExcelCellParameters.cs create mode 100644 DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs create mode 100644 DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/ExcelMergeParameters.cs create mode 100644 DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs create mode 100644 DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/PdfParagraph.cs create mode 100644 DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/PdfRowParameters.cs create mode 100644 DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/WordInfo.cs create mode 100644 DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/WordParagraph.cs create mode 100644 DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/WordTextProperties.cs create mode 100644 DiningRoom/DiningRoomBusinessLogic/OfficePackage/Implements/SaveToExcel.cs create mode 100644 DiningRoom/DiningRoomBusinessLogic/OfficePackage/Implements/SaveToPdf.cs create mode 100644 DiningRoom/DiningRoomBusinessLogic/OfficePackage/Implements/SaveToWord.cs create mode 100644 DiningRoom/DiningRoomContracts/ViewModels/ReportOrdersViewModel.cs create mode 100644 DiningRoom/DiningRoomView/FormComponentSelection.Designer.cs create mode 100644 DiningRoom/DiningRoomView/FormComponentSelection.cs rename DiningRoom/DiningRoomView/{FormReportWoodComponents.resx => FormComponentSelection.resx} (93%) delete mode 100644 DiningRoom/DiningRoomView/FormReportOrders.Designer.cs delete mode 100644 DiningRoom/DiningRoomView/FormReportOrders.cs create mode 100644 DiningRoom/DiningRoomView/FormReportProductComponents.Designer.cs create mode 100644 DiningRoom/DiningRoomView/FormReportProductComponents.cs rename DiningRoom/DiningRoomView/{FormReportOrders.resx => FormReportProductComponents.resx} (93%) delete mode 100644 DiningRoom/DiningRoomView/FormReportWoodComponents.Designer.cs delete mode 100644 DiningRoom/DiningRoomView/FormReportWoodComponents.cs diff --git a/DiningRoom/DiningRoomBusinessLogic/BusinessLogic/ReportLogic.cs b/DiningRoom/DiningRoomBusinessLogic/BusinessLogic/ReportLogic.cs index 0d14093..430e28e 100644 --- a/DiningRoom/DiningRoomBusinessLogic/BusinessLogic/ReportLogic.cs +++ b/DiningRoom/DiningRoomBusinessLogic/BusinessLogic/ReportLogic.cs @@ -1,19 +1,32 @@ -using DiningRoomContracts.BindingModels; +using DiningRoomBusinessLogic.OfficePackage; +using DiningRoomBusinessLogic.OfficePackage.HelperModels; +using DiningRoomBusinessLogic.OfficePackage.Implements; +using DiningRoomContracts.BindingModels; using DiningRoomContracts.BusinessLogicContracts; using DiningRoomContracts.SearchModels; using DiningRoomContracts.StorageContracts; using DiningRoomContracts.ViewModels; +using DocumentFormat.OpenXml.EMMA; namespace DiningRoomBusinessLogic.BusinessLogic { public class ReportLogic : IReportLogic { - private readonly IComponentStorage _componentStorage; + private readonly AbstractSaveToExcel _saveToExcel; - public ReportLogic(IComponentStorage ComponentStorage) + private readonly AbstractSaveToWord _saveToWord; + + private readonly AbstractSaveToPdf _saveToPdf; + + private readonly IComponentStorage _componentStorage; + + public ReportLogic(IComponentStorage ComponentStorage, AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf) { _componentStorage = ComponentStorage; - } + _saveToExcel = saveToExcel; + _saveToWord = saveToWord; + _saveToPdf = saveToPdf; + } public List GetReportComponentsWithOrders(List SelectedComponents) { @@ -26,13 +39,18 @@ namespace DiningRoomBusinessLogic.BusinessLogic } public void SaveReportToWordFile(ReportBindingModel Model) - { + { throw new NotImplementedException(); - } + } - public void SaveReportToExcelFile(ReportBindingModel Model) + public void SaveReportToExcelFile(ReportBindingModel Model, List selectedComponents) { - throw new NotImplementedException(); - } + _saveToExcel.CreateReport(new ExcelInfo + { + FileName = Model.FileName, + Title = "Список изделий", + ProductComponents = GetReportComponentsWithOrders(selectedComponents) + }); + } } } diff --git a/DiningRoom/DiningRoomBusinessLogic/OfficePackage/AbstractSaveToExcel.cs b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/AbstractSaveToExcel.cs new file mode 100644 index 0000000..b2908c4 --- /dev/null +++ b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/AbstractSaveToExcel.cs @@ -0,0 +1,117 @@ +using DiningRoomBusinessLogic.OfficePackage.HelperEnums; +using DiningRoomBusinessLogic.OfficePackage.HelperModels; +using DiningRoomContracts.ViewModels; +using DocumentFormat.OpenXml.Spreadsheet; + +namespace DiningRoomBusinessLogic.OfficePackage +{ + public abstract class AbstractSaveToExcel + { + /// + /// Создание отчета + /// + /// + public void CreateReport(ExcelInfo info) + { + CreateExcel(info); + + // Добавляем заголовок + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = 1, + Text = "Продукт", + StyleInfo = ExcelStyleInfoType.Title + }); + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = 1, + Text = "Имя заказа", + StyleInfo = ExcelStyleInfoType.Title + }); + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = 1, + Text = "Количество блюд в заказе", + StyleInfo = ExcelStyleInfoType.Title + }); + + uint rowIndex = 2; + + // Группируем компоненты по названию + var groupedComponents = info.ProductComponents + .GroupBy(item => item.ComponentName) + .ToList(); + + // Перебираем данные и добавляем их в Excel + foreach (var group in groupedComponents) + { + // Добавляем строку для названия компонента + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = group.Key, // Название компонента + StyleInfo = ExcelStyleInfoType.Text + }); + rowIndex++; + + // Перебираем заказы внутри группы компонентов + foreach (var item in group) + { + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = rowIndex, + Text = item.OrderName, + StyleInfo = ExcelStyleInfoType.TextWithBroder + }); + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = item.ProductCount.ToString(), + StyleInfo = ExcelStyleInfoType.TextWithBroder + }); + + rowIndex++; + } + + rowIndex++; + } + + SaveExcel(info); + } + + + + /// + /// Создание excel-файла + /// + /// + protected abstract void CreateExcel(ExcelInfo info); + + /// + /// Добавляем новую ячейку в лист + /// + /// + protected abstract void InsertCellInWorksheet(ExcelCellParameters excelParams); + + /// + /// Объединение ячеек + /// + /// + protected abstract void MergeCells(ExcelMergeParameters excelParams); + + /// + /// Сохранение файла + /// + /// + protected abstract void SaveExcel(ExcelInfo info); + } +} \ No newline at end of file diff --git a/DiningRoom/DiningRoomBusinessLogic/OfficePackage/AbstractSaveToPdf.cs b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/AbstractSaveToPdf.cs new file mode 100644 index 0000000..babca61 --- /dev/null +++ b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/AbstractSaveToPdf.cs @@ -0,0 +1,69 @@ +using DiningRoomBusinessLogic.OfficePackage.HelperEnums; +using DiningRoomBusinessLogic.OfficePackage.HelperModels; + +namespace DiningRoomBusinessLogic.OfficePackage +{ + public abstract class AbstractSaveToPdf + { + public void CreateDoc(PdfInfo info) + { + CreatePdf(info); + CreateParagraph(new PdfParagraph { Text = info.Title, Style = "NormalTitle", ParagraphAlignment = PdfParagraphAlignmentType.Center }); + CreateParagraph(new PdfParagraph { Text = $"с {info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center }); + + CreateTable(new List { "2cm", "3cm", "6cm", "6cm", "3cm" }); + + CreateRow(new PdfRowParameters + { + Texts = new List { "Номер", "Дата заказа", "Изделие", "Статус", "Сумма" }, + Style = "NormalTitle", + ParagraphAlignment = PdfParagraphAlignmentType.Center + }); + + foreach (var order in info.Orders) + { + CreateRow(new PdfRowParameters + { + Texts = new List { order.Id.ToString(), order.DateCreate.ToShortDateString(), order.ProductName, order.Status.ToString(), order.Sum.ToString() }, + Style = "Normal", + ParagraphAlignment = PdfParagraphAlignmentType.Left + }); + } + CreateParagraph(new PdfParagraph { Text = $"Итого: {info.Orders.Sum(x => x.Sum)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Right }); + + SavePdf(info); + } + + /// + /// Создание doc-файла + /// + /// + protected abstract void CreatePdf(PdfInfo info); + + /// + /// Создание параграфа с текстом + /// + /// + /// + protected abstract void CreateParagraph(PdfParagraph paragraph); + + /// + /// Создание таблицы + /// + /// + /// + protected abstract void CreateTable(List columns); + + /// + /// Создание и заполнение строки + /// + /// + protected abstract void CreateRow(PdfRowParameters rowParameters); + + /// + /// Сохранение файла + /// + /// + protected abstract void SavePdf(PdfInfo info); + } +} diff --git a/DiningRoom/DiningRoomBusinessLogic/OfficePackage/AbstractSaveToWord.cs b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/AbstractSaveToWord.cs new file mode 100644 index 0000000..3d38d8d --- /dev/null +++ b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/AbstractSaveToWord.cs @@ -0,0 +1,59 @@ +using DiningRoomBusinessLogic.OfficePackage.HelperEnums; +using DiningRoomBusinessLogic.OfficePackage.HelperModels; + +namespace DiningRoomBusinessLogic.OfficePackage +{ + public abstract class AbstractSaveToWord + { + public void CreateDoc(WordInfo info) + { + CreateWord(info); + + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24", }) }, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Center + } + }); + + foreach (var product in info.Products) + { + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { + (product.ProductName + ": ", new WordTextProperties { Size = "24", Bold = true }), + (Convert.ToInt32(product.Cost).ToString(), new WordTextProperties { Size = "24", })}, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Both + } + }); + } + + SaveWord(info); + } + + /// + /// Создание doc-файла + /// + /// + protected abstract void CreateWord(WordInfo info); + + /// + /// Создание абзаца с текстом + /// + /// + /// + protected abstract void CreateParagraph(WordParagraph paragraph); + + /// + /// Сохранение файла + /// + /// + protected abstract void SaveWord(WordInfo info); + } +} \ No newline at end of file diff --git a/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperEnums/ExcelStyleInfoType.cs b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperEnums/ExcelStyleInfoType.cs new file mode 100644 index 0000000..2a577c5 --- /dev/null +++ b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperEnums/ExcelStyleInfoType.cs @@ -0,0 +1,11 @@ +namespace DiningRoomBusinessLogic.OfficePackage.HelperEnums +{ + public enum ExcelStyleInfoType + { + Title, + + Text, + + TextWithBroder + } +} \ No newline at end of file diff --git a/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperEnums/PdfParagraphAlignmentType.cs b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperEnums/PdfParagraphAlignmentType.cs new file mode 100644 index 0000000..093a995 --- /dev/null +++ b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperEnums/PdfParagraphAlignmentType.cs @@ -0,0 +1,11 @@ +namespace DiningRoomBusinessLogic.OfficePackage.HelperEnums +{ + public enum PdfParagraphAlignmentType + { + Center, + + Left, + + Right + } +} \ No newline at end of file diff --git a/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperEnums/WordJustificationType.cs b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperEnums/WordJustificationType.cs new file mode 100644 index 0000000..4cf57da --- /dev/null +++ b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperEnums/WordJustificationType.cs @@ -0,0 +1,9 @@ +namespace DiningRoomBusinessLogic.OfficePackage.HelperEnums +{ + public enum WordJustificationType + { + Center, + + Both + } +} \ No newline at end of file diff --git a/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/ExcelCellParameters.cs b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/ExcelCellParameters.cs new file mode 100644 index 0000000..9df24e7 --- /dev/null +++ b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/ExcelCellParameters.cs @@ -0,0 +1,17 @@ +using DiningRoomBusinessLogic.OfficePackage.HelperEnums; + +namespace DiningRoomBusinessLogic.OfficePackage.HelperModels +{ + public class ExcelCellParameters + { + public string ColumnName { get; set; } = string.Empty; + + public uint RowIndex { get; set; } + + public string Text { get; set; } = string.Empty; + + public string CellReference => $"{ColumnName}{RowIndex}"; + + public ExcelStyleInfoType StyleInfo { get; set; } + } +} \ No newline at end of file diff --git a/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs new file mode 100644 index 0000000..775ee75 --- /dev/null +++ b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs @@ -0,0 +1,13 @@ +using DiningRoomContracts.ViewModels; + +namespace DiningRoomBusinessLogic.OfficePackage.HelperModels +{ + public class ExcelInfo + { + public string FileName { get; set; } = string.Empty; + + public string Title { get; set; } = string.Empty; + + public List ProductComponents { get; set; } = new(); + } +} \ No newline at end of file diff --git a/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/ExcelMergeParameters.cs b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/ExcelMergeParameters.cs new file mode 100644 index 0000000..9df1bb0 --- /dev/null +++ b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/ExcelMergeParameters.cs @@ -0,0 +1,11 @@ +namespace DiningRoomBusinessLogic.OfficePackage.HelperModels +{ + public class ExcelMergeParameters + { + public string CellFromName { get; set; } = string.Empty; + + public string CellToName { get; set; } = string.Empty; + + public string Merge => $"{CellFromName}:{CellToName}"; + } +} \ No newline at end of file diff --git a/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs new file mode 100644 index 0000000..1360633 --- /dev/null +++ b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs @@ -0,0 +1,17 @@ +using DiningRoomContracts.ViewModels; + +namespace DiningRoomBusinessLogic.OfficePackage.HelperModels +{ + public class PdfInfo + { + public string FileName { get; set; } = string.Empty; + + public string Title { get; set; } = string.Empty; + + public DateTime DateFrom { get; set; } + + public DateTime DateTo { get; set; } + + public List Orders { get; set; } = new(); + } +} \ No newline at end of file diff --git a/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/PdfParagraph.cs b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/PdfParagraph.cs new file mode 100644 index 0000000..35871a7 --- /dev/null +++ b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/PdfParagraph.cs @@ -0,0 +1,13 @@ +using DiningRoomBusinessLogic.OfficePackage.HelperEnums; + +namespace DiningRoomBusinessLogic.OfficePackage.HelperModels +{ + public class PdfParagraph + { + public string Text { get; set; } = string.Empty; + + public string Style { get; set; } = string.Empty; + + public PdfParagraphAlignmentType ParagraphAlignment { get; set; } + } +} \ No newline at end of file diff --git a/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/PdfRowParameters.cs b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/PdfRowParameters.cs new file mode 100644 index 0000000..3da149c --- /dev/null +++ b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/PdfRowParameters.cs @@ -0,0 +1,13 @@ +using DiningRoomBusinessLogic.OfficePackage.HelperEnums; + +namespace DiningRoomBusinessLogic.OfficePackage.HelperModels +{ + public class PdfRowParameters + { + public List Texts { get; set; } = new(); + + public string Style { get; set; } = string.Empty; + + public PdfParagraphAlignmentType ParagraphAlignment { get; set; } + } +} \ No newline at end of file diff --git a/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/WordInfo.cs b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/WordInfo.cs new file mode 100644 index 0000000..f7b2e50 --- /dev/null +++ b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/WordInfo.cs @@ -0,0 +1,13 @@ +using DiningRoomContracts.ViewModels; + +namespace DiningRoomBusinessLogic.OfficePackage.HelperModels +{ + public class WordInfo + { + public string FileName { get; set; } = string.Empty; + + public string Title { get; set; } = string.Empty; + + public List Products { get; set; } = new(); + } +} \ No newline at end of file diff --git a/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/WordParagraph.cs b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/WordParagraph.cs new file mode 100644 index 0000000..cf4c64a --- /dev/null +++ b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/WordParagraph.cs @@ -0,0 +1,9 @@ +namespace DiningRoomBusinessLogic.OfficePackage.HelperModels +{ + public class WordParagraph + { + public List<(string, WordTextProperties)> Texts { get; set; } = new(); + + public WordTextProperties? TextProperties { get; set; } + } +} \ No newline at end of file diff --git a/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/WordTextProperties.cs b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/WordTextProperties.cs new file mode 100644 index 0000000..5032788 --- /dev/null +++ b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/WordTextProperties.cs @@ -0,0 +1,13 @@ +using DiningRoomBusinessLogic.OfficePackage.HelperEnums; + +namespace DiningRoomBusinessLogic.OfficePackage.HelperModels +{ + public class WordTextProperties + { + public string Size { get; set; } = string.Empty; + + public bool Bold { get; set; } + + public WordJustificationType JustificationType { get; set; } + } +} diff --git a/DiningRoom/DiningRoomBusinessLogic/OfficePackage/Implements/SaveToExcel.cs b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/Implements/SaveToExcel.cs new file mode 100644 index 0000000..4f9302c --- /dev/null +++ b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/Implements/SaveToExcel.cs @@ -0,0 +1,294 @@ +using DiningRoomBusinessLogic.OfficePackage.HelperEnums; +using DiningRoomBusinessLogic.OfficePackage.HelperModels; +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Office2010.Excel; +using DocumentFormat.OpenXml.Office2013.Excel; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Spreadsheet; + +namespace DiningRoomBusinessLogic.OfficePackage.Implements +{ + public class SaveToExcel : AbstractSaveToExcel + { + private SpreadsheetDocument? _spreadsheetDocument; + + private SharedStringTablePart? _shareStringPart; + + private Worksheet? _worksheet; + + /// + /// Настройка стилей для файла + /// + /// + private static void CreateStyles(WorkbookPart workbookpart) + { + var sp = workbookpart.AddNewPart(); + sp.Stylesheet = new Stylesheet(); + + var fonts = new Fonts() { Count = 2U, KnownFonts = true }; + + var fontUsual = new Font(); + fontUsual.Append(new FontSize() { Val = 12D }); + fontUsual.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Theme = 1U }); + fontUsual.Append(new FontName() { Val = "Times New Roman" }); + fontUsual.Append(new FontFamilyNumbering() { Val = 2 }); + fontUsual.Append(new FontScheme() { Val = FontSchemeValues.Minor }); + + var fontTitle = new Font(); + fontTitle.Append(new Bold()); + fontTitle.Append(new FontSize() { Val = 14D }); + fontTitle.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Theme = 1U }); + fontTitle.Append(new FontName() { Val = "Times New Roman" }); + fontTitle.Append(new FontFamilyNumbering() { Val = 2 }); + fontTitle.Append(new FontScheme() { Val = FontSchemeValues.Minor }); + + fonts.Append(fontUsual); + fonts.Append(fontTitle); + + var fills = new Fills() { Count = 2U }; + + var fill1 = new Fill(); + fill1.Append(new PatternFill() { PatternType = PatternValues.None }); + + var fill2 = new Fill(); + fill2.Append(new PatternFill() { PatternType = PatternValues.Gray125 }); + + fills.Append(fill1); + fills.Append(fill2); + + var borders = new Borders() { Count = 2U }; + + var borderNoBorder = new Border(); + borderNoBorder.Append(new LeftBorder()); + borderNoBorder.Append(new RightBorder()); + borderNoBorder.Append(new TopBorder()); + borderNoBorder.Append(new BottomBorder()); + borderNoBorder.Append(new DiagonalBorder()); + + var borderThin = new Border(); + + var leftBorder = new LeftBorder() { Style = BorderStyleValues.Thin }; + leftBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U }); + + var rightBorder = new RightBorder() { Style = BorderStyleValues.Thin }; + rightBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U }); + + var topBorder = new TopBorder() { Style = BorderStyleValues.Thin }; + topBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U }); + + var bottomBorder = new BottomBorder() { Style = BorderStyleValues.Thin }; + bottomBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U }); + + borderThin.Append(leftBorder); + borderThin.Append(rightBorder); + borderThin.Append(topBorder); + borderThin.Append(bottomBorder); + borderThin.Append(new DiagonalBorder()); + + borders.Append(borderNoBorder); + borders.Append(borderThin); + + var cellStyleFormats = new CellStyleFormats() { + Count = 1U + }; + var cellFormatStyle = new CellFormat() { NumberFormatId = 0U, FontId = 0U, FillId = 0U, BorderId = 0U }; + + cellStyleFormats.Append(cellFormatStyle); + + var cellFormats = new CellFormats() { Count = 3U }; + var cellFormatFont = new CellFormat() { NumberFormatId = 0U, FontId = 0U, FillId = 0U, BorderId = 0U, FormatId = 0U, ApplyFont = true }; + var cellFormatFontAndBorder = new CellFormat() { NumberFormatId = 0U, FontId = 0U, FillId = 0U, BorderId = 1U, FormatId = 0U, ApplyFont = true, ApplyBorder = true }; + var cellFormatTitle = new CellFormat() { NumberFormatId = 0U, FontId = 1U, FillId = 0U, BorderId = 0U, FormatId = 0U, Alignment = new Alignment() { Vertical = VerticalAlignmentValues.Center, WrapText = true, Horizontal = HorizontalAlignmentValues.Center }, ApplyFont = true }; + + cellFormats.Append(cellFormatFont); + cellFormats.Append(cellFormatFontAndBorder); + cellFormats.Append(cellFormatTitle); + + var cellStyles = new CellStyles() { Count = 1U }; + + cellStyles.Append(new CellStyle() { Name = "Normal", FormatId = 0U, BuiltinId = 0U }); + + var differentialFormats = new DocumentFormat.OpenXml.Office2013.Excel.DifferentialFormats() { Count = 0U }; + + var tableStyles = new TableStyles() { Count = 0U, DefaultTableStyle = "TableStyleMedium2", DefaultPivotStyle = "PivotStyleLight16" }; + + var stylesheetExtensionList = new StylesheetExtensionList(); + + var stylesheetExtension1 = new StylesheetExtension() { Uri = "{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}" }; + stylesheetExtension1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"); + stylesheetExtension1.Append(new SlicerStyles() { DefaultSlicerStyle = "SlicerStyleLight1" }); + + var stylesheetExtension2 = new StylesheetExtension() { Uri = "{9260A510-F301-46a8-8635-F512D64BE5F5}" }; + stylesheetExtension2.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"); + stylesheetExtension2.Append(new TimelineStyles() { DefaultTimelineStyle = "TimeSlicerStyleLight1" }); + + stylesheetExtensionList.Append(stylesheetExtension1); + stylesheetExtensionList.Append(stylesheetExtension2); + + sp.Stylesheet.Append(fonts); + sp.Stylesheet.Append(fills); + sp.Stylesheet.Append(borders); + sp.Stylesheet.Append(cellStyleFormats); + sp.Stylesheet.Append(cellFormats); + sp.Stylesheet.Append(cellStyles); + sp.Stylesheet.Append(differentialFormats); + sp.Stylesheet.Append(tableStyles); + sp.Stylesheet.Append(stylesheetExtensionList); + } + + /// + /// Получение номера стиля из типа + /// + /// + /// + private static uint GetStyleValue(ExcelStyleInfoType styleInfo) + { + return styleInfo switch + { + ExcelStyleInfoType.Title => 2U, + ExcelStyleInfoType.TextWithBroder => 1U, + ExcelStyleInfoType.Text => 0U, + _ => 0U, + }; + } + + protected override void CreateExcel(ExcelInfo info) + { + _spreadsheetDocument = SpreadsheetDocument.Create(info.FileName, SpreadsheetDocumentType.Workbook); + // Создаем книгу (в ней хранятся листы) + var workbookpart = _spreadsheetDocument.AddWorkbookPart(); + workbookpart.Workbook = new Workbook(); + + CreateStyles(workbookpart); + + // Получаем/создаем хранилище текстов для книги + _shareStringPart = _spreadsheetDocument.WorkbookPart!.GetPartsOfType().Any() + ? _spreadsheetDocument.WorkbookPart.GetPartsOfType().First() + : _spreadsheetDocument.WorkbookPart.AddNewPart(); + + // Создаем SharedStringTable, если его нет + if (_shareStringPart.SharedStringTable == null) + { + _shareStringPart.SharedStringTable = new SharedStringTable(); + } + + // Создаем лист в книгу + var worksheetPart = workbookpart.AddNewPart(); + worksheetPart.Worksheet = new Worksheet(new SheetData()); + + // Добавляем лист в книгу + var sheets = _spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets()); + var sheet = new Sheet() + { + Id = _spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), + SheetId = 1, + Name = "Лист" + }; + sheets.Append(sheet); + + _worksheet = worksheetPart.Worksheet; + } + + protected override void InsertCellInWorksheet(ExcelCellParameters excelParams) + { + if (_worksheet == null || _shareStringPart == null) + { + return; + } + var sheetData = _worksheet.GetFirstChild(); + if (sheetData == null) + { + return; + } + + // Ищем строку, либо добавляем ее + Row row; + if (sheetData.Elements().Where(r => r.RowIndex! == excelParams.RowIndex).Any()) + { + row = sheetData.Elements().Where(r => r.RowIndex! == excelParams.RowIndex).First(); + } + else + { + row = new Row() { RowIndex = excelParams.RowIndex }; + sheetData.Append(row); + } + + // Ищем нужную ячейку + Cell cell; + if (row.Elements().Where(c => c.CellReference!.Value == excelParams.CellReference).Any()) + { + cell = row.Elements().Where(c => c.CellReference!.Value == excelParams.CellReference).First(); + } + else + { + // Все ячейки должны быть последовательно друг за другом расположены + // нужно определить, после какой вставлять + Cell? refCell = null; + foreach (Cell rowCell in row.Elements()) + { + if (string.Compare(rowCell.CellReference!.Value, excelParams.CellReference, true) > 0) + { + refCell = rowCell; + break; + } + } + + var newCell = new Cell() { CellReference = excelParams.CellReference }; + row.InsertBefore(newCell, refCell); + + cell = newCell; + } + + // вставляем новый текст + _shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new Text(excelParams.Text))); + _shareStringPart.SharedStringTable.Save(); + + cell.CellValue = new CellValue((_shareStringPart.SharedStringTable.Elements().Count() - 1).ToString()); + cell.DataType = new EnumValue(CellValues.SharedString); + cell.StyleIndex = GetStyleValue(excelParams.StyleInfo); + } + + protected override void MergeCells(ExcelMergeParameters excelParams) + { + if (_worksheet == null) + { + return; + } + MergeCells mergeCells; + + if (_worksheet.Elements().Any()) + { + mergeCells = _worksheet.Elements().First(); + } + else + { + mergeCells = new MergeCells(); + + if (_worksheet.Elements().Any()) + { + _worksheet.InsertAfter(mergeCells, _worksheet.Elements().First()); + } + else + { + _worksheet.InsertAfter(mergeCells, _worksheet.Elements().First()); + } + } + + var mergeCell = new MergeCell() + { + Reference = new StringValue(excelParams.Merge) + }; + mergeCells.Append(mergeCell); + } + + protected override void SaveExcel(ExcelInfo info) + { + if (_spreadsheetDocument == null) + { + return; + } + _spreadsheetDocument.WorkbookPart!.Workbook.Save(); + _spreadsheetDocument.Dispose(); + } + } +} \ No newline at end of file diff --git a/DiningRoom/DiningRoomBusinessLogic/OfficePackage/Implements/SaveToPdf.cs b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/Implements/SaveToPdf.cs new file mode 100644 index 0000000..515cdea --- /dev/null +++ b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/Implements/SaveToPdf.cs @@ -0,0 +1,114 @@ +using DiningRoomBusinessLogic.OfficePackage.HelperEnums; +using DiningRoomBusinessLogic.OfficePackage.HelperModels; +using MigraDoc.DocumentObjectModel; +using MigraDoc.DocumentObjectModel.Tables; +using MigraDoc.Rendering; + +namespace DiningRoomBusinessLogic.OfficePackage.Implements +{ + public class SaveToPdf : AbstractSaveToPdf + { + private Document? _document; + + private Section? _section; + + private Table? _table; + + private static ParagraphAlignment GetParagraphAlignment(PdfParagraphAlignmentType type) + { + return type switch + { + PdfParagraphAlignmentType.Center => ParagraphAlignment.Center, + PdfParagraphAlignmentType.Left => ParagraphAlignment.Left, + PdfParagraphAlignmentType.Right => ParagraphAlignment.Right, + _ => ParagraphAlignment.Justify, + }; + } + + /// + /// Создание стилей для документа + /// + /// + private static void DefineStyles(Document document) + { + var style = document.Styles["Normal"]; + style.Font.Name = "Times New Roman"; + style.Font.Size = 14; + + style = document.Styles.AddStyle("NormalTitle", "Normal"); + style.Font.Bold = true; + } + + protected override void CreatePdf(PdfInfo info) + { + _document = new Document(); + DefineStyles(_document); + + _section = _document.AddSection(); + } + + protected override void CreateParagraph(PdfParagraph pdfParagraph) + { + if (_section == null) + { + return; + } + var paragraph = _section.AddParagraph(pdfParagraph.Text); + paragraph.Format.SpaceAfter = "1cm"; + paragraph.Format.Alignment = GetParagraphAlignment(pdfParagraph.ParagraphAlignment); + paragraph.Style = pdfParagraph.Style; + } + + protected override void CreateTable(List columns) + { + if (_document == null) + { + return; + } + _table = _document.LastSection.AddTable(); + + foreach (var elem in columns) + { + _table.AddColumn(elem); + } + } + + protected override void CreateRow(PdfRowParameters rowParameters) + { + if (_table == null) + { + return; + } + var row = _table.AddRow(); + for (int i = 0; i < rowParameters.Texts.Count; ++i) + { + row.Cells[i].AddParagraph(rowParameters.Texts[i]); + + if (!string.IsNullOrEmpty(rowParameters.Style)) + { + row.Cells[i].Style = rowParameters.Style; + } + + Unit borderWidth = 0.5; + + row.Cells[i].Borders.Left.Width = borderWidth; + row.Cells[i].Borders.Right.Width = borderWidth; + row.Cells[i].Borders.Top.Width = borderWidth; + row.Cells[i].Borders.Bottom.Width = borderWidth; + + row.Cells[i].Format.Alignment = GetParagraphAlignment(rowParameters.ParagraphAlignment); + row.Cells[i].VerticalAlignment = VerticalAlignment.Center; + } + } + + protected override void SavePdf(PdfInfo info) + { + var renderer = new PdfDocumentRenderer(true) + { + Document = _document + }; + renderer.RenderDocument(); + renderer.PdfDocument.Save(info.FileName); + } + } +} diff --git a/DiningRoom/DiningRoomBusinessLogic/OfficePackage/Implements/SaveToWord.cs b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/Implements/SaveToWord.cs new file mode 100644 index 0000000..083f83b --- /dev/null +++ b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/Implements/SaveToWord.cs @@ -0,0 +1,135 @@ +using DiningRoomBusinessLogic.OfficePackage.HelperEnums; +using DiningRoomBusinessLogic.OfficePackage.HelperModels; +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Wordprocessing; + +namespace DiningRoomBusinessLogic.OfficePackage.Implements +{ + public class SaveToWord : AbstractSaveToWord + { + private WordprocessingDocument? _wordDocument; + + private Body? _docBody; + + /// + /// Получение типа выравнивания + /// + /// + /// + private static JustificationValues GetJustificationValues(WordJustificationType type) + { + return type switch + { + WordJustificationType.Both => JustificationValues.Both, + WordJustificationType.Center => JustificationValues.Center, + _ => JustificationValues.Left, + }; + } + + /// + /// Настройки страницы + /// + /// + private static SectionProperties CreateSectionProperties() + { + var properties = new SectionProperties(); + + var pageSize = new PageSize + { + Orient = PageOrientationValues.Portrait + }; + + properties.AppendChild(pageSize); + + return properties; + } + + /// + /// Задание форматирования для абзаца + /// + /// + /// + private static ParagraphProperties? CreateParagraphProperties(WordTextProperties? paragraphProperties) + { + if (paragraphProperties == null) + { + return null; + } + + var properties = new ParagraphProperties(); + + properties.AppendChild(new Justification() + { + Val = GetJustificationValues(paragraphProperties.JustificationType) + }); + + properties.AppendChild(new SpacingBetweenLines + { + LineRule = LineSpacingRuleValues.Auto + }); + + properties.AppendChild(new Indentation()); + + var paragraphMarkRunProperties = new ParagraphMarkRunProperties(); + if (!string.IsNullOrEmpty(paragraphProperties.Size)) + { + paragraphMarkRunProperties.AppendChild(new FontSize { Val = paragraphProperties.Size }); + } + properties.AppendChild(paragraphMarkRunProperties); + + return properties; + } + + protected override void CreateWord(WordInfo info) + { + _wordDocument = WordprocessingDocument.Create(info.FileName, WordprocessingDocumentType.Document); + MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart(); + mainPart.Document = new Document(); + _docBody = mainPart.Document.AppendChild(new Body()); + } + + protected override void CreateParagraph(WordParagraph paragraph) + { + if (_docBody == null || paragraph == null) + { + return; + } + var docParagraph = new Paragraph(); + + docParagraph.AppendChild(CreateParagraphProperties(paragraph.TextProperties)); + + foreach (var run in paragraph.Texts) + { + var docRun = new Run(); + + var properties = new RunProperties(); + properties.AppendChild(new FontSize { Val = run.Item2.Size }); + if (run.Item2.Bold) + { + properties.AppendChild(new Bold()); + } + docRun.AppendChild(properties); + + docRun.AppendChild(new Text { Text = run.Item1, Space = SpaceProcessingModeValues.Preserve }); + + docParagraph.AppendChild(docRun); + } + + _docBody.AppendChild(docParagraph); + } + + protected override void SaveWord(WordInfo info) + { + if (_docBody == null || _wordDocument == null) + { + return; + } + _docBody.AppendChild(CreateSectionProperties()); + + _wordDocument.MainDocumentPart!.Document.Save(); + + _wordDocument.Dispose(); + } + } +} \ No newline at end of file diff --git a/DiningRoom/DiningRoomContracts/BusinessLogicContracts/IReportLogic.cs b/DiningRoom/DiningRoomContracts/BusinessLogicContracts/IReportLogic.cs index a859cc9..3607a0e 100644 --- a/DiningRoom/DiningRoomContracts/BusinessLogicContracts/IReportLogic.cs +++ b/DiningRoom/DiningRoomContracts/BusinessLogicContracts/IReportLogic.cs @@ -18,6 +18,6 @@ namespace DiningRoomContracts.BusinessLogicContracts void SaveReportToWordFile(ReportBindingModel Model); - void SaveReportToExcelFile(ReportBindingModel Model); + void SaveReportToExcelFile(ReportBindingModel Model, List selectedComponents); } } diff --git a/DiningRoom/DiningRoomContracts/ViewModels/ReportComponentOrderViewModel.cs b/DiningRoom/DiningRoomContracts/ViewModels/ReportComponentOrderViewModel.cs index c66b906..55d4975 100644 --- a/DiningRoom/DiningRoomContracts/ViewModels/ReportComponentOrderViewModel.cs +++ b/DiningRoom/DiningRoomContracts/ViewModels/ReportComponentOrderViewModel.cs @@ -1,13 +1,10 @@ namespace DiningRoomContracts.ViewModels { - public class ReportComponentOrderViewModel - { - public int ComponentId { get; set; } + public class ReportComponentOrderViewModel + { + public string ComponentName { get; set; } + public string OrderName { get; set; } + public int ProductCount { get; set; } + } - public string ComponentName { get; set; } = string.Empty; - - public double ComponentCost { get; set; } - - public List<(int Count, string ProductName, double ProductPrice)> Orders { get; set; } = new(); - } } diff --git a/DiningRoom/DiningRoomContracts/ViewModels/ReportOrdersViewModel.cs b/DiningRoom/DiningRoomContracts/ViewModels/ReportOrdersViewModel.cs new file mode 100644 index 0000000..1f54f49 --- /dev/null +++ b/DiningRoom/DiningRoomContracts/ViewModels/ReportOrdersViewModel.cs @@ -0,0 +1,16 @@ +using DiningRoomDataModels.Enums; + +namespace DiningRoomContracts.ViewModels +{ + public class ReportOrdersViewModel + { + public int Id { get; set; } + + public DateTime DateCreate { get; set; } + + public string ProductName { get; set; } = string.Empty; + + public double Sum { get; set; } + public string Status { get; set; } = string.Empty ; + } +} \ No newline at end of file diff --git a/DiningRoom/DiningRoomDatabaseImplement/Implements/ComponentStorage.cs b/DiningRoom/DiningRoomDatabaseImplement/Implements/ComponentStorage.cs index 3e3e97f..00c2a63 100644 --- a/DiningRoom/DiningRoomDatabaseImplement/Implements/ComponentStorage.cs +++ b/DiningRoom/DiningRoomDatabaseImplement/Implements/ComponentStorage.cs @@ -92,30 +92,29 @@ namespace DiningRoomDatabaseImplement.Implements return ExistingComponent.GetViewModel; } - public List GetComponentsOrders(List Models) + public List GetComponentsOrders(List models) { - using var Context = new DiningRoomDatabase(); + using var context = new DiningRoomDatabase(); - return Context.Components + return context.Components .Include(x => x.ProductComponents) .ThenInclude(x => x.Product) .ThenInclude(x => x.Order) - .Where(x => - Models.Select(x => x.Id).Contains(x.Id) // Компонент, указанный пользователем, - && x.ProductComponents.Any(y => y.Product.Order != null)) - .ToList() - .Select(x => new ReportComponentOrderViewModel - { - ComponentId = x.Id, - ComponentName = x.ComponentName, - ComponentCost = x.Cost, - Orders = x.ProductComponents - .Select(y => (y.Count, y.Product.ProductName, y.Product.Cost)) - .ToList(), - }) + .Where(x => models.Select(m => m.Id).Contains(x.Id) + && x.ProductComponents.Any(pc => pc.Product.Order.Any())) + .SelectMany(x => x.ProductComponents + .SelectMany(pc => pc.Product.Order + .Select(order => new ReportComponentOrderViewModel + { + ComponentName = x.ComponentName, + OrderName = order.Name, // Assuming Order has a property OrderName + ProductCount = order.Count + }))) .ToList(); } + + public List GetComponentsByDate(ReportBindingModel ReportModel) { using var Context = new DiningRoomDatabase(); diff --git a/DiningRoom/DiningRoomView/DiningRoomView.csproj b/DiningRoom/DiningRoomView/DiningRoomView.csproj index 7ea523a..56cc393 100644 --- a/DiningRoom/DiningRoomView/DiningRoomView.csproj +++ b/DiningRoom/DiningRoomView/DiningRoomView.csproj @@ -15,6 +15,7 @@ + diff --git a/DiningRoom/DiningRoomView/FormComponentSelection.Designer.cs b/DiningRoom/DiningRoomView/FormComponentSelection.Designer.cs new file mode 100644 index 0000000..c5ec2c6 --- /dev/null +++ b/DiningRoom/DiningRoomView/FormComponentSelection.Designer.cs @@ -0,0 +1,74 @@ +namespace DiningRoomView +{ + partial class FormComponentSelection + { + private System.ComponentModel.IContainer components = null; + + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + private void InitializeComponent() + { + btnOK = new Button(); + btnCancel = new Button(); + dataGridView = new DataGridView(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // btnOK + // + btnOK.Location = new Point(252, 355); + btnOK.Margin = new Padding(4, 3, 4, 3); + btnOK.Name = "btnOK"; + btnOK.Size = new Size(88, 27); + btnOK.TabIndex = 1; + btnOK.Text = "OK"; + btnOK.UseVisualStyleBackColor = true; + btnOK.Click += btnOK_Click; + // + // btnCancel + // + btnCancel.Location = new Point(346, 355); + btnCancel.Margin = new Padding(4, 3, 4, 3); + btnCancel.Name = "btnCancel"; + btnCancel.Size = new Size(88, 27); + btnCancel.TabIndex = 2; + btnCancel.Text = "Cancel"; + btnCancel.UseVisualStyleBackColor = true; + btnCancel.Click += btnCancel_Click; + // + // dataGridView + // + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(12, 24); + dataGridView.Name = "dataGridView"; + dataGridView.RowTemplate.Height = 25; + dataGridView.Size = new Size(424, 301); + dataGridView.TabIndex = 3; + // + // FormComponentSelection + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(448, 393); + Controls.Add(dataGridView); + Controls.Add(btnCancel); + Controls.Add(btnOK); + Margin = new Padding(4, 3, 4, 3); + Name = "FormComponentSelection"; + Text = "Select Products"; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + private System.Windows.Forms.Button btnOK; + private System.Windows.Forms.Button btnCancel; + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/DiningRoom/DiningRoomView/FormComponentSelection.cs b/DiningRoom/DiningRoomView/FormComponentSelection.cs new file mode 100644 index 0000000..6ebaf56 --- /dev/null +++ b/DiningRoom/DiningRoomView/FormComponentSelection.cs @@ -0,0 +1,90 @@ +using DiningRoomBusinessLogic.BusinessLogic; +using DiningRoomContracts.BusinessLogicContracts; +using DiningRoomContracts.SearchModels; +using DiningRoomContracts.ViewModels; +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; + +namespace DiningRoomView +{ + public partial class FormComponentSelection : Form + { + private readonly IComponentLogic _logic; + private readonly List? _list; + public UserViewModel? _currentUser { get; set; } + public List SelectedProducts { get; private set; } + public FormComponentSelection(IComponentLogic logic, UserViewModel currentuser) + { + _logic = logic; + _currentUser = currentuser; + InitializeComponent(); + LoadData(); + } + public void LoadData() + { + if (_currentUser == null) + { + MessageBox.Show("Ошибка авторизации", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + Close(); + return; + } + try + { + var list = _logic.ReadList((new ComponentSearchModel { UserId = _currentUser.Id })); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["Id"].Visible = false; + dataGridView.Columns["UserId"].Visible = false; + dataGridView.Columns["Login"].Visible = false; + dataGridView.Columns["ComponentName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + public List GetSelectedComponents(DataGridView dataGridView) + { + var selectedComponents = new List(); + + foreach (DataGridViewRow row in dataGridView.SelectedRows) + { + if (row.Cells["Id"].Value != null && row.Cells["ComponentName"].Value != null) + { + var component = new ComponentSearchModel + { + Id = Convert.ToInt32(row.Cells["Id"].Value), + ComponentName = row.Cells["ComponentName"].Value.ToString() + }; + selectedComponents.Add(component); + } + } + + return selectedComponents; + } + private void btnCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + + + private void btnOK_Click(object sender, EventArgs e) + { + SelectedProducts = GetSelectedComponents(dataGridView); + DialogResult = DialogResult.OK; + Close(); + } + + } +} diff --git a/DiningRoom/DiningRoomView/FormReportWoodComponents.resx b/DiningRoom/DiningRoomView/FormComponentSelection.resx similarity index 93% rename from DiningRoom/DiningRoomView/FormReportWoodComponents.resx rename to DiningRoom/DiningRoomView/FormComponentSelection.resx index 1af7de1..af32865 100644 --- a/DiningRoom/DiningRoomView/FormReportWoodComponents.resx +++ b/DiningRoom/DiningRoomView/FormComponentSelection.resx @@ -1,17 +1,17 @@  - diff --git a/DiningRoom/DiningRoomView/FormMain.Designer.cs b/DiningRoom/DiningRoomView/FormMain.Designer.cs index adecee6..f54b4b0 100644 --- a/DiningRoom/DiningRoomView/FormMain.Designer.cs +++ b/DiningRoom/DiningRoomView/FormMain.Designer.cs @@ -34,6 +34,10 @@ продуктыToolStripMenuItem = new ToolStripMenuItem(); заказыToolStripMenuItem = new ToolStripMenuItem(); алкогольныеКартыToolStripMenuItem = new ToolStripMenuItem(); + отчетыToolStripMenuItem = new ToolStripMenuItem(); + заказыПоПродуктамToolStripMenuItem = new ToolStripMenuItem(); + wordToolStripMenuItem = new ToolStripMenuItem(); + excelToolStripMenuItem = new ToolStripMenuItem(); button1 = new Button(); label1 = new Label(); label2 = new Label(); @@ -68,7 +72,7 @@ // // menuStrip1 // - menuStrip1.Items.AddRange(new ToolStripItem[] { продуктыToolStripMenuItem, заказыToolStripMenuItem, алкогольныеКартыToolStripMenuItem }); + menuStrip1.Items.AddRange(new ToolStripItem[] { продуктыToolStripMenuItem, заказыToolStripMenuItem, алкогольныеКартыToolStripMenuItem, отчетыToolStripMenuItem }); menuStrip1.Location = new Point(0, 0); menuStrip1.Name = "menuStrip1"; menuStrip1.Size = new Size(666, 24); @@ -96,6 +100,33 @@ алкогольныеКартыToolStripMenuItem.Text = "Алкогольные карты"; алкогольныеКартыToolStripMenuItem.Click += КартыToolStripMenuItem_Click; // + // отчетыToolStripMenuItem + // + отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { заказыПоПродуктамToolStripMenuItem }); + отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; + отчетыToolStripMenuItem.Size = new Size(60, 20); + отчетыToolStripMenuItem.Text = "Отчеты"; + // + // заказыПоПродуктамToolStripMenuItem + // + заказыПоПродуктамToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { wordToolStripMenuItem, excelToolStripMenuItem }); + заказыПоПродуктамToolStripMenuItem.Name = "заказыПоПродуктамToolStripMenuItem"; + заказыПоПродуктамToolStripMenuItem.Size = new Size(192, 22); + заказыПоПродуктамToolStripMenuItem.Text = "Заказы по продуктам"; + // + // wordToolStripMenuItem + // + wordToolStripMenuItem.Name = "wordToolStripMenuItem"; + wordToolStripMenuItem.Size = new Size(180, 22); + wordToolStripMenuItem.Text = "Word"; + // + // excelToolStripMenuItem + // + excelToolStripMenuItem.Name = "excelToolStripMenuItem"; + excelToolStripMenuItem.Size = new Size(180, 22); + excelToolStripMenuItem.Text = "Excel"; + excelToolStripMenuItem.Click += ОтчетыToolStripMenuItem_Click; + // // button1 // button1.Location = new Point(491, 139); @@ -232,5 +263,9 @@ private Button button7; private ToolStripMenuItem заказыToolStripMenuItem; private ToolStripMenuItem алкогольныеКартыToolStripMenuItem; + private ToolStripMenuItem отчетыToolStripMenuItem; + private ToolStripMenuItem заказыПоПродуктамToolStripMenuItem; + private ToolStripMenuItem wordToolStripMenuItem; + private ToolStripMenuItem excelToolStripMenuItem; } } \ No newline at end of file diff --git a/DiningRoom/DiningRoomView/FormMain.cs b/DiningRoom/DiningRoomView/FormMain.cs index e9ea40c..9cb04f2 100644 --- a/DiningRoom/DiningRoomView/FormMain.cs +++ b/DiningRoom/DiningRoomView/FormMain.cs @@ -123,6 +123,20 @@ namespace DiningRoomView form.ShowDialog(); } } + private void ОтчетыToolStripMenuItem_Click(object sender, EventArgs e) + { + if (_currentUser == null) + { + MessageBox.Show("Ошибка авторизации", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + var service = Program.ServiceProvider?.GetService(typeof(FormReportProductComponents)); + if (service is FormReportProductComponents form) + { + form._currentUser = _currentUser; + form.ShowDialog(); + } + } private void КартыToolStripMenuItem_Click(object sender, EventArgs e) { if (_currentUser == null) diff --git a/DiningRoom/DiningRoomView/FormReportOrders.Designer.cs b/DiningRoom/DiningRoomView/FormReportOrders.Designer.cs deleted file mode 100644 index 8a4481e..0000000 --- a/DiningRoom/DiningRoomView/FormReportOrders.Designer.cs +++ /dev/null @@ -1,141 +0,0 @@ -namespace CarpentryWorkshopView -{ - partial class FormReportOrders - { - /// - /// 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() - { - this.panel = new System.Windows.Forms.Panel(); - this.buttonToPdf = new System.Windows.Forms.Button(); - this.buttonMake = new System.Windows.Forms.Button(); - this.dateTimePickerTo = new System.Windows.Forms.DateTimePicker(); - this.labelTo = new System.Windows.Forms.Label(); - this.dateTimePickerFrom = new System.Windows.Forms.DateTimePicker(); - this.labelFrom = new System.Windows.Forms.Label(); - this.panel.SuspendLayout(); - this.SuspendLayout(); - // - // panel - // - this.panel.Controls.Add(this.buttonToPdf); - this.panel.Controls.Add(this.buttonMake); - this.panel.Controls.Add(this.dateTimePickerTo); - this.panel.Controls.Add(this.labelTo); - this.panel.Controls.Add(this.dateTimePickerFrom); - this.panel.Controls.Add(this.labelFrom); - this.panel.Dock = System.Windows.Forms.DockStyle.Top; - this.panel.Location = new System.Drawing.Point(0, 0); - this.panel.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.panel.Name = "panel"; - this.panel.Size = new System.Drawing.Size(1031, 40); - this.panel.TabIndex = 0; - // - // buttonToPdf - // - this.buttonToPdf.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); - this.buttonToPdf.Location = new System.Drawing.Point(878, 8); - this.buttonToPdf.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.buttonToPdf.Name = "buttonToPdf"; - this.buttonToPdf.Size = new System.Drawing.Size(139, 27); - this.buttonToPdf.TabIndex = 5; - this.buttonToPdf.Text = "В Pdf"; - this.buttonToPdf.UseVisualStyleBackColor = true; - this.buttonToPdf.Click += new System.EventHandler(this.ButtonToPdf_Click); - // - // buttonMake - // - this.buttonMake.Location = new System.Drawing.Point(476, 8); - this.buttonMake.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.buttonMake.Name = "buttonMake"; - this.buttonMake.Size = new System.Drawing.Size(139, 27); - this.buttonMake.TabIndex = 4; - this.buttonMake.Text = "Сформировать"; - this.buttonMake.UseVisualStyleBackColor = true; - this.buttonMake.Click += new System.EventHandler(this.ButtonMake_Click); - // - // dateTimePickerTo - // - this.dateTimePickerTo.Location = new System.Drawing.Point(237, 7); - this.dateTimePickerTo.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.dateTimePickerTo.Name = "dateTimePickerTo"; - this.dateTimePickerTo.Size = new System.Drawing.Size(163, 23); - this.dateTimePickerTo.TabIndex = 3; - // - // labelTo - // - this.labelTo.AutoSize = true; - this.labelTo.Location = new System.Drawing.Point(208, 10); - this.labelTo.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - this.labelTo.Name = "labelTo"; - this.labelTo.Size = new System.Drawing.Size(21, 15); - this.labelTo.TabIndex = 2; - this.labelTo.Text = "по"; - // - // dateTimePickerFrom - // - this.dateTimePickerFrom.Location = new System.Drawing.Point(37, 7); - this.dateTimePickerFrom.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.dateTimePickerFrom.Name = "dateTimePickerFrom"; - this.dateTimePickerFrom.Size = new System.Drawing.Size(163, 23); - this.dateTimePickerFrom.TabIndex = 1; - // - // labelFrom - // - this.labelFrom.AutoSize = true; - this.labelFrom.Location = new System.Drawing.Point(14, 10); - this.labelFrom.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - this.labelFrom.Name = "labelFrom"; - this.labelFrom.Size = new System.Drawing.Size(15, 15); - this.labelFrom.TabIndex = 0; - this.labelFrom.Text = "С"; - // - // FormReportOrders - // - this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(1031, 647); - this.Controls.Add(this.panel); - this.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); - this.Name = "FormReportOrders"; - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; - this.Text = "Заказы"; - this.panel.ResumeLayout(false); - this.panel.PerformLayout(); - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.Panel panel; - private System.Windows.Forms.Button buttonToPdf; - private System.Windows.Forms.Button buttonMake; - private System.Windows.Forms.DateTimePicker dateTimePickerTo; - private System.Windows.Forms.Label labelTo; - private System.Windows.Forms.DateTimePicker dateTimePickerFrom; - private System.Windows.Forms.Label labelFrom; - } -} \ No newline at end of file diff --git a/DiningRoom/DiningRoomView/FormReportOrders.cs b/DiningRoom/DiningRoomView/FormReportOrders.cs deleted file mode 100644 index 631e269..0000000 --- a/DiningRoom/DiningRoomView/FormReportOrders.cs +++ /dev/null @@ -1,101 +0,0 @@ -using CarpentryWorkshopContracts.BindingModels; -using CarpentryWorkshopContracts.BusinessLogicsContracts; -using Microsoft.Extensions.Logging; -using Microsoft.Reporting.WinForms; -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; - -namespace CarpentryWorkshopView -{ - public partial class FormReportOrders : Form - { - private readonly ReportViewer reportViewer; - - private readonly ILogger _logger; - - private readonly IReportLogic _logic; - - public FormReportOrders(ILogger logger, IReportLogic logic) - { - InitializeComponent(); - _logger = logger; - _logic = logic; - reportViewer = new ReportViewer - { - Dock = DockStyle.Fill - }; - reportViewer.LocalReport.LoadReportDefinition(new FileStream("ReportOrders.rdlc", FileMode.Open)); - Controls.Clear(); - Controls.Add(reportViewer); - Controls.Add(panel); - } - - private void ButtonMake_Click(object sender, EventArgs e) - { - if (dateTimePickerFrom.Value.Date >= dateTimePickerTo.Value.Date) - { - MessageBox.Show("Дата начала должна быть меньше даты окончания", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - try - { - var dataSource = _logic.GetOrders(new ReportBindingModel - { - DateFrom = DateTime.SpecifyKind(dateTimePickerFrom.Value, DateTimeKind.Utc), - DateTo = DateTime.SpecifyKind(dateTimePickerTo.Value, DateTimeKind.Utc) - }); - var source = new ReportDataSource("DataSetOrders", dataSource); - reportViewer.LocalReport.DataSources.Clear(); - reportViewer.LocalReport.DataSources.Add(source); - var parameters = new[] { new ReportParameter("ReportParameterPeriod", - $"c {dateTimePickerFrom.Value.ToShortDateString()} по {dateTimePickerTo.Value.ToShortDateString()}") }; - reportViewer.LocalReport.SetParameters(parameters); - - reportViewer.RefreshReport(); - _logger.LogInformation("Загрузка списка заказов на период {From}-{To}", dateTimePickerFrom.Value.ToShortDateString(), dateTimePickerTo.Value.ToShortDateString()); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки списка заказов на период"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - - private void ButtonToPdf_Click(object sender, EventArgs e) - { - System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); - if (dateTimePickerFrom.Value.Date >= dateTimePickerTo.Value.Date) - { - MessageBox.Show("Дата начала должна быть меньше даты окончания", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - using var dialog = new SaveFileDialog { Filter = "pdf|*.pdf" }; - if (dialog.ShowDialog() == DialogResult.OK) - { - try - { - _logic.SaveOrdersToPdfFile(new ReportBindingModel - { - FileName = dialog.FileName, - DateFrom = DateTime.SpecifyKind(dateTimePickerFrom.Value, DateTimeKind.Utc), - DateTo = DateTime.SpecifyKind(dateTimePickerTo.Value, DateTimeKind.Utc) - }); - _logger.LogInformation("Сохранение списка заказов на период {From}-{To}", dateTimePickerFrom.Value.ToShortDateString(), dateTimePickerTo.Value.ToShortDateString()); - MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка сохранения списка заказов на период"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - } -} diff --git a/DiningRoom/DiningRoomView/FormReportProductComponents.Designer.cs b/DiningRoom/DiningRoomView/FormReportProductComponents.Designer.cs new file mode 100644 index 0000000..6f9ee9b --- /dev/null +++ b/DiningRoom/DiningRoomView/FormReportProductComponents.Designer.cs @@ -0,0 +1,113 @@ +namespace DiningRoomView +{ + partial class FormReportProductComponents + { + /// + /// 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() + { + dataGridView = new DataGridView(); + buttonSaveToExcel = new Button(); + ColumnComponent = new DataGridViewTextBoxColumn(); + ColumnProduct = new DataGridViewTextBoxColumn(); + ColumnCount = new DataGridViewTextBoxColumn(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.AllowUserToOrderColumns = true; + dataGridView.AllowUserToResizeColumns = false; + dataGridView.AllowUserToResizeRows = false; + dataGridView.BackgroundColor = SystemColors.ControlLightLight; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnComponent, ColumnProduct, ColumnCount }); + dataGridView.Dock = DockStyle.Bottom; + dataGridView.Location = new Point(0, 47); + dataGridView.Margin = new Padding(4, 3, 4, 3); + dataGridView.MultiSelect = false; + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersVisible = false; + dataGridView.Size = new Size(616, 510); + dataGridView.TabIndex = 0; + // + // buttonSaveToExcel + // + buttonSaveToExcel.Location = new Point(14, 14); + buttonSaveToExcel.Margin = new Padding(4, 3, 4, 3); + buttonSaveToExcel.Name = "buttonSaveToExcel"; + buttonSaveToExcel.Size = new Size(186, 27); + buttonSaveToExcel.TabIndex = 1; + buttonSaveToExcel.Text = "Сохранить в Excel"; + buttonSaveToExcel.UseVisualStyleBackColor = true; + buttonSaveToExcel.Click += ButtonSaveToExcel_Click; + // + // ColumnComponent + // + ColumnComponent.HeaderText = "Продукт"; + ColumnComponent.Name = "ColumnComponent"; + ColumnComponent.ReadOnly = true; + ColumnComponent.Width = 200; + // + // ColumnProduct + // + ColumnProduct.HeaderText = "Имя заказа"; + ColumnProduct.Name = "ColumnProduct"; + ColumnProduct.ReadOnly = true; + ColumnProduct.Width = 200; + // + // ColumnCount + // + ColumnCount.HeaderText = "Количество блюд в заказе"; + ColumnCount.Name = "ColumnCount"; + ColumnCount.ReadOnly = true; + // + // FormReportProductComponents + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(616, 557); + Controls.Add(buttonSaveToExcel); + Controls.Add(dataGridView); + Margin = new Padding(4, 3, 4, 3); + Name = "FormReportProductComponents"; + Text = "Компоненты по изделиям"; + Load += FormReportProductComponents_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private System.Windows.Forms.DataGridView dataGridView; + private System.Windows.Forms.Button buttonSaveToExcel; + private DataGridViewTextBoxColumn ColumnComponent; + private DataGridViewTextBoxColumn ColumnProduct; + private DataGridViewTextBoxColumn ColumnCount; + } +} \ No newline at end of file diff --git a/DiningRoom/DiningRoomView/FormReportProductComponents.cs b/DiningRoom/DiningRoomView/FormReportProductComponents.cs new file mode 100644 index 0000000..aa9de37 --- /dev/null +++ b/DiningRoom/DiningRoomView/FormReportProductComponents.cs @@ -0,0 +1,121 @@ +using DiningRoomContracts.BindingModels; +using DiningRoomContracts.BusinessLogicContracts; +using DiningRoomContracts.SearchModels; +using DiningRoomContracts.ViewModels; +using Microsoft.Extensions.Logging; +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; + +namespace DiningRoomView +{ + public partial class FormReportProductComponents : Form + { + private readonly ILogger _logger; + + private readonly IReportLogic _logic; + + public IComponentLogic _logicC; + public UserViewModel? _currentUser { get; set; } + + public List SelectedComp; + + public FormReportProductComponents(ILogger logger, IReportLogic logic, IComponentLogic logicC) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + _logicC = logicC; + } + + private void FormReportProductComponents_Load(object sender, EventArgs e) + { + try + { + + using (var formProductSelection = new FormComponentSelection(_logicC, _currentUser)) + { + + if (formProductSelection.ShowDialog() == DialogResult.OK) + { + var selectedProducts = formProductSelection.SelectedProducts; + SelectedComp = selectedProducts; + if (selectedProducts != null && selectedProducts.Any()) + { + var reportData = _logic.GetReportComponentsWithOrders(selectedProducts); + DisplayDataInGridView(reportData); + } + } + } + + _logger.LogInformation("Загрузка списка компонентов по заказам"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки списка изделий по компонентам"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void DisplayDataInGridView(List reportData) + { + dataGridView.Rows.Clear(); + + // Группируем данные по ComponentName + var groupedData = reportData + .GroupBy(item => item.ComponentName) + .ToList(); + + foreach (var group in groupedData) + { + // Добавляем строку для названия компонента + var componentRow = new DataGridViewRow(); + componentRow.CreateCells(dataGridView); + componentRow.Cells[0].Value = group.Key; // Название компонента + componentRow.DefaultCellStyle.Font = new Font(dataGridView.DefaultCellStyle.Font, FontStyle.Bold); + dataGridView.Rows.Add(componentRow); + + // Добавляем строки для каждого заказа, связанного с компонентом + foreach (var order in group) + { + var orderRow = new DataGridViewRow(); + orderRow.CreateCells(dataGridView); + orderRow.Cells[1].Value = order.OrderName; + orderRow.Cells[2].Value = order.ProductCount; + dataGridView.Rows.Add(orderRow); + } + } + } + + + + private void ButtonSaveToExcel_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "xlsx|*.xlsx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + try + { + + _logic.SaveReportToExcelFile(new ReportBindingModel + { + FileName = dialog.FileName + },SelectedComp); + _logger.LogInformation("Сохранение списка изделий по компонентам"); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения списка изделий по компонентам"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } +} diff --git a/DiningRoom/DiningRoomView/FormReportOrders.resx b/DiningRoom/DiningRoomView/FormReportProductComponents.resx similarity index 93% rename from DiningRoom/DiningRoomView/FormReportOrders.resx rename to DiningRoom/DiningRoomView/FormReportProductComponents.resx index 1af7de1..af32865 100644 --- a/DiningRoom/DiningRoomView/FormReportOrders.resx +++ b/DiningRoom/DiningRoomView/FormReportProductComponents.resx @@ -1,17 +1,17 @@  - diff --git a/DiningRoom/DiningRoomView/FormReportWoodComponents.Designer.cs b/DiningRoom/DiningRoomView/FormReportWoodComponents.Designer.cs deleted file mode 100644 index 9035a72..0000000 --- a/DiningRoom/DiningRoomView/FormReportWoodComponents.Designer.cs +++ /dev/null @@ -1,114 +0,0 @@ -namespace CarpentryWorkshopView -{ - partial class FormReportWoodComponents - { - /// - /// 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() - { - this.dataGridView = new System.Windows.Forms.DataGridView(); - this.buttonSaveToExcel = new System.Windows.Forms.Button(); - this.ColumnComponent = new System.Windows.Forms.DataGridViewTextBoxColumn(); - this.ColumnWood = new System.Windows.Forms.DataGridViewTextBoxColumn(); - this.ColumnCount = new System.Windows.Forms.DataGridViewTextBoxColumn(); - ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); - this.SuspendLayout(); - // - // dataGridView - // - this.dataGridView.AllowUserToAddRows = false; - this.dataGridView.AllowUserToDeleteRows = false; - this.dataGridView.AllowUserToOrderColumns = true; - this.dataGridView.AllowUserToResizeColumns = false; - this.dataGridView.AllowUserToResizeRows = false; - this.dataGridView.BackgroundColor = System.Drawing.SystemColors.ControlLightLight; - this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; - this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { - this.ColumnComponent, - this.ColumnWood, - this.ColumnCount}); - this.dataGridView.Dock = System.Windows.Forms.DockStyle.Bottom; - this.dataGridView.Location = new System.Drawing.Point(0, 41); - this.dataGridView.MultiSelect = false; - this.dataGridView.Name = "dataGridView"; - this.dataGridView.ReadOnly = true; - this.dataGridView.RowHeadersVisible = false; - this.dataGridView.Size = new System.Drawing.Size(528, 442); - this.dataGridView.TabIndex = 0; - // - // buttonSaveToExcel - // - this.buttonSaveToExcel.Location = new System.Drawing.Point(12, 12); - this.buttonSaveToExcel.Name = "buttonSaveToExcel"; - this.buttonSaveToExcel.Size = new System.Drawing.Size(159, 23); - this.buttonSaveToExcel.TabIndex = 1; - this.buttonSaveToExcel.Text = "Сохранить в Excel"; - this.buttonSaveToExcel.UseVisualStyleBackColor = true; - this.buttonSaveToExcel.Click += new System.EventHandler(this.ButtonSaveToExcel_Click); - // - // ColumnComponent - // - this.ColumnComponent.HeaderText = "Изделие"; - this.ColumnComponent.Name = "ColumnWood"; - this.ColumnComponent.ReadOnly = true; - this.ColumnComponent.Width = 200; - // - // ColumnWood - // - this.ColumnWood.HeaderText = "Компонент"; - this.ColumnWood.Name = "ColumnComponent"; - this.ColumnWood.ReadOnly = true; - this.ColumnWood.Width = 200; - // - // ColumnCount - // - this.ColumnCount.HeaderText = "Количество"; - this.ColumnCount.Name = "ColumnCount"; - this.ColumnCount.ReadOnly = true; - // - // FormReportWoodComponents - // - this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(528, 483); - this.Controls.Add(this.buttonSaveToExcel); - this.Controls.Add(this.dataGridView); - this.Name = "FormReportWoodComponents"; - this.Text = "Компоненты по изделиям"; - this.Load += new System.EventHandler(this.FormReportWoodComponents_Load); - ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.DataGridView dataGridView; - private System.Windows.Forms.Button buttonSaveToExcel; - private System.Windows.Forms.DataGridViewTextBoxColumn ColumnComponent; - private System.Windows.Forms.DataGridViewTextBoxColumn ColumnWood; - private System.Windows.Forms.DataGridViewTextBoxColumn ColumnCount; - } -} \ No newline at end of file diff --git a/DiningRoom/DiningRoomView/FormReportWoodComponents.cs b/DiningRoom/DiningRoomView/FormReportWoodComponents.cs deleted file mode 100644 index d401b62..0000000 --- a/DiningRoom/DiningRoomView/FormReportWoodComponents.cs +++ /dev/null @@ -1,79 +0,0 @@ -using CarpentryWorkshopContracts.BindingModels; -using CarpentryWorkshopContracts.BusinessLogicsContracts; -using Microsoft.Extensions.Logging; -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; - -namespace CarpentryWorkshopView -{ - public partial class FormReportWoodComponents : Form - { - private readonly ILogger _logger; - - private readonly IReportLogic _logic; - - public FormReportWoodComponents(ILogger logger, IReportLogic logic) - { - InitializeComponent(); - _logger = logger; - _logic = logic; - } - - private void FormReportWoodComponents_Load(object sender, EventArgs e) - { - try - { - var dict = _logic.GetWoodComponent(); - if (dict != null) - { - dataGridView.Rows.Clear(); - foreach (var elem in dict) - { - dataGridView.Rows.Add(new object[] { elem.WoodName, "", "" }); - foreach (var listElem in elem.Components) - { - dataGridView.Rows.Add(new object[] { "", listElem.Item1, listElem.Item2 }); - } - dataGridView.Rows.Add(new object[] { "Итого", "", elem.TotalCount }); - dataGridView.Rows.Add(Array.Empty()); - } - } - _logger.LogInformation("Загрузка списка изделий по компонентам"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки списка изделий по компонентам"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - - private void ButtonSaveToExcel_Click(object sender, EventArgs e) - { - using var dialog = new SaveFileDialog { Filter = "xlsx|*.xlsx" }; - if (dialog.ShowDialog() == DialogResult.OK) - { - try - { - _logic.SaveWoodComponentToExcelFile(new ReportBindingModel - { - FileName = dialog.FileName - }); - _logger.LogInformation("Сохранение списка изделий по компонентам"); - MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка сохранения списка изделий по компонентам"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - } -} diff --git a/DiningRoom/DiningRoomView/Program.cs b/DiningRoom/DiningRoomView/Program.cs index f4f2367..f2a0509 100644 --- a/DiningRoom/DiningRoomView/Program.cs +++ b/DiningRoom/DiningRoomView/Program.cs @@ -5,6 +5,8 @@ using DiningRoomDatabaseImplement.Implements; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using DiningRoomBusinessLogic.BusinessLogic; +using DiningRoomBusinessLogic.OfficePackage.Implements; +using DiningRoomBusinessLogic.OfficePackage; @@ -48,6 +50,11 @@ namespace DiningRoomView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -61,7 +68,8 @@ namespace DiningRoomView services.AddTransient(); services.AddTransient(); services.AddTransient(); - + services.AddTransient(); + services.AddTransient(); }