diff --git a/DiningRoom/DiningRoomBusinessLogic/BusinessLogic/ReportLogic.cs b/DiningRoom/DiningRoomBusinessLogic/BusinessLogic/ReportLogic.cs index 430e28e..3493045 100644 --- a/DiningRoom/DiningRoomBusinessLogic/BusinessLogic/ReportLogic.cs +++ b/DiningRoom/DiningRoomBusinessLogic/BusinessLogic/ReportLogic.cs @@ -37,10 +37,26 @@ namespace DiningRoomBusinessLogic.BusinessLogic { return _componentStorage.GetComponentsByDate(Report); } - - public void SaveReportToWordFile(ReportBindingModel Model) + public void SaveComponentsToPdfFile(ReportBindingModel model) { - throw new NotImplementedException(); + _saveToPdf.CreateDoc(new PdfInfo + { + FileName = model.FileName, + Title = "Список заказов", + DateFrom = model.DateFrom!.Value, + DateTo = model.DateTo!.Value, + Components = GetReportComponentsByCardDate(model) + }); + } + + public void SaveReportToWordFile(ReportBindingModel Model, List selectedComponents) + { + _saveToWord.CreateDoc(new WordInfo + { + FileName = Model.FileName, + Title = "Список изделий", + ProductComponents = GetReportComponentsWithOrders(selectedComponents) + }); } public void SaveReportToExcelFile(ReportBindingModel Model, List selectedComponents) diff --git a/DiningRoom/DiningRoomBusinessLogic/OfficePackage/AbstractSaveToPdf.cs b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/AbstractSaveToPdf.cs index babca61..3d4af1d 100644 --- a/DiningRoom/DiningRoomBusinessLogic/OfficePackage/AbstractSaveToPdf.cs +++ b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/AbstractSaveToPdf.cs @@ -11,29 +11,52 @@ namespace DiningRoomBusinessLogic.OfficePackage CreateParagraph(new PdfParagraph { Text = info.Title, Style = "NormalTitle", ParagraphAlignment = PdfParagraphAlignmentType.Center }); CreateParagraph(new PdfParagraph { Text = $"с {info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center }); - CreateTable(new List { "2cm", "3cm", "6cm", "6cm", "3cm" }); + // Устанавливаем размеры колонок таблицы + CreateTable(new List { "3cm", "2cm", "6cm", "6cm" }); - CreateRow(new PdfRowParameters - { - Texts = new List { "Номер", "Дата заказа", "Изделие", "Статус", "Сумма" }, - Style = "NormalTitle", - ParagraphAlignment = PdfParagraphAlignmentType.Center - }); + // Группировка данных по ComponentName + var groupedData = info.Components.GroupBy(c => c.ComponentName); - foreach (var order in info.Orders) + foreach (var group in groupedData) { CreateRow(new PdfRowParameters { - Texts = new List { order.Id.ToString(), order.DateCreate.ToShortDateString(), order.ProductName, order.Status.ToString(), order.Sum.ToString() }, - Style = "Normal", + Texts = new List { "Продукт", "Цена", "", "" }, // assuming currency format + Style = "NormalTitle", ParagraphAlignment = PdfParagraphAlignmentType.Left }); + // Добавление строки с именем компонента и его стоимостью + CreateRow(new PdfRowParameters + { + Texts = new List { group.Key, group.First().ComponentCost.ToString("C"),"","" }, // assuming currency format + Style = "NormalTitle", + ParagraphAlignment = PdfParagraphAlignmentType.Left + }); + + // Добавление заголовка для элементов компонента + CreateRow(new PdfRowParameters + { + Texts = new List { "","","Карта", "Блюдо" }, + Style = "NormalTitle", + ParagraphAlignment = PdfParagraphAlignmentType.Center + }); + + // Добавление строк с элементами компонента + foreach (var item in group) + { + CreateRow(new PdfRowParameters + { + Texts = new List { "", "",item.CardName, item.ProductName }, + Style = "Normal", + ParagraphAlignment = PdfParagraphAlignmentType.Left + }); + } } - CreateParagraph(new PdfParagraph { Text = $"Итого: {info.Orders.Sum(x => x.Sum)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Right }); SavePdf(info); } + /// /// Создание doc-файла /// diff --git a/DiningRoom/DiningRoomBusinessLogic/OfficePackage/AbstractSaveToWord.cs b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/AbstractSaveToWord.cs index 3d38d8d..6e6d25d 100644 --- a/DiningRoom/DiningRoomBusinessLogic/OfficePackage/AbstractSaveToWord.cs +++ b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/AbstractSaveToWord.cs @@ -9,6 +9,7 @@ namespace DiningRoomBusinessLogic.OfficePackage { CreateWord(info); + // Добавляем заголовок CreateParagraph(new WordParagraph { Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24", }) }, @@ -19,24 +20,61 @@ namespace DiningRoomBusinessLogic.OfficePackage } }); - foreach (var product in info.Products) + // Группируем компоненты по имени компонента + var groupedComponents = info.ProductComponents + .GroupBy(item => item.ComponentName) + .ToList(); + + // Перебираем группы компонентов и добавляем их в документ + foreach (var group in groupedComponents) { + // Добавляем строку с названием компонента CreateParagraph(new WordParagraph { - Texts = new List<(string, WordTextProperties)> { - (product.ProductName + ": ", new WordTextProperties { Size = "24", Bold = true }), - (Convert.ToInt32(product.Cost).ToString(), new WordTextProperties { Size = "24", })}, + Texts = new List<(string, WordTextProperties)> { ("Продукт - " + group.Key + ":", new WordTextProperties { Size = "24", Bold = true }) }, TextProperties = new WordTextProperties { Size = "24", JustificationType = WordJustificationType.Both } }); + + // Перебираем продукты внутри группы компонентов + foreach (var product in group) + { + // Добавляем информацию о продукте + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { + ("Количество блюд в заказе - "+Convert.ToInt32(product.ProductCount).ToString() + " ", new WordTextProperties { Size = "24" }), + ("Название заказа - "+product.OrderName, new WordTextProperties { Size = "24"}) + }, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Both + } + }); + } + // Добавляем пустые абзацы для создания отступа + for (int i = 0; i < 2; i++) + { + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { ("", new WordTextProperties { Size = "24" }) }, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Both + } + }); + } } SaveWord(info); } + /// /// Создание doc-файла /// diff --git a/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs index 1360633..b5f4514 100644 --- a/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs +++ b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs @@ -12,6 +12,6 @@ namespace DiningRoomBusinessLogic.OfficePackage.HelperModels public DateTime DateTo { get; set; } - public List Orders { get; set; } = new(); + public List Components { get; set; } = new(); } } \ No newline at end of file diff --git a/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/WordInfo.cs b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/WordInfo.cs index f7b2e50..12e9704 100644 --- a/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/WordInfo.cs +++ b/DiningRoom/DiningRoomBusinessLogic/OfficePackage/HelperModels/WordInfo.cs @@ -8,6 +8,6 @@ namespace DiningRoomBusinessLogic.OfficePackage.HelperModels public string Title { get; set; } = string.Empty; - public List Products { get; set; } = new(); + public List ProductComponents { get; set; } = new(); } } \ No newline at end of file diff --git a/DiningRoom/DiningRoomContracts/BusinessLogicContracts/IReportLogic.cs b/DiningRoom/DiningRoomContracts/BusinessLogicContracts/IReportLogic.cs index 3607a0e..e468c42 100644 --- a/DiningRoom/DiningRoomContracts/BusinessLogicContracts/IReportLogic.cs +++ b/DiningRoom/DiningRoomContracts/BusinessLogicContracts/IReportLogic.cs @@ -16,8 +16,9 @@ namespace DiningRoomContracts.BusinessLogicContracts /// List GetReportComponentsByCardDate(ReportBindingModel Report); - void SaveReportToWordFile(ReportBindingModel Model); + void SaveReportToWordFile(ReportBindingModel Model, List selectedComponents); void SaveReportToExcelFile(ReportBindingModel Model, List selectedComponents); - } + void SaveComponentsToPdfFile(ReportBindingModel model); + } } diff --git a/DiningRoom/DiningRoomContracts/ViewModels/GroupedComponentViewModel.cs b/DiningRoom/DiningRoomContracts/ViewModels/GroupedComponentViewModel.cs new file mode 100644 index 0000000..03aee45 --- /dev/null +++ b/DiningRoom/DiningRoomContracts/ViewModels/GroupedComponentViewModel.cs @@ -0,0 +1,9 @@ +using DiningRoomContracts.ViewModels; + +public class GroupedComponentViewModel +{ + public string ComponentName { get; set; } + public double? ComponentCost { get; set; } + public string CardName { get; set; } + public string ProductName { get; set; } +} diff --git a/DiningRoom/DiningRoomContracts/ViewModels/ReportComponentByDateViewModel.cs b/DiningRoom/DiningRoomContracts/ViewModels/ReportComponentByDateViewModel.cs index 9ba29bb..f795517 100644 --- a/DiningRoom/DiningRoomContracts/ViewModels/ReportComponentByDateViewModel.cs +++ b/DiningRoom/DiningRoomContracts/ViewModels/ReportComponentByDateViewModel.cs @@ -16,5 +16,7 @@ public int CardId { get; set; } public string CardName { get; set; } - } + + public DateTime DateCardCreate { get; set; } = DateTime.Now; + } } diff --git a/DiningRoom/DiningRoomDatabaseImplement/Implements/ComponentStorage.cs b/DiningRoom/DiningRoomDatabaseImplement/Implements/ComponentStorage.cs index 00c2a63..4d19980 100644 --- a/DiningRoom/DiningRoomDatabaseImplement/Implements/ComponentStorage.cs +++ b/DiningRoom/DiningRoomDatabaseImplement/Implements/ComponentStorage.cs @@ -130,6 +130,7 @@ namespace DiningRoomDatabaseImplement.Implements .SelectMany(card => card.Drinks .SelectMany(d => d.Components.SelectMany(dc => dc.Component.ProductComponents.Select(pc => new ReportComponentByDateViewModel { + DateCardCreate = card.DateCardCreate, ComponentId = pc.ComponentId, ComponentName = dc.Component.ComponentName, ComponentCost = dc.Component.Cost, diff --git a/DiningRoom/DiningRoomView/DiningRoomView.csproj b/DiningRoom/DiningRoomView/DiningRoomView.csproj index 56cc393..2e26a84 100644 --- a/DiningRoom/DiningRoomView/DiningRoomView.csproj +++ b/DiningRoom/DiningRoomView/DiningRoomView.csproj @@ -9,6 +9,7 @@ + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/DiningRoom/DiningRoomView/FormMain.Designer.cs b/DiningRoom/DiningRoomView/FormMain.Designer.cs index f54b4b0..b29d720 100644 --- a/DiningRoom/DiningRoomView/FormMain.Designer.cs +++ b/DiningRoom/DiningRoomView/FormMain.Designer.cs @@ -38,6 +38,7 @@ заказыПоПродуктамToolStripMenuItem = new ToolStripMenuItem(); wordToolStripMenuItem = new ToolStripMenuItem(); excelToolStripMenuItem = new ToolStripMenuItem(); + продуктыПоБлюдамИКартамToolStripMenuItem = new ToolStripMenuItem(); button1 = new Button(); label1 = new Label(); label2 = new Label(); @@ -102,7 +103,7 @@ // // отчетыToolStripMenuItem // - отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { заказыПоПродуктамToolStripMenuItem }); + отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { заказыПоПродуктамToolStripMenuItem, продуктыПоБлюдамИКартамToolStripMenuItem }); отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; отчетыToolStripMenuItem.Size = new Size(60, 20); отчетыToolStripMenuItem.Text = "Отчеты"; @@ -111,22 +112,30 @@ // заказыПоПродуктамToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { wordToolStripMenuItem, excelToolStripMenuItem }); заказыПоПродуктамToolStripMenuItem.Name = "заказыПоПродуктамToolStripMenuItem"; - заказыПоПродуктамToolStripMenuItem.Size = new Size(192, 22); + заказыПоПродуктамToolStripMenuItem.Size = new Size(246, 22); заказыПоПродуктамToolStripMenuItem.Text = "Заказы по продуктам"; // // wordToolStripMenuItem // wordToolStripMenuItem.Name = "wordToolStripMenuItem"; - wordToolStripMenuItem.Size = new Size(180, 22); + wordToolStripMenuItem.Size = new Size(103, 22); wordToolStripMenuItem.Text = "Word"; + wordToolStripMenuItem.Click += отчетWordToolStripMenuItem_Click; // // excelToolStripMenuItem // excelToolStripMenuItem.Name = "excelToolStripMenuItem"; - excelToolStripMenuItem.Size = new Size(180, 22); + excelToolStripMenuItem.Size = new Size(103, 22); excelToolStripMenuItem.Text = "Excel"; excelToolStripMenuItem.Click += ОтчетыToolStripMenuItem_Click; // + // продуктыПоБлюдамИКартамToolStripMenuItem + // + продуктыПоБлюдамИКартамToolStripMenuItem.Name = "продуктыПоБлюдамИКартамToolStripMenuItem"; + продуктыПоБлюдамИКартамToolStripMenuItem.Size = new Size(246, 22); + продуктыПоБлюдамИКартамToolStripMenuItem.Text = "Продукты по блюдам и картам"; + продуктыПоБлюдамИКартамToolStripMenuItem.Click += списокПродуктовPDFToolStripMenuItem_Click; + // // button1 // button1.Location = new Point(491, 139); @@ -267,5 +276,6 @@ private ToolStripMenuItem заказыПоПродуктамToolStripMenuItem; private ToolStripMenuItem wordToolStripMenuItem; private ToolStripMenuItem excelToolStripMenuItem; + private ToolStripMenuItem продуктыПоБлюдамИКартамToolStripMenuItem; } } \ No newline at end of file diff --git a/DiningRoom/DiningRoomView/FormMain.cs b/DiningRoom/DiningRoomView/FormMain.cs index 9cb04f2..c83e3a0 100644 --- a/DiningRoom/DiningRoomView/FormMain.cs +++ b/DiningRoom/DiningRoomView/FormMain.cs @@ -20,16 +20,21 @@ namespace DiningRoomView { private readonly ILogger _logger; private readonly IProductLogic _productLogic; - private readonly IDrinkLogic _drinkLogic; + private readonly IComponentLogic _logicC; + private readonly IDrinkLogic _drinkLogic; private readonly IUserLogic _userLogic; + private readonly IReportLogic _reportLogic; private UserViewModel? _currentUser; - public FormMain(ILogger logger, IProductLogic productLogic, IDrinkLogic drinkLogic, IUserLogic userLogic) + public List SelectedComp; + public FormMain(ILogger logger, IProductLogic productLogic, IDrinkLogic drinkLogic, IUserLogic userLogic, IReportLogic reportLogic, IComponentLogic logicC) { InitializeComponent(); _logger = logger; _productLogic = productLogic; _drinkLogic = drinkLogic; _userLogic = userLogic; + _reportLogic = reportLogic; + _logicC = logicC; } private void FormMain_Load(object sender, EventArgs e) { @@ -137,6 +142,47 @@ namespace DiningRoomView form.ShowDialog(); } } + private void отчетWordToolStripMenuItem_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + try + { + + using (var formProductSelection = new FormComponentSelection(_logicC, _currentUser)) + { + + if (formProductSelection.ShowDialog() == DialogResult.OK) + { + var selectedProducts = formProductSelection.SelectedProducts; + SelectedComp = selectedProducts; + if (selectedProducts != null && selectedProducts.Any()) + { + var reportData = _reportLogic.GetReportComponentsWithOrders(selectedProducts); + } + } + } + + _logger.LogInformation("Загрузка списка компонентов по заказам"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки списка изделий по компонентам"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + _reportLogic.SaveReportToWordFile(new ReportBindingModel { FileName = dialog.FileName },SelectedComp); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + private void списокПродуктовPDFToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportComponentsByDate)); + if (service is FormReportComponentsByDate form) + { + form.ShowDialog(); + } + } private void КартыToolStripMenuItem_Click(object sender, EventArgs e) { if (_currentUser == null) diff --git a/DiningRoom/DiningRoomView/FormOrdersOld.Designer.cs b/DiningRoom/DiningRoomView/FormOrdersOld.Designer.cs deleted file mode 100644 index 5f129e2..0000000 --- a/DiningRoom/DiningRoomView/FormOrdersOld.Designer.cs +++ /dev/null @@ -1,127 +0,0 @@ -namespace DiningRoomView -{ - partial class FormOrdersOld - { - /// - /// 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(); - ButtonCreateOrder = new Button(); - ButtonRef = new Button(); - ButtonIssuedOrder = new Button(); - ButtonOrderReady = new Button(); - ButtonTakeOrderInWork = new Button(); - ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); - SuspendLayout(); - // - // dataGridView - // - dataGridView.BackgroundColor = SystemColors.ButtonHighlight; - dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.EnableHeadersVisualStyles = false; - dataGridView.Location = new Point(12, 12); - dataGridView.MultiSelect = false; - dataGridView.Name = "dataGridView"; - dataGridView.Size = new Size(600, 371); - dataGridView.TabIndex = 1; - // - // ButtonCreateOrder - // - ButtonCreateOrder.Location = new Point(618, 12); - ButtonCreateOrder.Name = "ButtonCreateOrder"; - ButtonCreateOrder.Size = new Size(122, 23); - ButtonCreateOrder.TabIndex = 2; - ButtonCreateOrder.Text = "Создать заказ"; - ButtonCreateOrder.UseVisualStyleBackColor = true; - ButtonCreateOrder.Click += ButtonCreateOrder_Click; - // - // ButtonRef - // - ButtonRef.Location = new Point(618, 147); - ButtonRef.Name = "ButtonRef"; - ButtonRef.Size = new Size(122, 23); - ButtonRef.TabIndex = 6; - ButtonRef.Text = "Обновить список"; - ButtonRef.UseVisualStyleBackColor = true; - ButtonRef.Click += ButtonRef_Click; - // - // ButtonIssuedOrder - // - ButtonIssuedOrder.Location = new Point(618, 118); - ButtonIssuedOrder.Name = "ButtonIssuedOrder"; - ButtonIssuedOrder.Size = new Size(122, 23); - ButtonIssuedOrder.TabIndex = 5; - ButtonIssuedOrder.Text = "Заказ выдан"; - ButtonIssuedOrder.UseVisualStyleBackColor = true; - ButtonIssuedOrder.Click += ButtonIssuedOrder_Click; - // - // ButtonOrderReady - // - ButtonOrderReady.Location = new Point(618, 89); - ButtonOrderReady.Name = "ButtonOrderReady"; - ButtonOrderReady.Size = new Size(122, 23); - ButtonOrderReady.TabIndex = 4; - ButtonOrderReady.Text = "Заказ готов"; - ButtonOrderReady.UseVisualStyleBackColor = true; - ButtonOrderReady.Click += ButtonOrderReady_Click; - // - // ButtonTakeOrderInWork - // - ButtonTakeOrderInWork.Location = new Point(618, 41); - ButtonTakeOrderInWork.Name = "ButtonTakeOrderInWork"; - ButtonTakeOrderInWork.Size = new Size(122, 42); - ButtonTakeOrderInWork.TabIndex = 3; - ButtonTakeOrderInWork.Text = "Отдать на выполнение"; - ButtonTakeOrderInWork.UseVisualStyleBackColor = true; - ButtonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click; - // - // FormOrders - // - AutoScaleDimensions = new SizeF(7F, 15F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(752, 391); - Controls.Add(ButtonRef); - Controls.Add(ButtonIssuedOrder); - Controls.Add(ButtonOrderReady); - Controls.Add(ButtonTakeOrderInWork); - Controls.Add(ButtonCreateOrder); - Controls.Add(dataGridView); - Name = "FormOrders"; - Text = "Заказы"; - Load += FormMain_Load; - ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); - ResumeLayout(false); - } - - #endregion - private System.Windows.Forms.DataGridView dataGridView; - private System.Windows.Forms.Button ButtonCreateOrder; - private System.Windows.Forms.Button ButtonRef; - private Button ButtonIssuedOrder; - private Button ButtonOrderReady; - private Button ButtonTakeOrderInWork; - } -} \ No newline at end of file diff --git a/DiningRoom/DiningRoomView/FormOrdersOld.cs b/DiningRoom/DiningRoomView/FormOrdersOld.cs deleted file mode 100644 index 8202f68..0000000 --- a/DiningRoom/DiningRoomView/FormOrdersOld.cs +++ /dev/null @@ -1,145 +0,0 @@ -using DiningRoomBusinessLogic.BusinessLogic; -using DiningRoomContracts.BindingModels; -using DiningRoomContracts.BusinessLogicContracts; -using DiningRoomContracts.SearchModels; -using DiningRoomContracts.ViewModels; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; - -namespace DiningRoomView -{ - public partial class FormOrdersOld : Form - { - private readonly ILogger _logger; - private readonly IOrderLogic _orderLogic; - public UserViewModel? _currentUser { get; set; } - public FormOrdersOld(ILogger logger, IOrderLogic orderLogic) - { - InitializeComponent(); - _logger = logger; - _orderLogic = orderLogic; - } - private void FormMain_Load(object sender, EventArgs e) - { - LoadData(); - } - private void LoadData() - { - if (_currentUser == null) - { - MessageBox.Show("Ошибка авторизации", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - _logger.LogInformation("Загрузка заказов"); - // прописать логику - try - { - var list = _orderLogic.ReadList(new OrderSearchModel { UserId = _currentUser.Id }); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["ProductId"].Visible = false; - } - _logger.LogInformation("Загрузка продуктов"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки продуктов"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - private void ButtonCreateOrder_Click(object sender, EventArgs e) - { - if (_currentUser == null) - { - MessageBox.Show("Ошибка авторизации", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); - if (service is FormCreateOrder form) - { - form.UserId = _currentUser.Id; - form.ShowDialog(); - LoadData(); - } - } - private void ButtonTakeOrderInWork_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id); - try - { - var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel { Id = id }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка передачи заказа в работу"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - private void ButtonOrderReady_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id); - try - { - var operationResult = _orderLogic.FinishOrder(new OrderBindingModel { Id = id }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка отметки о готовности заказа"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - private void ButtonIssuedOrder_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); - try - { - var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel { Id = id }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - _logger.LogInformation("Заказ №{id} выдан", id); - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка отметки о выдачи заказа"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - private void ButtonRef_Click(object sender, EventArgs e) - { - LoadData(); - } - } -} diff --git a/DiningRoom/DiningRoomView/FormReportComponentsByDate.Designer.cs b/DiningRoom/DiningRoomView/FormReportComponentsByDate.Designer.cs new file mode 100644 index 0000000..74ef81a --- /dev/null +++ b/DiningRoom/DiningRoomView/FormReportComponentsByDate.Designer.cs @@ -0,0 +1,155 @@ +namespace DiningRoomView +{ + partial class FormReportComponentsByDate + { + /// + /// 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() + { + panel = new Panel(); + buttonToPdf = new Button(); + buttonMake = new Button(); + dateTimePickerTo = new DateTimePicker(); + labelTo = new Label(); + dateTimePickerFrom = new DateTimePicker(); + labelFrom = new Label(); + dataGridView = new DataGridView(); + panel.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // panel + // + panel.Controls.Add(buttonToPdf); + panel.Controls.Add(buttonMake); + panel.Controls.Add(dateTimePickerTo); + panel.Controls.Add(labelTo); + panel.Controls.Add(dateTimePickerFrom); + panel.Controls.Add(labelFrom); + panel.Dock = DockStyle.Top; + panel.Location = new Point(0, 0); + panel.Margin = new Padding(4, 3, 4, 3); + panel.Name = "panel"; + panel.Size = new Size(1031, 40); + panel.TabIndex = 0; + // + // buttonToPdf + // + buttonToPdf.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonToPdf.Location = new Point(878, 8); + buttonToPdf.Margin = new Padding(4, 3, 4, 3); + buttonToPdf.Name = "buttonToPdf"; + buttonToPdf.Size = new Size(139, 27); + buttonToPdf.TabIndex = 5; + buttonToPdf.Text = "В Pdf"; + buttonToPdf.UseVisualStyleBackColor = true; + buttonToPdf.Click += buttonGenerateAndSendPdf_Click; + // + // buttonMake + // + buttonMake.Location = new Point(476, 8); + buttonMake.Margin = new Padding(4, 3, 4, 3); + buttonMake.Name = "buttonMake"; + buttonMake.Size = new Size(139, 27); + buttonMake.TabIndex = 4; + buttonMake.Text = "Сформировать"; + buttonMake.UseVisualStyleBackColor = true; + buttonMake.Click += ButtonMake_Click; + // + // dateTimePickerTo + // + dateTimePickerTo.Location = new Point(237, 7); + dateTimePickerTo.Margin = new Padding(4, 3, 4, 3); + dateTimePickerTo.Name = "dateTimePickerTo"; + dateTimePickerTo.Size = new Size(163, 23); + dateTimePickerTo.TabIndex = 3; + // + // labelTo + // + labelTo.AutoSize = true; + labelTo.Location = new Point(208, 10); + labelTo.Margin = new Padding(4, 0, 4, 0); + labelTo.Name = "labelTo"; + labelTo.Size = new Size(21, 15); + labelTo.TabIndex = 2; + labelTo.Text = "по"; + // + // dateTimePickerFrom + // + dateTimePickerFrom.Location = new Point(37, 7); + dateTimePickerFrom.Margin = new Padding(4, 3, 4, 3); + dateTimePickerFrom.Name = "dateTimePickerFrom"; + dateTimePickerFrom.Size = new Size(163, 23); + dateTimePickerFrom.TabIndex = 1; + // + // labelFrom + // + labelFrom.AutoSize = true; + labelFrom.Location = new Point(14, 10); + labelFrom.Margin = new Padding(4, 0, 4, 0); + labelFrom.Name = "labelFrom"; + labelFrom.Size = new Size(15, 15); + labelFrom.TabIndex = 0; + labelFrom.Text = "С"; + // + // dataGridView + // + dataGridView.BackgroundColor = SystemColors.ButtonHighlight; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(12, 46); + dataGridView.Name = "dataGridView"; + dataGridView.RowTemplate.Height = 25; + dataGridView.Size = new Size(1005, 589); + dataGridView.TabIndex = 1; + // + // FormReportComponentsByDate + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1031, 647); + Controls.Add(dataGridView); + Controls.Add(panel); + Margin = new Padding(4, 3, 4, 3); + Name = "FormReportComponentsByDate"; + StartPosition = FormStartPosition.CenterScreen; + Text = "Заказы"; + panel.ResumeLayout(false); + panel.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private System.Windows.Forms.Panel panel; + private System.Windows.Forms.Button buttonToPdf; + private System.Windows.Forms.Button buttonMake; + private System.Windows.Forms.DateTimePicker dateTimePickerTo; + private System.Windows.Forms.Label labelTo; + private System.Windows.Forms.DateTimePicker dateTimePickerFrom; + private System.Windows.Forms.Label labelFrom; + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/DiningRoom/DiningRoomView/FormReportComponentsByDate.cs b/DiningRoom/DiningRoomView/FormReportComponentsByDate.cs new file mode 100644 index 0000000..8910286 --- /dev/null +++ b/DiningRoom/DiningRoomView/FormReportComponentsByDate.cs @@ -0,0 +1,247 @@ +using DiningRoomBusinessLogic.OfficePackage.HelperModels; +using DiningRoomContracts.BindingModels; +using DiningRoomContracts.BusinessLogicContracts; +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.Net.Mail; +using System.Net; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using System.IO; +using System.Net; +using System.Net.Mail; +using System.Windows.Forms; +using iTextSharp.text; +using iTextSharp.text.pdf; + +namespace DiningRoomView +{ + public partial class FormReportComponentsByDate : Form + { + + private readonly ILogger _logger; + + private readonly IReportLogic _logic; + + public FormReportComponentsByDate(ILogger logger, IReportLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + 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.GetReportComponentsByCardDate(new ReportBindingModel + { + DateFrom = DateTime.SpecifyKind(dateTimePickerFrom.Value, DateTimeKind.Utc), + DateTo = DateTime.SpecifyKind(dateTimePickerTo.Value, DateTimeKind.Utc) + }); + + // Группировка данных по ComponentName и преобразование в нужный формат + var displayData = new List(); + var groupedData = dataSource.GroupBy(c => c.ComponentName); + + foreach (var group in groupedData) + { + // Добавляем строку с именем компонента и его стоимостью + displayData.Add(new GroupedComponentViewModel + { + ComponentName = group.Key, + ComponentCost = group.First().ComponentCost + }); + + // Добавляем строки с названием карты и блюда + foreach (var item in group) + { + displayData.Add(new GroupedComponentViewModel + { + CardName = item.CardName, + ProductName = item.ProductName + }); + } + } + + // Очистка предыдущих данных + dataGridView.DataSource = null; + + // Установка нового источника данных + dataGridView.DataSource = displayData; + + // Форматирование столбцов + dataGridView.Columns["ComponentName"].HeaderText = "Название компонента"; + dataGridView.Columns["ComponentCost"].HeaderText = "Стоимость компонента"; + dataGridView.Columns["CardName"].HeaderText = "Название карты"; + dataGridView.Columns["ProductName"].HeaderText = "Название блюда"; + + // Настройка видимости столбцов + dataGridView.Columns["ComponentName"].Visible = true; + dataGridView.Columns["ComponentCost"].Visible = true; + dataGridView.Columns["CardName"].Visible = true; + dataGridView.Columns["ProductName"].Visible = true; + + // Логирование успешной загрузки данных + _logger.LogInformation("Загрузка списка заказов на период {From}-{To}", dateTimePickerFrom.Value.ToShortDateString(), dateTimePickerTo.Value.ToShortDateString()); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки списка заказов на период"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + + + + private void ButtonToPdf_Click(object sender, EventArgs e) + { + System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); + if (dateTimePickerFrom.Value.Date >= dateTimePickerTo.Value.Date) + { + MessageBox.Show("Дата начала должна быть меньше даты окончания", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + using var dialog = new SaveFileDialog { Filter = "pdf|*.pdf" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + try + { + _logic.SaveComponentsToPdfFile(new ReportBindingModel + { + FileName = dialog.FileName, + DateFrom = DateTime.SpecifyKind(dateTimePickerFrom.Value, DateTimeKind.Utc), + DateTo = DateTime.SpecifyKind(dateTimePickerTo.Value, DateTimeKind.Utc) + }); + _logger.LogInformation("Сохранение списка заказов на период {From}-{To}", dateTimePickerFrom.Value.ToShortDateString(), dateTimePickerTo.Value.ToShortDateString()); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения списка заказов на период"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + private void buttonGenerateAndSendPdf_Click(object sender, EventArgs e) + { + try + { + // Получение данных для PDF + var info = new PdfInfo + { + Title = "Отчет", + DateFrom = dateTimePickerFrom.Value, + DateTo = dateTimePickerTo.Value, + Components = _logic.GetReportComponentsByCardDate(new ReportBindingModel + { + DateFrom = DateTime.SpecifyKind(dateTimePickerFrom.Value, DateTimeKind.Utc), + DateTo = DateTime.SpecifyKind(dateTimePickerTo.Value, DateTimeKind.Utc) + }) + }; + + // Генерация PDF в памяти + using (MemoryStream stream = new MemoryStream()) + { + CreateDoc(info, stream); + + // Email пользователя + string userEmail = "tikhonenkov2015@gmail.com"; // Замените на email пользователя + + // Отправка email с PDF вложением + SendEmailWithPdf(stream, userEmail); + } + + MessageBox.Show("PDF файл успешно отправлен на почту!", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + catch (Exception ex) + { + MessageBox.Show("Ошибка: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + public void CreateDoc(PdfInfo info, MemoryStream stream) + { + Document document = new Document(); + PdfWriter writer = PdfWriter.GetInstance(document, stream); + document.Open(); + + document.Add(new Paragraph(info.Title, FontFactory.GetFont("Arial", "16", Font.Bold))); + document.Add(new Paragraph($"с {info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}", FontFactory.GetFont("Arial", "12"))); + + PdfPTable table = new PdfPTable(4); + table.WidthPercentage = 100; + table.SetWidths(new float[] { 3, 2, 6, 6 }); + + var groupedData = info.Components.GroupBy(c => c.ComponentName); + + foreach (var group in groupedData) + { + PdfPCell cell = new PdfPCell(new Phrase("Продукт", FontFactory.GetFont("Arial", "12", Font.Bold))); + cell.Colspan = 4; + table.AddCell(cell); + + table.AddCell(new Phrase(group.Key, FontFactory.GetFont("Arial", "12", Font.Bold))); + table.AddCell(new Phrase(group.First().ComponentCost.ToString("C"), FontFactory.GetFont("Arial", "12", Font.Bold))); + table.AddCell(""); + table.AddCell(""); + + table.AddCell(new Phrase("", FontFactory.GetFont("Arial", "12", Font.Bold))); + table.AddCell(""); + table.AddCell(new Phrase("Карта", FontFactory.GetFont("Arial", "12", Font.Bold))); + table.AddCell(new Phrase("Блюдо", FontFactory.GetFont("Arial", "12", Font.Bold))); + + foreach (var item in group) + { + table.AddCell(""); + table.AddCell(""); + table.AddCell(new Phrase(item.CardName, FontFactory.GetFont("Arial", 12))); + table.AddCell(new Phrase(item.ProductName, FontFactory.GetFont("Arial", 12))); + } + } + + document.Add(table); + document.Close(); + writer.Close(); + } + private void SendEmailWithPdf(MemoryStream pdfStream, string userEmail) + { + pdfStream.Position = 0; // Сбросить позицию потока на начало + + MailMessage mail = new MailMessage(); + SmtpClient smtpClient = new SmtpClient("smtp.example.com"); // Замените на SMTP-сервер вашего почтового провайдера + + mail.From = new MailAddress("mailworker2024@gmail.com"); // Ваш email + mail.To.Add(userEmail); + mail.Subject = "Отчет"; + mail.Body = "Пожалуйста, найдите прикрепленный PDF отчет."; + + // Создание вложения из потока + Attachment attachment = new Attachment(pdfStream, "Report.pdf", "application/pdf"); + mail.Attachments.Add(attachment); + + smtpClient.Port = 587; // Обычно 587 или 25 для SMTP + smtpClient.Credentials = new NetworkCredential("mailworker2024@gmail.com", "bixb rbag kumt lefa"); // Ваш email и пароль + smtpClient.EnableSsl = true; + + smtpClient.Send(mail); + } + + + + + } +} diff --git a/DiningRoom/DiningRoomView/FormOrdersOld.resx b/DiningRoom/DiningRoomView/FormReportComponentsByDate.resx similarity index 100% rename from DiningRoom/DiningRoomView/FormOrdersOld.resx rename to DiningRoom/DiningRoomView/FormReportComponentsByDate.resx diff --git a/DiningRoom/DiningRoomView/Program.cs b/DiningRoom/DiningRoomView/Program.cs index f2a0509..85a67b9 100644 --- a/DiningRoom/DiningRoomView/Program.cs +++ b/DiningRoom/DiningRoomView/Program.cs @@ -70,6 +70,7 @@ namespace DiningRoomView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); } diff --git a/DiningRoom/DiningRoomView/ReportComponents.rdlc b/DiningRoom/DiningRoomView/ReportComponents.rdlc new file mode 100644 index 0000000..359f516 --- /dev/null +++ b/DiningRoom/DiningRoomView/ReportComponents.rdlc @@ -0,0 +1,577 @@ + + + 0 + + + + System.Data.DataSet + /* Local Connection */ + + 10791c83-cee8-4a38-bbd0-245fc17cefb3 + + + + + + DiningRoomContractsViewModels + /* Local Query */ + + + + Id + System.Int32 + + + DateCreate + System.DateTime + + + WoodName + System.String + + + Sum + System.Double + + + Status + System.String + + + + DiningRoomContracts.ViewModels + ReportOrdersViewModel + DiningRoomContracts.ViewModels.ReportOrdersViewModel, DiningRoomContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + + + + + + + + + true + true + + + + + Заказы + + + + Textbox2 + 0.6cm + 16.51cm + + + Middle + 2pt + 2pt + 2pt + 2pt + + + + + + + 2.5cm + + + 2.5cm + + + 2.5cm + + + 2.5cm + + + 2.5cm + + + + + 0.6cm + + + + + true + true + + + + + ComponentId + + + 2pt + 2pt + 2pt + 2pt + + + true + + + + + + true + true + + + + + Date Create + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Wood Name + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Sum + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Status + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + 0.6cm + + + + + true + true + + + + + =Fields!ComponentId.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!DateCreate.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!WoodName.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!Sum.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!Status.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + + + + + + + + + + + + + + After + + + + + + + DataSetOrders + 1.95474cm + 0.76412cm + 1.2cm + 12.5cm + 1 + + + + + + true + true + + + + + Итого: + + + 2pt + 2pt + 2pt + 2pt + + + + true + true + + + + + =Sum(Fields!Sum.Value, "DataSetOrders") + + + + + + 2pt + 2pt + 2pt + 2pt + + + + true + true + + + + + =Parameters!ReportParameterPeriod.Value + + + + ReportParameterPeriod + 0.94932cm + 0.6cm + 16.51cm + 4 + + + Middle + 2pt + 2pt + 2pt + 2pt + + + + 2in +