diff --git a/AircraftPlant/AircraftPlantBusinessLogic/AircraftPlantBusinessLogic.csproj b/AircraftPlant/AircraftPlantBusinessLogic/AircraftPlantBusinessLogic.csproj index 029f939..bcaa5f0 100644 --- a/AircraftPlant/AircraftPlantBusinessLogic/AircraftPlantBusinessLogic.csproj +++ b/AircraftPlant/AircraftPlantBusinessLogic/AircraftPlantBusinessLogic.csproj @@ -7,7 +7,9 @@ + + diff --git a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ReportLogic.cs b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ReportLogic.cs new file mode 100644 index 0000000..f8b9be9 --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ReportLogic.cs @@ -0,0 +1,230 @@ +using AircraftPlantBusinessLogic.OfficePackage; +using AircraftPlantBusinessLogic.OfficePackage.HelperModels; +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.BusinessLogicsContracts; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.StoragesContracts; +using AircraftPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.BusinessLogics +{ + /// + /// Реализация интерфейса бизнес-логики для создания отчетов + /// + public class ReportLogic : IReportLogic + { + /// + /// Хранилище компонентов + /// + private readonly IComponentStorage _componentStorage; + + /// + /// Хранилище изделий + /// + private readonly IPlaneStorage _planeStorage; + + /// + /// Хранилище заказов + /// + private readonly IOrderStorage _orderStorage; + + /// + /// Хранилище магазинов + /// + private readonly IShopStorage _shopStorage; + + /// + /// Взаимодействие с отчетами в Excel-формате + /// + private readonly AbstractSaveToExcel _saveToExcel; + + /// + /// Взаимодействие с отчетами в Word-формате + /// + private readonly AbstractSaveToWord _saveToWord; + + /// + /// Взаимодействие с отчетами в Pdf-формате + /// + private readonly AbstractSaveToPdf _saveToPdf; + + /// + /// Конструктор + /// + /// + /// + /// + /// + /// + /// + public ReportLogic(IPlaneStorage planeStorage, IComponentStorage componentStorage, IOrderStorage orderStorage, IShopStorage shopStorage, + AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf) + { + _planeStorage = planeStorage; + _componentStorage = componentStorage; + _orderStorage = orderStorage; + _shopStorage = shopStorage; + + _saveToExcel = saveToExcel; + _saveToWord = saveToWord; + _saveToPdf = saveToPdf; + } + + /// + /// Получение списка изделий с расшифровкой по компонентам + /// + /// + public List GetPlaneComponents() + { + return _planeStorage.GetFullList().Select(x => new ReportPlaneComponentViewModel + { + PlaneName = x.PlaneName, + Components = x.PlaneComponents.Select(x => (x.Value.Item1.ComponentName, x.Value.Item2)).ToList(), + TotalCount = x.PlaneComponents.Select(x => x.Value.Item2).Sum() + }).ToList(); + } + + /// + /// Получение списка заказов за определенный период + /// + /// + /// + public List GetOrders(ReportBindingModel model) + { + return _orderStorage.GetFilteredList(new OrderSearchModel { DateFrom = model.DateFrom, DateTo = model.DateTo }) + .Select(x => new ReportOrdersViewModel + { + Id = x.Id, + DateCreate = x.DateCreate, + PlaneName = x.PlaneName, + Sum = x.Sum, + Status = x.Status.ToString() + }) + .ToList(); + } + + /// + /// Получение списка заказов с группировкой по датам + /// + /// + public List GetGroupOrders() + { + return _orderStorage.GetFullList() + .GroupBy(x => x.DateCreate.Date) + .Select(x => new ReportGroupOrdersViewModel + { + DateCreate = x.Key, + Count = x.Count(), + Sum = x.Select(y => y.Sum).Sum() + }) + .ToList(); + } + + /// + /// Получение списка магазинов с указанием хранимых изделий + /// + /// + public List GetShopPlanes() + { + return _shopStorage.GetFullList() + .Select(x => new ReportShopPlanesViewModel + { + ShopName = x.ShopName, + Planes = x.ShopPlanes.Select(x => (x.Value.Item1.PlaneName, x.Value.Item2)).ToList(), + TotalCount = x.ShopPlanes.Select(x => x.Value.Item2).Sum() + }) + .ToList(); + } + + /// + /// Сохранение изделий в Word-файл + /// + /// + public void SavePlanesToWordFile(ReportBindingModel model) + { + _saveToWord.CreateDoc(new WordInfo + { + FileName = model.FileName, + Title = "Список изделий", + Planes = _planeStorage.GetFullList() + }); + } + + /// + /// Сохранение изделий с расшифровкой по компонентам в Excel-файл + /// + /// + public void SavePlaneComponentsToExcelFile(ReportBindingModel model) + { + _saveToExcel.CreateReport(new ExcelInfo + { + FileName = model.FileName, + Title = "Список изделий", + PlaneComponents = GetPlaneComponents() + }); + } + + /// + /// Сохранение заказов в Pdf-файл + /// + /// + public void SaveOrdersToPdfFile(ReportBindingModel model) + { + _saveToPdf.CreateDoc(new PdfInfo + { + FileName = model.FileName, + Title = "Список заказов", + DateFrom = model.DateFrom!.Value, + DateTo = model.DateTo!.Value, + Orders = GetOrders(model) + }); + } + + /// + /// Сохранение магазинов в Word-файл + /// + /// + public void SaveShopsToWordFile(ReportBindingModel model) + { + _saveToWord.CreateShopsDoc(new WordInfo + { + FileName = model.FileName, + Title = "Список магазинов", + Shops = _shopStorage.GetFullList() + }); + } + + /// + /// Сохранение магазинов с указанием изделий в файл-Excel + /// + /// + public void SaveShopPlanesToExcelFile(ReportBindingModel model) + { + _saveToExcel.CreateShopPlanesReport(new ExcelInfo + { + FileName = model.FileName, + Title = "Ассортимент магазинов", + ShopPlanes = GetShopPlanes() + }); + } + + /// + /// Сохранение заказов с группировкой по датам в файл-Pdf + /// + /// + public void SaveGroupOrdersToPdfFile(ReportBindingModel model) + { + _saveToPdf.CreateGroupOrdersDoc(new PdfInfo + { + FileName= model.FileName, + Title = "Список заказов с группировкой по датам", + GroupOrders = GetGroupOrders() + }); + } + } +} diff --git a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/AbstractSaveToExcel.cs b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/AbstractSaveToExcel.cs new file mode 100644 index 0000000..91bc3fa --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/AbstractSaveToExcel.cs @@ -0,0 +1,191 @@ +using AircraftPlantBusinessLogic.OfficePackage.HelperEnums; +using AircraftPlantBusinessLogic.OfficePackage.HelperModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.OfficePackage +{ + /// + /// Абстрактный класс для сохранения Excel-файла + /// + public abstract class AbstractSaveToExcel + { + /// + /// Создание отчета в Excel-формате + /// + /// + public void CreateReport(ExcelInfo info) + { + CreateExcel(info); + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = 1, + Text = info.Title, + StyleInfo = ExcelStyleInfoType.Title + }); + + MergeCells(new ExcelMergeParameters + { + CellFromName = "A1", + CellToName = "C1" + }); + + uint rowIndex = 2; + foreach (var pc in info.PlaneComponents) + { + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = pc.PlaneName, + StyleInfo = ExcelStyleInfoType.Text + }); + rowIndex++; + + foreach (var (Component, Count) in pc.Components) + { + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = rowIndex, + Text = Component, + StyleInfo = ExcelStyleInfoType.TextWithBroder + }); + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = Count.ToString(), + StyleInfo = ExcelStyleInfoType.TextWithBroder + }); + + rowIndex++; + } + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = "Итого", + StyleInfo = ExcelStyleInfoType.Text + }); + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = pc.TotalCount.ToString(), + StyleInfo = ExcelStyleInfoType.Text + }); + rowIndex++; + } + + SaveExcel(info); + } + + /// + /// Создание отчета в Excel-формате + /// по магазинам с расшифровкой по изделиям + /// + /// + public void CreateShopPlanesReport(ExcelInfo info) + { + CreateExcel(info); + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = 1, + Text = info.Title, + StyleInfo = ExcelStyleInfoType.Title + }); + + MergeCells(new ExcelMergeParameters + { + CellFromName = "A1", + CellToName = "C1" + }); + + uint rowIndex = 2; + foreach (var sp in info.ShopPlanes) + { + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = sp.ShopName, + StyleInfo = ExcelStyleInfoType.Text + }); + rowIndex++; + + foreach (var (Plane, Count) in sp.Planes) + { + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = rowIndex, + Text = Plane, + StyleInfo = ExcelStyleInfoType.TextWithBroder + }); + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = Count.ToString(), + StyleInfo = ExcelStyleInfoType.TextWithBroder + }); + + rowIndex++; + } + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = "Итого", + StyleInfo = ExcelStyleInfoType.Text + }); + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = sp.TotalCount.ToString(), + StyleInfo = ExcelStyleInfoType.Text + }); + 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); + } +} diff --git a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/AbstractSaveToPdf.cs b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/AbstractSaveToPdf.cs new file mode 100644 index 0000000..2854b8d --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/AbstractSaveToPdf.cs @@ -0,0 +1,112 @@ +using AircraftPlantBusinessLogic.OfficePackage.HelperEnums; +using AircraftPlantBusinessLogic.OfficePackage.HelperModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.OfficePackage +{ + /// + /// Абстрактный класс для сохранения Word-файла + /// + public abstract class AbstractSaveToPdf + { + /// + /// Создание отчета в Pdf-формате + /// + /// + 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", "3cm", "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.PlaneName, 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); + } + + /// + /// Создание отчета в Pdf-формате + /// по закзам с группировкой по датам + /// + /// + public void CreateGroupOrdersDoc(PdfInfo info) + { + CreatePdf(info); + CreateParagraph(new PdfParagraph { Text = info.Title, Style = "NormalTitle", ParagraphAlignment = PdfParagraphAlignmentType.Center }); + + CreateTable(new List { "4cm", "3cm", "2cm" }); + + CreateRow(new PdfRowParameters + { + Texts = new List { "Дата заказа", "Количество", "Сумма" }, + Style = "NormalTitle", + ParagraphAlignment = PdfParagraphAlignmentType.Center + }); + + foreach (var order in info.GroupOrders) + { + CreateRow(new PdfRowParameters + { + Texts = new List { order.DateCreate.ToShortDateString(), order.Count.ToString(), order.Sum.ToString() }, + Style = "Normal", + ParagraphAlignment = PdfParagraphAlignmentType.Left + }); + } + CreateParagraph(new PdfParagraph { Text = $"Итого: {info.GroupOrders.Sum(x => x.Sum)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Right }); + + SavePdf(info); + } + + /// + /// Создание pdf-файла + /// + /// + 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/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/AbstractSaveToWord.cs b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/AbstractSaveToWord.cs new file mode 100644 index 0000000..6dd7d35 --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/AbstractSaveToWord.cs @@ -0,0 +1,131 @@ +using AircraftPlantBusinessLogic.OfficePackage.HelperEnums; +using AircraftPlantBusinessLogic.OfficePackage.HelperModels; +using DocumentFormat.OpenXml.Wordprocessing; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.OfficePackage +{ + /// + /// Абстрактный класс для сохранения Word-файла + /// + public abstract class AbstractSaveToWord + { + /// + /// Создание отчета в Word-формате + /// + /// + 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 plane in info.Planes) + { + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> + { + (plane.PlaneName, new WordTextProperties { Size = "24", Bold = true}), + ("\t" + plane.Price.ToString(), new WordTextProperties{Size = "24"}) + }, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Both + } + }); + } + + SaveWord(info); + } + + /// + /// Создание отчета по магазинам в doc-формате + /// + /// + public void CreateShopsDoc(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 + } + }); + + CreateTable(new List { "3000", "3000", "3000" }); + CreateRow(new WordRow + { + Texts = new List { "Название", "Адрес", "Дата открытия" }, + TextProperties = new WordTextProperties + { + Size = "24", + Bold = true, + JustificationType = WordJustificationType.Center + } + }); + + foreach (var shop in info.Shops) + { + CreateRow(new WordRow + { + Texts = new List { shop.ShopName, shop.Address, shop.DateOpening.ToString() }, + TextProperties = new WordTextProperties + { + Size = "22", + JustificationType = WordJustificationType.Both + } + }); + } + + SaveWord(info); + } + + /// + /// Создание doc-файла + /// + /// + protected abstract void CreateWord(WordInfo info); + + /// + /// Создание абзаца с текстом + /// + /// + protected abstract void CreateParagraph(WordParagraph paragraph); + + /// + /// Создание таблицы + /// + /// + protected abstract void CreateTable(List columns); + + /// + /// Создание строки + /// + /// + protected abstract void CreateRow(WordRow row); + + /// + /// Сохранение файла + /// + /// + protected abstract void SaveWord(WordInfo info); + } +} diff --git a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperEnums/ExcelStyleInfoType.cs b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperEnums/ExcelStyleInfoType.cs new file mode 100644 index 0000000..168c120 --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperEnums/ExcelStyleInfoType.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.OfficePackage.HelperEnums +{ + /// + /// Тип стиля текста + /// + public enum ExcelStyleInfoType + { + /// + /// Заголовок + /// + Title, + + /// + /// Обычный текст + /// + Text, + + /// + /// Текст в рамке + /// + TextWithBroder + } +} diff --git a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperEnums/PdfParagraphAlignmentType.cs b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperEnums/PdfParagraphAlignmentType.cs new file mode 100644 index 0000000..cfea86f --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperEnums/PdfParagraphAlignmentType.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.OfficePackage.HelperEnums +{ + /// + /// Тип выравнивания текста + /// + public enum PdfParagraphAlignmentType + { + /// + /// По центру + /// + Center, + + /// + /// По левому краю + /// + Left, + + /// + /// По правому краю + /// + Right + } +} diff --git a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperEnums/WordJustificationType.cs b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperEnums/WordJustificationType.cs new file mode 100644 index 0000000..ee38748 --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperEnums/WordJustificationType.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.OfficePackage.HelperEnums +{ + /// + /// Тип вырывнивания текста + /// + public enum WordJustificationType + { + /// + /// По центру + /// + Center, + + /// + /// По ширине + /// + Both + } +} diff --git a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/ExcelCellParameters.cs b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/ExcelCellParameters.cs new file mode 100644 index 0000000..173ef55 --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/ExcelCellParameters.cs @@ -0,0 +1,40 @@ +using AircraftPlantBusinessLogic.OfficePackage.HelperEnums; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.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; } + } +} diff --git a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs new file mode 100644 index 0000000..68846b8 --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs @@ -0,0 +1,36 @@ +using AircraftPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.OfficePackage.HelperModels +{ + /// + /// Модель для передачи данных + /// для создания отчета в Excel-файле + /// + public class ExcelInfo + { + /// + /// Название файла + /// + public string FileName { get; set; } = string.Empty; + + /// + /// Заголовок + /// + public string Title { get; set; } = string.Empty; + + /// + /// Список изделий с расшифровкой по компонентам + /// + public List PlaneComponents { get; set; } = new(); + + /// + /// Список магазинов с расшифровкой по изделиям + /// + public List ShopPlanes { get; set; } = new(); + } +} diff --git a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/ExcelMergeParameters.cs b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/ExcelMergeParameters.cs new file mode 100644 index 0000000..dedba3e --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/ExcelMergeParameters.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.OfficePackage.HelperModels +{ + /// + /// Модель для описания объединенных ячеек + /// + public class ExcelMergeParameters + { + /// + /// Начальная ячейка + /// + public string CellFromName { get; set; } = string.Empty; + + /// + /// Конечная ячейка + /// + public string CellToName { get; set; } = string.Empty; + + /// + /// Получить диапазон объединения ячеек + /// + public string Merge => $"{CellFromName}:{CellToName}"; + } +} diff --git a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs new file mode 100644 index 0000000..db84a6f --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs @@ -0,0 +1,46 @@ +using AircraftPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.OfficePackage.HelperModels +{ + /// + /// Модель для передачи данных + /// для создания отчета в Pdf-файле + /// + 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(); + + /// + /// Список заказов с группировкой по датам + /// + public List GroupOrders { get; set; } = new(); + } +} diff --git a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/PdfParagraph.cs b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/PdfParagraph.cs new file mode 100644 index 0000000..c56826a --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/PdfParagraph.cs @@ -0,0 +1,31 @@ +using AircraftPlantBusinessLogic.OfficePackage.HelperEnums; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.OfficePackage.HelperModels +{ + /// + /// Модель для передачи данных + /// для создания абзаца Pdf-файла + /// + public class PdfParagraph + { + /// + /// Текст абзаца + /// + public string Text { get; set; } = string.Empty; + + /// + /// Стиль текста + /// + public string Style { get; set; } = string.Empty; + + /// + /// Тип выравнивания текста + /// + public PdfParagraphAlignmentType ParagraphAlignment { get; set; } + } +} diff --git a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/PdfRowParameters.cs b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/PdfRowParameters.cs new file mode 100644 index 0000000..32053e6 --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/PdfRowParameters.cs @@ -0,0 +1,31 @@ +using AircraftPlantBusinessLogic.OfficePackage.HelperEnums; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.OfficePackage.HelperModels +{ + /// + /// Модель для передачи данных + /// для создания строки Pdf-файла + /// + public class PdfRowParameters + { + /// + /// Список текстов + /// + public List Texts { get; set; } = new(); + + /// + /// Стиль текста + /// + public string Style { get; set; } = string.Empty; + + /// + /// Тип выравнивания текста + /// + public PdfParagraphAlignmentType ParagraphAlignment { get; set; } + } +} diff --git a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/WordInfo.cs b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/WordInfo.cs new file mode 100644 index 0000000..728c63a --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/WordInfo.cs @@ -0,0 +1,36 @@ +using AircraftPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.OfficePackage.HelperModels +{ + /// + /// Модель для передачи данных + /// для создания отчета в Word-файле + /// + public class WordInfo + { + /// + /// Название файла + /// + public string FileName { get; set; } = string.Empty; + + /// + /// Заголовок + /// + public string Title { get; set; } = string.Empty; + + /// + /// Список изделий + /// + public List Planes { get; set; } = new(); + + /// + /// Список магазинов + /// + public List Shops { get; set; } = new(); + } +} diff --git a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/WordParagraph.cs b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/WordParagraph.cs new file mode 100644 index 0000000..eb42372 --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/WordParagraph.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.OfficePackage.HelperModels +{ + /// + /// Модель для передачи данных + /// для создания абзаца файла-Word + /// + public class WordParagraph + { + /// + /// Список текстов в абзаце + /// + public List<(string, WordTextProperties)> Texts { get; set; } = new(); + + /// + /// Свойства абзаца + /// + public WordTextProperties? TextProperties { get; set; } + } +} diff --git a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/WordRow.cs b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/WordRow.cs new file mode 100644 index 0000000..fec096b --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/WordRow.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.OfficePackage.HelperModels +{ + /// + /// Модель для передачи данных + /// для создания строки файла-Word + /// + public class WordRow + { + /// + /// Список текстов в строке + /// + public List Texts { get; set; } = new(); + + /// + /// Свойства строки + /// + public WordTextProperties? TextProperties { get; set; } + } +} diff --git a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/WordTextProperties.cs b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/WordTextProperties.cs new file mode 100644 index 0000000..1f75050 --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/WordTextProperties.cs @@ -0,0 +1,30 @@ +using AircraftPlantBusinessLogic.OfficePackage.HelperEnums; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.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/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/Implements/SaveToExcel.cs b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/Implements/SaveToExcel.cs new file mode 100644 index 0000000..4702f57 --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/Implements/SaveToExcel.cs @@ -0,0 +1,331 @@ +using AircraftPlantBusinessLogic.OfficePackage.HelperEnums; +using AircraftPlantBusinessLogic.OfficePackage.HelperModels; +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Office2010.Excel; +using DocumentFormat.OpenXml.Office2013.Excel; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Spreadsheet; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.OfficePackage.Implements +{ + /// + /// Реализация абстрактного класса для сохранения Excel-файла + /// + 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, + }; + } + + /// + /// Создание excel-файла + /// + /// + 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(); + } + } +} diff --git a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/Implements/SaveToPdf.cs b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/Implements/SaveToPdf.cs new file mode 100644 index 0000000..d445028 --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/Implements/SaveToPdf.cs @@ -0,0 +1,158 @@ +using AircraftPlantBusinessLogic.OfficePackage.HelperEnums; +using AircraftPlantBusinessLogic.OfficePackage.HelperModels; +using MigraDoc.DocumentObjectModel; +using MigraDoc.DocumentObjectModel.Tables; +using MigraDoc.Rendering; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.OfficePackage.Implements +{ + /// + /// Реализация абстрактного класса для сохранения Pdf-файла + /// + 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; + } + + /// + /// Создание pdf-файла + /// + /// + 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/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/Implements/SaveToWord.cs b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/Implements/SaveToWord.cs new file mode 100644 index 0000000..57ba632 --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/Implements/SaveToWord.cs @@ -0,0 +1,250 @@ +using AircraftPlantBusinessLogic.OfficePackage.HelperEnums; +using AircraftPlantBusinessLogic.OfficePackage.HelperModels; +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Wordprocessing; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.OfficePackage.Implements +{ + /// + /// Реализация абстрактного класса для сохранения Word-файла + /// + public class SaveToWord : AbstractSaveToWord + { + /// + /// Документ + /// + private WordprocessingDocument? _wordDocument; + + /// + /// Тело документа + /// + private Body? _docBody; + + /// + /// Таблица + /// + private Table? _table; + + /// + /// Получение типа выравнивания текста + /// + /// + /// + 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; + } + + /// + /// Создание doc-файла + /// + /// + 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 CreateTable(List columns) + { + if (_docBody == null) + { + return; + } + + _table = new Table(); + + var tableProperties = new TableProperties(); + tableProperties.AppendChild(new TableLayout { Type = TableLayoutValues.Fixed }); + tableProperties.AppendChild(new TableBorders( + new TopBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, + new LeftBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, + new RightBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, + new BottomBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, + new InsideHorizontalBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, + new InsideVerticalBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 } + )); + tableProperties.AppendChild(new TableWidth { Type = TableWidthUnitValues.Auto }); + _table.AppendChild(tableProperties); + + TableGrid tableGrid = new TableGrid(); + foreach (var column in columns) + { + tableGrid.AppendChild(new GridColumn() { Width = column }); + } + _table.AppendChild(tableGrid); + + _docBody.AppendChild(_table); + } + + /// + /// Создание строки + /// + /// + protected override void CreateRow(WordRow row) + { + if (_docBody == null || _table == null) + { + return; + } + + TableRow docRow = new TableRow(); + foreach (var column in row.Texts) + { + var docParagraph = new Paragraph(); + WordParagraph paragraph = new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { (column, row.TextProperties) }, + TextProperties = row.TextProperties + }; + + 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); + } + + TableCell docCell = new TableCell(); + docCell.AppendChild(docParagraph); + docRow.AppendChild(docCell); + } + + _table.AppendChild(docRow); + } + + /// + /// Сохранение файла + /// + /// + protected override void SaveWord(WordInfo info) + { + if (_docBody == null || _wordDocument == null) + { + return; + } + _docBody.AppendChild(CreateSectionProperties()); + + _wordDocument.MainDocumentPart!.Document.Save(); + _wordDocument.Dispose(); + } + } +} diff --git a/AircraftPlant/AircraftPlantContracts/BindingModels/ReportBindingModel.cs b/AircraftPlant/AircraftPlantContracts/BindingModels/ReportBindingModel.cs new file mode 100644 index 0000000..b389f62 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/BindingModels/ReportBindingModel.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.BindingModels +{ + /// + /// Модель для передачи данных пользователя для отчета + /// + public class ReportBindingModel + { + /// + /// Название файла + /// + public string FileName { get; set; } = string.Empty; + + /// + /// Начало периода выборки данных + /// + public DateTime? DateFrom { get; set; } + + /// + /// Конец периода выборки данных + /// + public DateTime? DateTo { get; set; } + } +} diff --git a/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IReportLogic.cs b/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IReportLogic.cs new file mode 100644 index 0000000..98b0bd5 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IReportLogic.cs @@ -0,0 +1,77 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.BusinessLogicsContracts +{ + /// + /// Интерфейс для описания работы с отчетами + /// + public interface IReportLogic + { + /// + /// Получение списка изделий с указанием используемых компонентов + /// + /// + List GetPlaneComponents(); + + /// + /// Получение списка заказов за определенный период + /// + /// + /// + List GetOrders(ReportBindingModel model); + + /// + /// Получение списка заказов с группировкой по датам + /// + /// + List GetGroupOrders(); + + /// + /// Получение списка магазинов с указанием хранимых изделий + /// + /// + List GetShopPlanes(); + + /// + /// Сохранение изделий в файл-Word + /// + /// + void SavePlanesToWordFile(ReportBindingModel model); + + /// + /// Сохранение изделий с указаеним компонентов в файл-Excel + /// + /// + void SavePlaneComponentsToExcelFile(ReportBindingModel model); + + /// + /// Сохранение заказов в файл-Pdf + /// + /// + void SaveOrdersToPdfFile(ReportBindingModel model); + + /// + /// Сохранение магазинов в Word-файл + /// + /// + void SaveShopsToWordFile(ReportBindingModel model); + + /// + /// Сохранение магазинов с указанием изделий в файл-Excel + /// + /// + void SaveShopPlanesToExcelFile(ReportBindingModel model); + + /// + /// Сохранение заказов с группировкой по датам в файл-Pdf + /// + /// + void SaveGroupOrdersToPdfFile(ReportBindingModel model); + } +} diff --git a/AircraftPlant/AircraftPlantContracts/SearchModels/OrderSearchModel.cs b/AircraftPlant/AircraftPlantContracts/SearchModels/OrderSearchModel.cs index 3ff9399..f9ecf3c 100644 --- a/AircraftPlant/AircraftPlantContracts/SearchModels/OrderSearchModel.cs +++ b/AircraftPlant/AircraftPlantContracts/SearchModels/OrderSearchModel.cs @@ -16,5 +16,15 @@ namespace AircraftPlantContracts.SearchModels /// Идентификатор /// public int? Id { get; set; } + + /// + /// Начало периода выборки данных + /// + public DateTime? DateFrom { get; set; } + + /// + /// Конец периода выборки данных + /// + public DateTime? DateTo { get; set; } } } diff --git a/AircraftPlant/AircraftPlantContracts/ViewModels/ReportGroupOrdersViewModel.cs b/AircraftPlant/AircraftPlantContracts/ViewModels/ReportGroupOrdersViewModel.cs new file mode 100644 index 0000000..b7d8a75 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/ViewModels/ReportGroupOrdersViewModel.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.ViewModels +{ + /// + /// Модель для отчета по заказам с группировкой по датам + /// + public class ReportGroupOrdersViewModel + { + /// + /// Дата создания заказа + /// + public DateTime DateCreate { get; set; } + + /// + /// Количество изделий + /// + public int Count { get; set; } + + /// + /// Сумма заказа + /// + public double Sum { get; set; } + } +} diff --git a/AircraftPlant/AircraftPlantContracts/ViewModels/ReportOrdersViewModel.cs b/AircraftPlant/AircraftPlantContracts/ViewModels/ReportOrdersViewModel.cs new file mode 100644 index 0000000..41b9cf7 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/ViewModels/ReportOrdersViewModel.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.ViewModels +{ + /// + /// Модель для отчета по заказам + /// + public class ReportOrdersViewModel + { + /// + /// Идентификатор заказа + /// + public int Id { get; set; } + + /// + /// Дата создания заказа + /// + public DateTime DateCreate { get; set; } + + /// + /// Название изделия + /// + public string PlaneName { get; set; } = string.Empty; + + /// + /// Сумма заказа + /// + public double Sum { get; set; } + + /// + /// Статус заказа + /// + public string Status { get; set; } = string.Empty; + } +} diff --git a/AircraftPlant/AircraftPlantContracts/ViewModels/ReportPlaneComponentViewModel.cs b/AircraftPlant/AircraftPlantContracts/ViewModels/ReportPlaneComponentViewModel.cs new file mode 100644 index 0000000..d19ea42 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/ViewModels/ReportPlaneComponentViewModel.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.ViewModels +{ + /// + /// Модель для отчета по компонентам + /// + public class ReportPlaneComponentViewModel + { + /// + /// Название изделия + /// + public string PlaneName { get; set; } = string.Empty; + + /// + /// Итоговое количество + /// + public int TotalCount { get; set; } + + /// + /// Список компонентов изделия + /// + public List<(string Component, int Count)> Components { get; set; } = new(); + } +} diff --git a/AircraftPlant/AircraftPlantContracts/ViewModels/ReportShopPlanesViewModel.cs b/AircraftPlant/AircraftPlantContracts/ViewModels/ReportShopPlanesViewModel.cs new file mode 100644 index 0000000..290471b --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/ViewModels/ReportShopPlanesViewModel.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.ViewModels +{ + /// + /// Модель для отчета по магазинам с расшифровкой по изделиям + /// + public class ReportShopPlanesViewModel + { + /// + /// Название магазина + /// + public string ShopName { get; set; } = string.Empty; + + /// + /// Максимальное количество изделий + /// + public int TotalCount { get; set; } + + /// + /// Список изделий в магазине + /// + public List<(string Plane, int Count)> Planes { get; set; } = new(); + } +} diff --git a/AircraftPlant/AircraftPlantDatabaseImplement/Implements/OrderStorage.cs b/AircraftPlant/AircraftPlantDatabaseImplement/Implements/OrderStorage.cs index fc05f33..4beeb66 100644 --- a/AircraftPlant/AircraftPlantDatabaseImplement/Implements/OrderStorage.cs +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Implements/OrderStorage.cs @@ -35,12 +35,21 @@ namespace AircraftPlantDatabaseImplement.Implements /// public List GetFilteredList(OrderSearchModel model) { - if (!model.Id.HasValue) + if (!model.Id.HasValue && (!model.DateFrom.HasValue || !model.DateTo.HasValue)) { return new(); } using var context = new AircraftPlantDatabase(); + + if (model.DateFrom.HasValue) + { + return context.Orders + .Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo) + .Select(x => GetViewModel(x)) + .ToList(); + } + return context.Orders .Where(x => x.Id.Equals(model.Id)) .Select(x => GetViewModel(x)) diff --git a/AircraftPlant/AircraftPlantFileImplement/Implements/OrderStorage.cs b/AircraftPlant/AircraftPlantFileImplement/Implements/OrderStorage.cs index 61e31bd..cef7c62 100644 --- a/AircraftPlant/AircraftPlantFileImplement/Implements/OrderStorage.cs +++ b/AircraftPlant/AircraftPlantFileImplement/Implements/OrderStorage.cs @@ -48,11 +48,19 @@ namespace AircraftPlantFileImplement.Implements /// public List GetFilteredList(OrderSearchModel model) { - if (!model.Id.HasValue) + if (!model.Id.HasValue || !model.DateFrom.HasValue || !model.DateTo.HasValue) { return new(); } + if (model.DateFrom.HasValue) + { + return _source.Orders + .Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo) + .Select(x => GetViewModel(x)) + .ToList(); + } + return _source.Orders .Where(x => x.Id.Equals(model.Id)) .Select(x => GetViewModel(x)) diff --git a/AircraftPlant/AircraftPlantListImplement/Implements/OrderStorage.cs b/AircraftPlant/AircraftPlantListImplement/Implements/OrderStorage.cs index cdd1b93..779d7c8 100644 --- a/AircraftPlant/AircraftPlantListImplement/Implements/OrderStorage.cs +++ b/AircraftPlant/AircraftPlantListImplement/Implements/OrderStorage.cs @@ -51,11 +51,23 @@ namespace AircraftPlantListImplement.Implements public List GetFilteredList(OrderSearchModel model) { var result = new List(); - if (!model.Id.HasValue) + if (!model.Id.HasValue || !model.DateFrom.HasValue || !model.DateTo.HasValue) { return result; } + if (model.DateFrom.HasValue) + { + foreach (var order in _source.Orders) + { + if (order.DateCreate >= model.DateFrom && order.DateCreate <= model.DateTo) + { + result.Add(GetViewModel(order)); + } + } + return result; + } + foreach (var order in _source.Orders) { if (order.Id == model.Id) diff --git a/AircraftPlant/AircraftPlantView/AircraftPlantView.csproj b/AircraftPlant/AircraftPlantView/AircraftPlantView.csproj index d6dc72f..354cd26 100644 --- a/AircraftPlant/AircraftPlantView/AircraftPlantView.csproj +++ b/AircraftPlant/AircraftPlantView/AircraftPlantView.csproj @@ -26,6 +26,7 @@ + diff --git a/AircraftPlant/AircraftPlantView/FormMain.Designer.cs b/AircraftPlant/AircraftPlantView/FormMain.Designer.cs index bbefa1b..ab50ec4 100644 --- a/AircraftPlant/AircraftPlantView/FormMain.Designer.cs +++ b/AircraftPlant/AircraftPlantView/FormMain.Designer.cs @@ -39,8 +39,15 @@ компонентыToolStripMenuItem = new ToolStripMenuItem(); изделияToolStripMenuItem = new ToolStripMenuItem(); магазиныToolStripMenuItem = new ToolStripMenuItem(); + отчетыToolStripMenuItem = new ToolStripMenuItem(); + изделияToolStripMenuItem1 = new ToolStripMenuItem(); + изделияСКомпонентамиToolStripMenuItem = new ToolStripMenuItem(); + списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); buttonAddPlaneInShop = new Button(); buttonSellPlanes = new Button(); + заказыСГруппировкойToolStripMenuItem = new ToolStripMenuItem(); + списокМагазиновToolStripMenuItem = new ToolStripMenuItem(); + ассортиментМагазиновToolStripMenuItem = new ToolStripMenuItem(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); menuStrip.SuspendLayout(); SuspendLayout(); @@ -115,7 +122,7 @@ // // menuStrip // - menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem }); + menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; menuStrip.Size = new Size(984, 24); @@ -150,6 +157,34 @@ магазиныToolStripMenuItem.Text = "Магазины"; магазиныToolStripMenuItem.Click += магазиныToolStripMenuItem_Click; // + // отчетыToolStripMenuItem + // + отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { изделияToolStripMenuItem1, изделияСКомпонентамиToolStripMenuItem, списокЗаказовToolStripMenuItem, заказыСГруппировкойToolStripMenuItem, списокМагазиновToolStripMenuItem, ассортиментМагазиновToolStripMenuItem }); + отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; + отчетыToolStripMenuItem.Size = new Size(60, 20); + отчетыToolStripMenuItem.Text = "Отчеты"; + // + // изделияToolStripMenuItem1 + // + изделияToolStripMenuItem1.Name = "изделияToolStripMenuItem1"; + изделияToolStripMenuItem1.Size = new Size(215, 22); + изделияToolStripMenuItem1.Text = "Изделия"; + изделияToolStripMenuItem1.Click += изделияToolStripMenuItem1_Click; + // + // изделияСКомпонентамиToolStripMenuItem + // + изделияСКомпонентамиToolStripMenuItem.Name = "изделияСКомпонентамиToolStripMenuItem"; + изделияСКомпонентамиToolStripMenuItem.Size = new Size(215, 22); + изделияСКомпонентамиToolStripMenuItem.Text = "Изделия с компонентами"; + изделияСКомпонентамиToolStripMenuItem.Click += изделияСКомпонентамиToolStripMenuItem_Click; + // + // списокЗаказовToolStripMenuItem + // + списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; + списокЗаказовToolStripMenuItem.Size = new Size(215, 22); + списокЗаказовToolStripMenuItem.Text = "Список заказов"; + списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; + // // buttonAddPlaneInShop // buttonAddPlaneInShop.Location = new Point(822, 210); @@ -170,6 +205,27 @@ buttonSellPlanes.UseVisualStyleBackColor = true; buttonSellPlanes.Click += buttonSellPlanes_Click; // + // заказыСГруппировкойToolStripMenuItem + // + заказыСГруппировкойToolStripMenuItem.Name = "заказыСГруппировкойToolStripMenuItem"; + заказыСГруппировкойToolStripMenuItem.Size = new Size(250, 22); + заказыСГруппировкойToolStripMenuItem.Text = "Список заказов с группировкой"; + заказыСГруппировкойToolStripMenuItem.Click += заказыСГруппировкойToolStripMenuItem_Click; + // + // списокМагазиновToolStripMenuItem + // + списокМагазиновToolStripMenuItem.Name = "списокМагазиновToolStripMenuItem"; + списокМагазиновToolStripMenuItem.Size = new Size(250, 22); + списокМагазиновToolStripMenuItem.Text = "Список магазинов"; + списокМагазиновToolStripMenuItem.Click += списокМагазиновToolStripMenuItem_Click; + // + // ассортиментМагазиновToolStripMenuItem + // + ассортиментМагазиновToolStripMenuItem.Name = "ассортиментМагазиновToolStripMenuItem"; + ассортиментМагазиновToolStripMenuItem.Size = new Size(250, 22); + ассортиментМагазиновToolStripMenuItem.Text = "Ассортимент магазинов"; + ассортиментМагазиновToolStripMenuItem.Click += ассортиментМагазиновToolStripMenuItem_Click; + // // FormMain // AutoScaleDimensions = new SizeF(7F, 15F); @@ -210,5 +266,12 @@ private ToolStripMenuItem магазиныToolStripMenuItem; private Button buttonAddPlaneInShop; private Button buttonSellPlanes; + private ToolStripMenuItem отчетыToolStripMenuItem; + private ToolStripMenuItem изделияToolStripMenuItem1; + private ToolStripMenuItem изделияСКомпонентамиToolStripMenuItem; + private ToolStripMenuItem списокЗаказовToolStripMenuItem; + private ToolStripMenuItem заказыСГруппировкойToolStripMenuItem; + private ToolStripMenuItem списокМагазиновToolStripMenuItem; + private ToolStripMenuItem ассортиментМагазиновToolStripMenuItem; } } \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormMain.cs b/AircraftPlant/AircraftPlantView/FormMain.cs index 8241ddb..6ba6319 100644 --- a/AircraftPlant/AircraftPlantView/FormMain.cs +++ b/AircraftPlant/AircraftPlantView/FormMain.cs @@ -27,18 +27,24 @@ namespace AircraftPlantView /// /// Бизнес-логика для заказов /// - private readonly IOrderLogic _logic; + private readonly IOrderLogic _orderLogic; + + /// + /// Взаимодействие с отчетами + /// + private readonly IReportLogic _reportLogic; /// /// Конструктор /// /// /// - public FormMain(ILogger logger, IOrderLogic logic) + public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic) { InitializeComponent(); _logger = logger; - _logic = logic; + _orderLogic = orderLogic; + _reportLogic = reportLogic; } /// @@ -93,6 +99,92 @@ namespace AircraftPlantView } } + /// + /// Вывести отчет по изделиям + /// + /// + /// + private void изделияToolStripMenuItem1_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + _reportLogic.SavePlanesToWordFile(new ReportBindingModel { FileName = dialog.FileName }); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + + /// + /// Получить отчет по изделиям с расшифровкой по компонентам + /// + /// + /// + private void изделияСКомпонентамиToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportPlaneComponents)); + if (service is FormReportPlaneComponents form) + { + form.ShowDialog(); + } + } + + /// + /// Получить отчет по заказам + /// + /// + /// + private void списокЗаказовToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); + if (service is FormReportOrders form) + { + form.ShowDialog(); + } + } + + /// + /// Получить отчет по заказам с группировкой по датам + /// + /// + /// + private void заказыСГруппировкойToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportGroupOrders)); + if (service is FormReportGroupOrders form) + { + form.ShowDialog(); + } + } + + /// + /// Получить отчет со списком магазинов + /// + /// + /// + private void списокМагазиновToolStripMenuItem_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + _reportLogic.SaveShopsToWordFile(new ReportBindingModel { FileName = dialog.FileName }); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + + /// + /// Получить отчет по ассортименту магазинов + /// + /// + /// + private void ассортиментМагазиновToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportShopPlanes)); + if (service is FormReportShopPlanes form) + { + form.ShowDialog(); + } + } + /// /// Кнопка "Создать заказ" /// @@ -121,7 +213,7 @@ namespace AircraftPlantView _logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id); try { - var operationResult = _logic.TakeOrderInWork(new OrderBindingModel { Id = id }); + var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel { Id = id }); if (!operationResult) { throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); @@ -149,7 +241,7 @@ namespace AircraftPlantView _logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id); try { - var operationResult = _logic.DeliveryOrder(new OrderBindingModel { Id = id }); + var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel { Id = id }); if (!operationResult) { throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); @@ -177,7 +269,7 @@ namespace AircraftPlantView _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); try { - var operationResult = _logic.FinishOrder(new OrderBindingModel { Id = id }); + var operationResult = _orderLogic.FinishOrder(new OrderBindingModel { Id = id }); if (!operationResult) { throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); @@ -239,7 +331,7 @@ namespace AircraftPlantView _logger.LogInformation("Загрузка заказов"); try { - var list = _logic.ReadList(null); + var list = _orderLogic.ReadList(null); if (list != null) { dataGridView.DataSource = list; diff --git a/AircraftPlant/AircraftPlantView/FormReportGroupOrders.Designer.cs b/AircraftPlant/AircraftPlantView/FormReportGroupOrders.Designer.cs new file mode 100644 index 0000000..66e1889 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormReportGroupOrders.Designer.cs @@ -0,0 +1,85 @@ +namespace AircraftPlantView +{ + partial class FormReportGroupOrders + { + /// + /// 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() + { + panelControl = new Panel(); + buttonMake = new Button(); + buttonToPdf = new Button(); + panelControl.SuspendLayout(); + SuspendLayout(); + // + // panelControl + // + panelControl.Controls.Add(buttonMake); + panelControl.Controls.Add(buttonToPdf); + panelControl.Dock = DockStyle.Top; + panelControl.Location = new Point(0, 0); + panelControl.Name = "panelControl"; + panelControl.Size = new Size(800, 47); + panelControl.TabIndex = 5; + // + // buttonMake + // + buttonMake.Location = new Point(589, 12); + buttonMake.Name = "buttonMake"; + buttonMake.Size = new Size(118, 23); + buttonMake.TabIndex = 5; + buttonMake.Text = "Сформировать"; + buttonMake.UseVisualStyleBackColor = true; + buttonMake.Click += buttonMake_Click; + // + // buttonToPdf + // + buttonToPdf.Location = new Point(713, 12); + buttonToPdf.Name = "buttonToPdf"; + buttonToPdf.Size = new Size(75, 23); + buttonToPdf.TabIndex = 4; + buttonToPdf.Text = "В Pdf"; + buttonToPdf.UseVisualStyleBackColor = true; + buttonToPdf.Click += buttonToPdf_Click; + // + // FormReportGroupOrders + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 361); + Controls.Add(panelControl); + Name = "FormReportGroupOrders"; + Text = "Заказы с группировкой по датам"; + panelControl.ResumeLayout(false); + ResumeLayout(false); + } + + #endregion + + private Panel panelControl; + private Button buttonMake; + private Button buttonToPdf; + } +} \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormReportGroupOrders.cs b/AircraftPlant/AircraftPlantView/FormReportGroupOrders.cs new file mode 100644 index 0000000..eb89468 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormReportGroupOrders.cs @@ -0,0 +1,107 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.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 AircraftPlantView +{ + /// + /// Форма формирования отчета по заказам с группировкой по датам + /// + public partial class FormReportGroupOrders : Form + { + /// + /// Отчет + /// + private readonly ReportViewer reportViewer; + + /// + /// Логгер + /// + private readonly ILogger _logger; + + /// + /// Бизнес-логика для отчетов + /// + private readonly IReportLogic _logic; + + /// + /// Конструктор + /// + public FormReportGroupOrders(ILogger logger, IReportLogic logic) + { + InitializeComponent(); + + _logger = logger; + _logic = logic; + + reportViewer = new ReportViewer + { + Dock = DockStyle.Fill + }; + reportViewer.LocalReport.LoadReportDefinition(new FileStream("ReportGroupOrders.rdlc", FileMode.Open)); + Controls.Clear(); + Controls.Add(reportViewer); + Controls.Add(panelControl); + } + + /// + /// Кнопка "Сформировать" + /// + /// + /// + private void buttonMake_Click(object sender, EventArgs e) + { + try + { + var dataSource = _logic.GetGroupOrders(); + var source = new ReportDataSource("DataSetGroupOrders", dataSource); + reportViewer.LocalReport.DataSources.Clear(); + reportViewer.LocalReport.DataSources.Add(source); + reportViewer.RefreshReport(); + _logger.LogInformation("Загрузка списка заказов с группировкой по датам"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки списка заказов c группировкой по датам"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + /// + /// Кнопка "В Pdf" + /// + /// + /// + private void buttonToPdf_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "pdf|*.pdf" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + try + { + _logic.SaveGroupOrdersToPdfFile(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/AircraftPlant/AircraftPlantView/FormReportGroupOrders.resx b/AircraftPlant/AircraftPlantView/FormReportGroupOrders.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormReportGroupOrders.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/AircraftPlant/AircraftPlantView/FormReportOrders.Designer.cs b/AircraftPlant/AircraftPlantView/FormReportOrders.Designer.cs new file mode 100644 index 0000000..4a70fe8 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormReportOrders.Designer.cs @@ -0,0 +1,130 @@ +namespace AircraftPlantView +{ + 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() + { + labelFrom = new Label(); + dateTimePickerFrom = new DateTimePicker(); + dateTimePickerTo = new DateTimePicker(); + labelTo = new Label(); + panelControl = new Panel(); + buttonToPdf = new Button(); + buttonMake = new Button(); + panelControl.SuspendLayout(); + SuspendLayout(); + // + // labelFrom + // + labelFrom.AutoSize = true; + labelFrom.Location = new Point(7, 18); + labelFrom.Name = "labelFrom"; + labelFrom.Size = new Size(15, 15); + labelFrom.TabIndex = 0; + labelFrom.Text = "С"; + // + // dateTimePickerFrom + // + dateTimePickerFrom.Location = new Point(28, 12); + dateTimePickerFrom.Name = "dateTimePickerFrom"; + dateTimePickerFrom.Size = new Size(200, 23); + dateTimePickerFrom.TabIndex = 1; + // + // dateTimePickerTo + // + dateTimePickerTo.Location = new Point(261, 12); + dateTimePickerTo.Name = "dateTimePickerTo"; + dateTimePickerTo.Size = new Size(200, 23); + dateTimePickerTo.TabIndex = 2; + // + // labelTo + // + labelTo.AutoSize = true; + labelTo.Location = new Point(234, 18); + labelTo.Name = "labelTo"; + labelTo.Size = new Size(21, 15); + labelTo.TabIndex = 3; + labelTo.Text = "по"; + // + // panelControl + // + panelControl.Controls.Add(buttonMake); + panelControl.Controls.Add(buttonToPdf); + panelControl.Controls.Add(dateTimePickerTo); + panelControl.Controls.Add(labelTo); + panelControl.Controls.Add(labelFrom); + panelControl.Controls.Add(dateTimePickerFrom); + panelControl.Dock = DockStyle.Top; + panelControl.Location = new Point(0, 0); + panelControl.Name = "panelControl"; + panelControl.Size = new Size(800, 47); + panelControl.TabIndex = 4; + // + // buttonToPdf + // + buttonToPdf.Location = new Point(713, 12); + buttonToPdf.Name = "buttonToPdf"; + buttonToPdf.Size = new Size(75, 23); + buttonToPdf.TabIndex = 4; + buttonToPdf.Text = "В Pdf"; + buttonToPdf.UseVisualStyleBackColor = true; + buttonToPdf.Click += buttonToPdf_Click; + // + // buttonMake + // + buttonMake.Location = new Point(589, 12); + buttonMake.Name = "buttonMake"; + buttonMake.Size = new Size(118, 23); + buttonMake.TabIndex = 5; + buttonMake.Text = "Сформировать"; + buttonMake.UseVisualStyleBackColor = true; + buttonMake.Click += buttonMake_Click; + // + // FormReportOrders + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 361); + Controls.Add(panelControl); + Name = "FormReportOrders"; + Text = "Заказы"; + panelControl.ResumeLayout(false); + panelControl.PerformLayout(); + ResumeLayout(false); + } + + #endregion + + private Label labelFrom; + private DateTimePicker dateTimePickerFrom; + private DateTimePicker dateTimePickerTo; + private Label labelTo; + private Panel panelControl; + private Button buttonToPdf; + private Button buttonMake; + } +} \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormReportOrders.cs b/AircraftPlant/AircraftPlantView/FormReportOrders.cs new file mode 100644 index 0000000..5527554 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormReportOrders.cs @@ -0,0 +1,125 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.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 AircraftPlantView +{ + /// + /// Форма формирования отчета по заказам + /// + 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(panelControl); + } + + /// + /// Кнопка "Сформировать" + /// + /// + /// + 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 = dateTimePickerFrom.Value, + DateTo = dateTimePickerTo.Value + }); + 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); + } + } + + /// + /// Кнопка "В Pdf" + /// + /// + /// + private void buttonToPdf_Click(object sender, EventArgs e) + { + 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 = dateTimePickerFrom.Value, + DateTo = dateTimePickerTo.Value + }); + _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/AircraftPlant/AircraftPlantView/FormReportOrders.resx b/AircraftPlant/AircraftPlantView/FormReportOrders.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormReportOrders.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/AircraftPlant/AircraftPlantView/FormReportPlaneComponents.Designer.cs b/AircraftPlant/AircraftPlantView/FormReportPlaneComponents.Designer.cs new file mode 100644 index 0000000..221eee6 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormReportPlaneComponents.Designer.cs @@ -0,0 +1,110 @@ +namespace AircraftPlantView +{ + partial class FormReportPlaneComponents + { + /// + /// 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(); + ColumnPlane = new DataGridViewTextBoxColumn(); + ColumnComponent = new DataGridViewTextBoxColumn(); + ColumnCount = new DataGridViewTextBoxColumn(); + buttonSaveToExcel = new Button(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.BackgroundColor = Color.White; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnPlane, ColumnComponent, ColumnCount }); + dataGridView.Dock = DockStyle.Bottom; + dataGridView.GridColor = Color.Black; + dataGridView.Location = new Point(0, 29); + dataGridView.MultiSelect = false; + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowTemplate.Height = 25; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.Size = new Size(584, 332); + dataGridView.TabIndex = 0; + // + // ColumnPlane + // + ColumnPlane.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + ColumnPlane.HeaderText = "Изделие"; + ColumnPlane.Name = "ColumnPlane"; + ColumnPlane.ReadOnly = true; + // + // ColumnComponent + // + ColumnComponent.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + ColumnComponent.HeaderText = "Компонент"; + ColumnComponent.Name = "ColumnComponent"; + ColumnComponent.ReadOnly = true; + // + // ColumnCount + // + ColumnCount.HeaderText = "Количество"; + ColumnCount.Name = "ColumnCount"; + ColumnCount.ReadOnly = true; + // + // buttonSaveToExcel + // + buttonSaveToExcel.Dock = DockStyle.Top; + buttonSaveToExcel.Location = new Point(0, 0); + buttonSaveToExcel.Name = "buttonSaveToExcel"; + buttonSaveToExcel.Size = new Size(584, 23); + buttonSaveToExcel.TabIndex = 1; + buttonSaveToExcel.Text = "Сохранить в Excel"; + buttonSaveToExcel.UseVisualStyleBackColor = true; + buttonSaveToExcel.Click += buttonSaveToExcel_Click; + // + // FormReportPlaneComponents + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(584, 361); + Controls.Add(buttonSaveToExcel); + Controls.Add(dataGridView); + Name = "FormReportPlaneComponents"; + Text = "Изделия с компонентами"; + Load += FormReportPlaneComponents_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + private DataGridViewTextBoxColumn ColumnPlane; + private DataGridViewTextBoxColumn ColumnComponent; + private DataGridViewTextBoxColumn ColumnCount; + private Button buttonSaveToExcel; + } +} \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormReportPlaneComponents.cs b/AircraftPlant/AircraftPlantView/FormReportPlaneComponents.cs new file mode 100644 index 0000000..b926bc7 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormReportPlaneComponents.cs @@ -0,0 +1,101 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.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 AircraftPlantView +{ + /// + /// Форма формирования отчета по изделиям с расшифровкой по компонентам + /// + public partial class FormReportPlaneComponents : Form + { + /// + /// Логгер + /// + private readonly ILogger _logger; + + /// + /// Взаимодействие с отчетами + /// + private readonly IReportLogic _logic; + + /// + /// Конструктор + /// + public FormReportPlaneComponents(ILogger logger, IReportLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + /// + /// Загрузка данных + /// + /// + /// + private void FormReportPlaneComponents_Load(object sender, EventArgs e) + { + try + { + var dict = _logic.GetPlaneComponents(); + if (dict != null) + { + dataGridView.Rows.Clear(); + foreach (var elem in dict) + { + dataGridView.Rows.Add(new object[] { elem.PlaneName, "", "" }); + 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); + } + } + + /// + /// Кнопка "Сохранить в Excel" + /// + /// + /// + private void buttonSaveToExcel_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "xlsx|*.xlsx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + try + { + _logic.SavePlaneComponentsToExcelFile(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/AircraftPlant/AircraftPlantView/FormReportPlaneComponents.resx b/AircraftPlant/AircraftPlantView/FormReportPlaneComponents.resx new file mode 100644 index 0000000..c01596c --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormReportPlaneComponents.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + True + + + True + + + True + + \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormReportShopPlanes.Designer.cs b/AircraftPlant/AircraftPlantView/FormReportShopPlanes.Designer.cs new file mode 100644 index 0000000..9f95e2d --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormReportShopPlanes.Designer.cs @@ -0,0 +1,110 @@ +namespace AircraftPlantView +{ + partial class FormReportShopPlanes + { + /// + /// 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() + { + buttonSaveToExcel = new Button(); + dataGridView = new DataGridView(); + ColumnShopName = new DataGridViewTextBoxColumn(); + ColumnPlaneName = new DataGridViewTextBoxColumn(); + ColumnCount = new DataGridViewTextBoxColumn(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // buttonSaveToExcel + // + buttonSaveToExcel.Dock = DockStyle.Top; + buttonSaveToExcel.Location = new Point(0, 0); + buttonSaveToExcel.Name = "buttonSaveToExcel"; + buttonSaveToExcel.Size = new Size(584, 23); + buttonSaveToExcel.TabIndex = 2; + buttonSaveToExcel.Text = "Сохранить в Excel"; + buttonSaveToExcel.UseVisualStyleBackColor = true; + buttonSaveToExcel.Click += buttonSaveToExcel_Click; + // + // dataGridView + // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.BackgroundColor = Color.White; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnShopName, ColumnPlaneName, ColumnCount }); + dataGridView.Dock = DockStyle.Bottom; + dataGridView.GridColor = Color.Black; + dataGridView.Location = new Point(0, 29); + dataGridView.MultiSelect = false; + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowTemplate.Height = 25; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.Size = new Size(584, 332); + dataGridView.TabIndex = 3; + // + // ColumnShopName + // + ColumnShopName.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + ColumnShopName.HeaderText = "Магазин"; + ColumnShopName.Name = "ColumnShopName"; + ColumnShopName.ReadOnly = true; + // + // ColumnPlaneName + // + ColumnPlaneName.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + ColumnPlaneName.HeaderText = "Изделие"; + ColumnPlaneName.Name = "ColumnPlaneName"; + ColumnPlaneName.ReadOnly = true; + // + // ColumnCount + // + ColumnCount.HeaderText = "Количество"; + ColumnCount.Name = "ColumnCount"; + ColumnCount.ReadOnly = true; + // + // FormReportShopPlanes + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(584, 361); + Controls.Add(dataGridView); + Controls.Add(buttonSaveToExcel); + Name = "FormReportShopPlanes"; + Text = "Ассортимент магазинов"; + Load += FormReportShopPlanes_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private Button buttonSaveToExcel; + private DataGridView dataGridView; + private DataGridViewTextBoxColumn ColumnShopName; + private DataGridViewTextBoxColumn ColumnPlaneName; + private DataGridViewTextBoxColumn ColumnCount; + } +} \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormReportShopPlanes.cs b/AircraftPlant/AircraftPlantView/FormReportShopPlanes.cs new file mode 100644 index 0000000..60c13a2 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormReportShopPlanes.cs @@ -0,0 +1,101 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.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 AircraftPlantView +{ + /// + /// Форма формирования отчета с ассортиментом магазинов + /// + public partial class FormReportShopPlanes : Form + { + /// + /// Логгер + /// + private readonly ILogger _logger; + + /// + /// Взаимодействие с отчетами + /// + private readonly IReportLogic _logic; + + /// + /// Конструктор + /// + public FormReportShopPlanes(ILogger logger, IReportLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + /// + /// Загрузка данных + /// + /// + /// + private void FormReportShopPlanes_Load(object sender, EventArgs e) + { + try + { + var dict = _logic.GetShopPlanes(); + if (dict != null) + { + dataGridView.Rows.Clear(); + foreach (var elem in dict) + { + dataGridView.Rows.Add(new object[] { elem.ShopName, "", "" }); + foreach (var listElem in elem.Planes) + { + 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.SaveShopPlanesToExcelFile(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/AircraftPlant/AircraftPlantView/FormReportShopPlanes.resx b/AircraftPlant/AircraftPlantView/FormReportShopPlanes.resx new file mode 100644 index 0000000..a43dac9 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormReportShopPlanes.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + True + + + True + + + True + + + True + + + True + + + True + + \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/Program.cs b/AircraftPlant/AircraftPlantView/Program.cs index 594f730..31a3744 100644 --- a/AircraftPlant/AircraftPlantView/Program.cs +++ b/AircraftPlant/AircraftPlantView/Program.cs @@ -1,4 +1,6 @@ using AircraftPlantBusinessLogic.BusinessLogics; +using AircraftPlantBusinessLogic.OfficePackage.Implements; +using AircraftPlantBusinessLogic.OfficePackage; using AircraftPlantContracts.BusinessLogicsContracts; using AircraftPlantContracts.StoragesContracts; using AircraftPlantDatabaseImplement.Implements; @@ -54,8 +56,13 @@ namespace AircraftPlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -67,6 +74,10 @@ namespace AircraftPlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); } } } \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/ReportGroupOrders.rdlc b/AircraftPlant/AircraftPlantView/ReportGroupOrders.rdlc new file mode 100644 index 0000000..645722a --- /dev/null +++ b/AircraftPlant/AircraftPlantView/ReportGroupOrders.rdlc @@ -0,0 +1,441 @@ + + + 0 + + + + System.Data.DataSet + /* Local Connection */ + + 20791c83-cee8-4a38-bbd0-245fc17cefb3 + + + + + + AircraftPlantContractsViewModels + /* Local Query */ + + + + DateCreate + System.DateTime + + + Count + System.Int32 + + + Sum + System.Decimal + + + + AircraftPlantContracts.ViewModels + ReportGroupOrdersViewModel + AircraftPlantContracts.ViewModels.ReportGroupOrdersViewModel, AircraftPlantContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + + + + + + + + + true + true + + + + + Отчёт по заказам + + + + 0.6cm + 16.51cm + + + Middle + 2pt + 2pt + 2pt + 2pt + + + + true + true + + + + + =Parameters!ReportParameterPeriod.Value + + + + + + + ReportParameterPeriod + 0.6cm + 0.6cm + 16.51cm + 1 + + + 2pt + 2pt + 2pt + 2pt + + + + + + + 3.90406cm + + + 3.97461cm + + + 3.65711cm + + + + + 0.6cm + + + + + true + true + + + + + Дата создания + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Количество заказов + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Общая сумма заказов + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + 0.6cm + + + + + true + true + + + + + =Fields!DateCreate.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!Count.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!Sum.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + + + + + + + + + + + + After + + + + + + + DataSetGroupOrders + 1.88242cm + 2.68676cm + 1.2cm + 11.53578cm + 2 + + + + + + true + true + + + + + Итого: + + + + 3.29409cm + 8.06542cm + 0.6cm + 2.5cm + 3 + + + 2pt + 2pt + 2pt + 2pt + + + + true + true + + + + + =Sum(Fields!Sum.Value, "DataSetGroupOrders") + + + + + + + 3.29409cm + 10.70653cm + 0.6cm + 3.48072cm + 4 + + + 2pt + 2pt + 2pt + 2pt + + + + 2in + + + + + + + 1.00217cm + 22.69068cm + + + Middle + 2pt + 2pt + 2pt + 2pt + + + + true + true + + + + + =Parameters!ReportParameterPeriod.Value + + + + + + + ReportParameterPeriod + 1.07272cm + 0.98637cm + 22.69068cm + 1 + + + Middle + 2pt + 2pt + 2pt + 2pt + + + + + + + 2.5cm + + + 3.0715cm + + + 8.2785cm + + + 2.5cm + + + 5.37866cm + + + + + 0.6cm + + + + + true + true + + + + + Номер + + + + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Дата создания + + + + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Изделие + + + + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Статус + + + + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Сумма + + + + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + 0.6cm + + + + + true + true + + + + + =Fields!Id.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!DateCreate.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!PlaneName.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!Status.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!Sum.Value + + + + Sum + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + + + + + + + + + + + + + + After + + + + + + + DataSetOrders + 2.54564cm + 0.4572cm + 1.2cm + 21.72866cm + 2 + + + + + + true + true + + + + + Итого: + + + + + + + Textbox11 + 4.26014cm + 14.3072cm + 0.6cm + 2.5cm + 3 + + + Middle + 2pt + 2pt + 2pt + 2pt + + + + true + true + + + + + =Sum(Fields!Sum.Value, "DataSetOrders") + + + + + + + Textbox12 + 4.26014cm + 16.8072cm + 0.6cm + 2.5cm + 4 + + + Middle + 2pt + 2pt + 2pt + 2pt + + + + 2.1639in +