diff --git a/ProjectOpticsStore/ProjectOpticsStore/Entities/Order.cs b/ProjectOpticsStore/ProjectOpticsStore/Entities/Order.cs index 5d3a545..fcdfc19 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Entities/Order.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/Entities/Order.cs @@ -1,4 +1,5 @@ -using ProjectOpticsStore.Entities; +using Newtonsoft.Json; +using ProjectOpticsStore.Entities; using ProjectOpticsStore.Entities.Enums; public class Order @@ -10,7 +11,7 @@ public class Order public OrderStatusEnum Status { get; private set; } = OrderStatusEnum.Pending; // Коллекция, описывающая связь "Order_Product" - public IEnumerable OrderProducts { get; private set; } = new List(); + [JsonIgnore] public IEnumerable OrderProducts { get; private set; } = new List(); public static Order CreateOperation(int id, int customerId, IEnumerable orderProducts, OrderStatusEnum status = OrderStatusEnum.Pending) { @@ -23,4 +24,16 @@ public class Order OrderProducts = orderProducts }; } + + public static Order CreateOperation(TempOrderProduct tempOrderProduct, IEnumerable orderProducts) + { + return new Order + { + Id = tempOrderProduct.Id, + CustomerId = tempOrderProduct.CustomerId, + DateCreated = tempOrderProduct.DateCreated, + Status = tempOrderProduct.Status, + OrderProducts = orderProducts + }; + } } diff --git a/ProjectOpticsStore/ProjectOpticsStore/Entities/Order_Product.cs b/ProjectOpticsStore/ProjectOpticsStore/Entities/Order_Product.cs index 86393cc..3569d33 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Entities/Order_Product.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/Entities/Order_Product.cs @@ -2,17 +2,15 @@ public class Order_Product { - public int Id { get; private set; } public int OrderId { get; private set; } public int ProductId { get; private set; } public int Quantity { get; private set; } // Создание элемента связи - public static Order_Product CreateElement(int id, int orderId, int productId, int quantity) + public static Order_Product CreateElement(int orderId, int productId, int quantity) { return new Order_Product { - Id = id, OrderId = orderId, ProductId = productId, Quantity = quantity diff --git a/ProjectOpticsStore/ProjectOpticsStore/Entities/TempOrderProduct.cs b/ProjectOpticsStore/ProjectOpticsStore/Entities/TempOrderProduct.cs new file mode 100644 index 0000000..e1fa218 --- /dev/null +++ b/ProjectOpticsStore/ProjectOpticsStore/Entities/TempOrderProduct.cs @@ -0,0 +1,16 @@ +using ProjectOpticsStore.Entities.Enums; + +namespace ProjectOpticsStore.Entities; + +public class TempOrderProduct +{ + public int Id { get; private set; } + public int CustomerId { get; private set; } + public DateTime DateCreated { get; private set; } + + public OrderStatusEnum Status { get; private set; } + + public int OrderId { get; private set; } + public int ProductId { get; private set; } + public int Quantity { get; private set; } +} diff --git a/ProjectOpticsStore/ProjectOpticsStore/FormOpticsStore.Designer.cs b/ProjectOpticsStore/ProjectOpticsStore/FormOpticsStore.Designer.cs index 06fbc1c..8160afe 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/FormOpticsStore.Designer.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/FormOpticsStore.Designer.cs @@ -37,6 +37,9 @@ поставкаToolStripMenuItem = new ToolStripMenuItem(); заказатьToolStripMenuItem = new ToolStripMenuItem(); отчетыToolStripMenuItem = new ToolStripMenuItem(); + DirectoryReportToolStripMenuItem = new ToolStripMenuItem(); + productReportToolStripMenuItem = new ToolStripMenuItem(); + ProductDistributionToolStripMenuItem = new ToolStripMenuItem(); menuStrip1.SuspendLayout(); SuspendLayout(); // @@ -46,7 +49,8 @@ menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, операцииToolStripMenuItem, отчетыToolStripMenuItem }); menuStrip1.Location = new Point(0, 0); menuStrip1.Name = "menuStrip1"; - menuStrip1.Size = new Size(800, 28); + menuStrip1.Padding = new Padding(5, 2, 0, 2); + menuStrip1.Size = new Size(700, 24); menuStrip1.TabIndex = 0; menuStrip1.Text = "menuStrip1"; // @@ -54,27 +58,27 @@ // справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { товарыToolStripMenuItem, магазиныToolStripMenuItem, заказчикиToolStripMenuItem }); справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; - справочникиToolStripMenuItem.Size = new Size(117, 24); + справочникиToolStripMenuItem.Size = new Size(94, 20); справочникиToolStripMenuItem.Text = "Справочники"; // // товарыToolStripMenuItem // товарыToolStripMenuItem.Name = "товарыToolStripMenuItem"; - товарыToolStripMenuItem.Size = new Size(224, 26); + товарыToolStripMenuItem.Size = new Size(131, 22); товарыToolStripMenuItem.Text = "Товары"; товарыToolStripMenuItem.Click += ProductsToolStripMenuItem_Click; // // магазиныToolStripMenuItem // магазиныToolStripMenuItem.Name = "магазиныToolStripMenuItem"; - магазиныToolStripMenuItem.Size = new Size(224, 26); + магазиныToolStripMenuItem.Size = new Size(131, 22); магазиныToolStripMenuItem.Text = "Магазины"; магазиныToolStripMenuItem.Click += StoresToolStripMenuItem_Click; // // заказчикиToolStripMenuItem // заказчикиToolStripMenuItem.Name = "заказчикиToolStripMenuItem"; - заказчикиToolStripMenuItem.Size = new Size(224, 26); + заказчикиToolStripMenuItem.Size = new Size(131, 22); заказчикиToolStripMenuItem.Text = "Заказчики"; заказчикиToolStripMenuItem.Click += CustomersToolStripMenuItem_Click; // @@ -82,38 +86,64 @@ // операцииToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { поставкаToolStripMenuItem, заказатьToolStripMenuItem }); операцииToolStripMenuItem.Name = "операцииToolStripMenuItem"; - операцииToolStripMenuItem.Size = new Size(95, 24); + операцииToolStripMenuItem.Size = new Size(75, 20); операцииToolStripMenuItem.Text = "Операции"; // // поставкаToolStripMenuItem // поставкаToolStripMenuItem.Name = "поставкаToolStripMenuItem"; - поставкаToolStripMenuItem.Size = new Size(164, 26); + поставкаToolStripMenuItem.Size = new Size(131, 22); поставкаToolStripMenuItem.Text = "Поставить"; поставкаToolStripMenuItem.Click += SupplyToolStripMenuItem_Click; // // заказатьToolStripMenuItem // заказатьToolStripMenuItem.Name = "заказатьToolStripMenuItem"; - заказатьToolStripMenuItem.Size = new Size(164, 26); + заказатьToolStripMenuItem.Size = new Size(131, 22); заказатьToolStripMenuItem.Text = "Заказать"; заказатьToolStripMenuItem.Click += OrderToolStripMenuItem_Click; // // отчетыToolStripMenuItem // + отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { DirectoryReportToolStripMenuItem, productReportToolStripMenuItem, ProductDistributionToolStripMenuItem }); отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; - отчетыToolStripMenuItem.Size = new Size(73, 24); + отчетыToolStripMenuItem.Size = new Size(60, 20); отчетыToolStripMenuItem.Text = "Отчеты"; // + // DirectoryReportToolStripMenuItem + // + DirectoryReportToolStripMenuItem.Name = "DirectoryReportToolStripMenuItem"; + DirectoryReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.W; + DirectoryReportToolStripMenuItem.Size = new Size(280, 22); + DirectoryReportToolStripMenuItem.Text = "Документ со справочниками"; + DirectoryReportToolStripMenuItem.Click += DirectoryReportToolStripMenuItem_Click; + // + // productReportToolStripMenuItem + // + productReportToolStripMenuItem.Name = "productReportToolStripMenuItem"; + productReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.E; + productReportToolStripMenuItem.Size = new Size(280, 22); + productReportToolStripMenuItem.Text = "Движение товаров"; + productReportToolStripMenuItem.Click += productReportToolStripMenuItem_Click; + // + // ProductDistributionToolStripMenuItem + // + ProductDistributionToolStripMenuItem.Name = "ProductDistributionToolStripMenuItem"; + ProductDistributionToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.P; + ProductDistributionToolStripMenuItem.Size = new Size(280, 22); + ProductDistributionToolStripMenuItem.Text = "Распределение товаров"; + ProductDistributionToolStripMenuItem.Click += ProductDistributionToolStripMenuItem_Click; + // // FormOpticsStore // - AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; BackgroundImage = Properties.Resources.catwithglasses; BackgroundImageLayout = ImageLayout.Stretch; - ClientSize = new Size(800, 450); + ClientSize = new Size(700, 338); Controls.Add(menuStrip1); MainMenuStrip = menuStrip1; + Margin = new Padding(3, 2, 3, 2); Name = "FormOpticsStore"; StartPosition = FormStartPosition.CenterScreen; Text = "Салон Оптики"; @@ -134,5 +164,8 @@ private ToolStripMenuItem заказчикиToolStripMenuItem; private ToolStripMenuItem поставкаToolStripMenuItem; private ToolStripMenuItem заказатьToolStripMenuItem; + private ToolStripMenuItem DirectoryReportToolStripMenuItem; + private ToolStripMenuItem productReportToolStripMenuItem; + private ToolStripMenuItem ProductDistributionToolStripMenuItem; } } diff --git a/ProjectOpticsStore/ProjectOpticsStore/FormOpticsStore.cs b/ProjectOpticsStore/ProjectOpticsStore/FormOpticsStore.cs index 79e73ef..5d082ab 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/FormOpticsStore.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/FormOpticsStore.cs @@ -22,7 +22,7 @@ public partial class FormOpticsStore : Form } catch (Exception ex) { - MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -34,7 +34,7 @@ public partial class FormOpticsStore : Form } catch (Exception ex) { - MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -46,7 +46,7 @@ public partial class FormOpticsStore : Form } catch (Exception ex) { - MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -59,7 +59,7 @@ public partial class FormOpticsStore : Form } catch (Exception ex) { - MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -71,7 +71,43 @@ public partial class FormOpticsStore : Form } catch (Exception ex) { - MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void DirectoryReportToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + _container.Resolve().ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void productReportToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + _container.Resolve().ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ProductDistributionToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + _container.Resolve().ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -79,4 +115,5 @@ public partial class FormOpticsStore : Form { Close(); } + } \ No newline at end of file diff --git a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormDirectoryReport.Designer.cs b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormDirectoryReport.Designer.cs new file mode 100644 index 0000000..1c6e109 --- /dev/null +++ b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormDirectoryReport.Designer.cs @@ -0,0 +1,100 @@ +namespace ProjectOpticsStore.Forms +{ + partial class FormDirectoryReport + { + /// + /// 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() + { + checkBoxCustomers = new CheckBox(); + checkBoxStores = new CheckBox(); + checkBoxProducts = new CheckBox(); + buttonCreate = new Button(); + SuspendLayout(); + // + // checkBoxCustomers + // + checkBoxCustomers.AutoSize = true; + checkBoxCustomers.Location = new Point(42, 28); + checkBoxCustomers.Name = "checkBoxCustomers"; + checkBoxCustomers.Size = new Size(83, 19); + checkBoxCustomers.TabIndex = 0; + checkBoxCustomers.Text = "Заказчики"; + checkBoxCustomers.UseVisualStyleBackColor = true; + // + // checkBoxStores + // + checkBoxStores.AutoSize = true; + checkBoxStores.Location = new Point(42, 78); + checkBoxStores.Name = "checkBoxStores"; + checkBoxStores.Size = new Size(82, 19); + checkBoxStores.TabIndex = 1; + checkBoxStores.Text = "Магазины"; + checkBoxStores.UseVisualStyleBackColor = true; + // + // checkBoxProducts + // + checkBoxProducts.AutoSize = true; + checkBoxProducts.Location = new Point(42, 127); + checkBoxProducts.Name = "checkBoxProducts"; + checkBoxProducts.Size = new Size(67, 19); + checkBoxProducts.TabIndex = 2; + checkBoxProducts.Text = "Товары"; + checkBoxProducts.UseVisualStyleBackColor = true; + // + // buttonCreate + // + buttonCreate.Location = new Point(233, 49); + buttonCreate.Name = "buttonCreate"; + buttonCreate.Size = new Size(123, 74); + buttonCreate.TabIndex = 3; + buttonCreate.Text = "Определенным образом сформировать"; + buttonCreate.UseVisualStyleBackColor = true; + buttonCreate.Click += buttonCreate_Click; + // + // FormDirectoryReport + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(398, 181); + Controls.Add(buttonCreate); + Controls.Add(checkBoxProducts); + Controls.Add(checkBoxStores); + Controls.Add(checkBoxCustomers); + Name = "FormDirectoryReport"; + StartPosition = FormStartPosition.CenterParent; + Text = "FormDirectoryReport"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private CheckBox checkBoxCustomers; + private CheckBox checkBoxStores; + private CheckBox checkBoxProducts; + private Button buttonCreate; + } +} \ No newline at end of file diff --git a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormDirectoryReport.cs b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormDirectoryReport.cs new file mode 100644 index 0000000..5693e84 --- /dev/null +++ b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormDirectoryReport.cs @@ -0,0 +1,48 @@ +using ProjectOpticsStore.Reports; +using Unity; + +namespace ProjectOpticsStore.Forms; + +public partial class FormDirectoryReport : Form +{ + private readonly IUnityContainer _container; + public FormDirectoryReport(IUnityContainer container) + { + InitializeComponent(); + _container = container ?? throw new ArgumentNullException(nameof(container)); + } + + private void buttonCreate_Click(object sender, EventArgs e) + { + try + { + if (!checkBoxCustomers.Checked && !checkBoxStores.Checked && !checkBoxProducts.Checked) + { + throw new Exception("Не выбран ни один справочник для выгрузки"); + } + var sfd = new SaveFileDialog() + { + Filter = "Docx Files | *.docx" + }; + if (sfd.ShowDialog() != DialogResult.OK) + { + throw new Exception("Не выбран файла для отчета"); + } + if (_container.Resolve().CreateDoc(sfd.FileName, checkBoxCustomers.Checked, + checkBoxStores.Checked, checkBoxProducts.Checked)) + { + MessageBox.Show("Документ сформирован", "Формирование документа", + MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Возникли ошибки при формировании документа. Подробности в логах", + "Формирование документа", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при создании отчета", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } +} diff --git a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormDirectoryReport.resx b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormDirectoryReport.resx new file mode 100644 index 0000000..8b2ff64 --- /dev/null +++ b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormDirectoryReport.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/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrder.cs b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrder.cs index c125daa..7dde527 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrder.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrder.cs @@ -1,6 +1,7 @@ using ProjectOpticsStore.Entities.Enums; using ProjectOpticsStore.Entities; using ProjectOpticsStore.Repositories; +using DocumentFormat.OpenXml.Drawing.Charts; namespace ProjectOpticsStore.Forms; @@ -116,14 +117,11 @@ public partial class FormOrder : Form if (row.Cells["ColumnProduct"].Value == null || row.Cells["ColumnQuantity"].Value == null) continue; - // Получаем значения из ячеек - var productId = Convert.ToInt32(row.Cells["ColumnProduct"].Value); - var quantity = Convert.ToInt32(row.Cells["ColumnQuantity"].Value); - - // Используем метод CreateElement для создания объектов Order_Product - list.Add(Order_Product.CreateElement(0, 0, productId, quantity)); + list.Add(Order_Product.CreateElement(0, Convert.ToInt32(row.Cells["ColumnProduct"].Value), + Convert.ToInt32(row.Cells["ColumnQuantity"].Value))); } + return list.GroupBy(x => x.ProductId, x => x.Quantity, (id, quantity) => + Order_Product.CreateElement(0, id, quantity.Sum())).ToList(); - return list; } } \ No newline at end of file diff --git a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrders.Designer.cs b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrders.Designer.cs index ff1d271..c8a53e7 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrders.Designer.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrders.Designer.cs @@ -29,7 +29,6 @@ private void InitializeComponent() { panelButtons = new Panel(); - buttonDel = new Button(); buttonAdd = new Button(); dataGridViewOrders = new DataGridView(); panelButtons.SuspendLayout(); @@ -38,7 +37,6 @@ // // panelButtons // - panelButtons.Controls.Add(buttonDel); panelButtons.Controls.Add(buttonAdd); panelButtons.Dock = DockStyle.Right; panelButtons.Location = new Point(569, 0); @@ -47,18 +45,6 @@ panelButtons.Size = new Size(131, 338); panelButtons.TabIndex = 2; // - // buttonDel - // - buttonDel.BackgroundImage = Properties.Resources.Button_Delete; - buttonDel.BackgroundImageLayout = ImageLayout.Stretch; - buttonDel.Location = new Point(18, 242); - buttonDel.Margin = new Padding(3, 2, 3, 2); - buttonDel.Name = "buttonDel"; - buttonDel.Size = new Size(99, 75); - buttonDel.TabIndex = 2; - buttonDel.UseVisualStyleBackColor = true; - buttonDel.Click += ButtonDel_Click; - // // buttonAdd // buttonAdd.BackgroundImage = Properties.Resources.Button_Add; @@ -107,7 +93,6 @@ #endregion private Panel panelButtons; - private Button buttonDel; private Button buttonAdd; private DataGridView dataGridViewOrders; } diff --git a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrders.cs b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrders.cs index ca28af2..b994147 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrders.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrders.cs @@ -45,39 +45,16 @@ public partial class FormOrders : Form } } - // Кнопка для удаления выбранного заказа - private void ButtonDel_Click(object sender, EventArgs e) - { - if (!TryGetIdentifierFromSelectedRow(out var orderId)) - { - return; - } - - if (MessageBox.Show("Удалить заказ?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes) - { - return; - } - - try - { - _orderRepository.DeleteOrder(orderId); - LoadList(); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } // Метод для загрузки списка заказов в DataGridView private void LoadList() { dataGridViewOrders.DataSource = _orderRepository.ReadOrders(); - if (dataGridViewOrders.Columns.Contains("OrderProducts")) - { - dataGridViewOrders.Columns["OrderProducts"].Visible = false; - } + //if (dataGridViewOrders.Columns.Contains("OrderProducts")) + //{ + // dataGridViewOrders.Columns["OrderProducts"].Visible = false; + //} } // Метод для получения идентификатора заказа из выбранной строки в DataGridView diff --git a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormProductReport.Designer.cs b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormProductReport.Designer.cs new file mode 100644 index 0000000..10daa65 --- /dev/null +++ b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormProductReport.Designer.cs @@ -0,0 +1,164 @@ +namespace ProjectOpticsStore.Forms +{ + partial class FormProductReport + { + /// + /// 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() + { + dateTimePickerStartDate = new DateTimePicker(); + dateTimePickerEndDate = new DateTimePicker(); + label1 = new Label(); + label2 = new Label(); + buttonMakeReport = new Button(); + comboBoxProducts = new ComboBox(); + label3 = new Label(); + label4 = new Label(); + textBoxFilePath = new TextBox(); + buttonSelectFilePath = new Button(); + SuspendLayout(); + // + // dateTimePickerStartDate + // + dateTimePickerStartDate.Location = new Point(141, 163); + dateTimePickerStartDate.Name = "dateTimePickerStartDate"; + dateTimePickerStartDate.Size = new Size(200, 23); + dateTimePickerStartDate.TabIndex = 0; + // + // dateTimePickerEndDate + // + dateTimePickerEndDate.Location = new Point(141, 221); + dateTimePickerEndDate.Name = "dateTimePickerEndDate"; + dateTimePickerEndDate.Size = new Size(200, 23); + dateTimePickerEndDate.TabIndex = 1; + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(35, 169); + label1.Name = "label1"; + label1.Size = new Size(77, 15); + label1.TabIndex = 2; + label1.Text = "Дата начала:"; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(35, 227); + label2.Name = "label2"; + label2.Size = new Size(71, 15); + label2.TabIndex = 3; + label2.Text = "Дата конца:"; + // + // buttonMakeReport + // + buttonMakeReport.Location = new Point(119, 287); + buttonMakeReport.Name = "buttonMakeReport"; + buttonMakeReport.Size = new Size(130, 41); + buttonMakeReport.TabIndex = 4; + buttonMakeReport.Text = "Сформировать"; + buttonMakeReport.UseVisualStyleBackColor = true; + buttonMakeReport.Click += ButtonMakeReport_Click; + // + // comboBoxProducts + // + comboBoxProducts.FormattingEnabled = true; + comboBoxProducts.Location = new Point(141, 106); + comboBoxProducts.Name = "comboBoxProducts"; + comboBoxProducts.Size = new Size(200, 23); + comboBoxProducts.TabIndex = 5; + // + // label3 + // + label3.AutoSize = true; + label3.Location = new Point(35, 109); + label3.Name = "label3"; + label3.Size = new Size(42, 15); + label3.TabIndex = 6; + label3.Text = "Товар:"; + // + // label4 + // + label4.AutoSize = true; + label4.Location = new Point(35, 46); + label4.Name = "label4"; + label4.Size = new Size(90, 15); + label4.TabIndex = 7; + label4.Text = "Путь до файла:"; + // + // textBoxFilePath + // + textBoxFilePath.Location = new Point(141, 43); + textBoxFilePath.Name = "textBoxFilePath"; + textBoxFilePath.ReadOnly = true; + textBoxFilePath.Size = new Size(169, 23); + textBoxFilePath.TabIndex = 8; + // + // buttonSelectFilePath + // + buttonSelectFilePath.Location = new Point(311, 43); + buttonSelectFilePath.Name = "buttonSelectFilePath"; + buttonSelectFilePath.Size = new Size(30, 23); + buttonSelectFilePath.TabIndex = 9; + buttonSelectFilePath.Text = "<3"; + buttonSelectFilePath.UseVisualStyleBackColor = true; + buttonSelectFilePath.Click += ButtonSelectFilePath_Click; + // + // FormProductReport + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(380, 363); + Controls.Add(buttonSelectFilePath); + Controls.Add(textBoxFilePath); + Controls.Add(label4); + Controls.Add(label3); + Controls.Add(comboBoxProducts); + Controls.Add(buttonMakeReport); + Controls.Add(label2); + Controls.Add(label1); + Controls.Add(dateTimePickerEndDate); + Controls.Add(dateTimePickerStartDate); + Name = "FormProductReport"; + StartPosition = FormStartPosition.CenterParent; + Text = "Отчет по товару"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private DateTimePicker dateTimePickerStartDate; + private DateTimePicker dateTimePickerEndDate; + private Label label1; + private Label label2; + private Button buttonMakeReport; + private ComboBox comboBoxProducts; + private Label label3; + private Label label4; + private TextBox textBoxFilePath; + private Button buttonSelectFilePath; + } +} \ No newline at end of file diff --git a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormProductReport.cs b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormProductReport.cs new file mode 100644 index 0000000..92d023e --- /dev/null +++ b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormProductReport.cs @@ -0,0 +1,76 @@ +using ProjectOpticsStore.Reports; +using ProjectOpticsStore.Repositories; +using ProjectOpticsStore.Repositories.Implementations; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using Unity; + +namespace ProjectOpticsStore.Forms +{ + public partial class FormProductReport : Form + { + IUnityContainer _container; + public FormProductReport(IUnityContainer container, IProductRepository productRepository) + { + InitializeComponent(); + _container = container ?? throw new ArgumentNullException(nameof(container)); + comboBoxProducts.DataSource = productRepository.ReadProducts(); + comboBoxProducts.DisplayMember = "Type"; + comboBoxProducts.ValueMember = "Id"; + } + + private void ButtonSelectFilePath_Click(object sender, EventArgs e) + { + var sfd = new SaveFileDialog() + { + Filter = "Excel Files | *.xlsx" + }; + if (sfd.ShowDialog() != DialogResult.OK) + { + return; + } + textBoxFilePath.Text = sfd.FileName; + } + private void ButtonMakeReport_Click(object sender, EventArgs e) + { + + + try + { + if (string.IsNullOrWhiteSpace(textBoxFilePath.Text)) + { + throw new Exception("Отсутствует имя файла для отчета"); + } + if (comboBoxProducts.SelectedIndex < 0) + { + throw new Exception("Не выбран корм"); + } + if (dateTimePickerEndDate.Value <= dateTimePickerStartDate.Value) + { + throw new Exception("Дата начала должна быть раньше даты окончания"); + } + if (_container.Resolve().CreateTable(textBoxFilePath.Text, (int)comboBoxProducts.SelectedValue!, + dateTimePickerStartDate.Value, dateTimePickerEndDate.Value)) + { + MessageBox.Show("Документ сформирован", "Формирование документа", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах", "Формирование документа", + MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при создании очета", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } +} diff --git a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormProductReport.resx b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormProductReport.resx new file mode 100644 index 0000000..8b2ff64 --- /dev/null +++ b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormProductReport.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/ProjectOpticsStore/ProjectOpticsStore/Forms/FormSupplies.Designer.cs b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormSupplies.Designer.cs index bc80e61..3d5dbf2 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormSupplies.Designer.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormSupplies.Designer.cs @@ -31,12 +31,14 @@ panelButtons = new Panel(); buttonAdd = new Button(); dataGridViewSupplies = new DataGridView(); + buttonDel = new Button(); panelButtons.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridViewSupplies).BeginInit(); SuspendLayout(); // // panelButtons // + panelButtons.Controls.Add(buttonDel); panelButtons.Controls.Add(buttonAdd); panelButtons.Dock = DockStyle.Right; panelButtons.Location = new Point(569, 0); @@ -75,6 +77,18 @@ dataGridViewSupplies.Size = new Size(569, 338); dataGridViewSupplies.TabIndex = 6; // + // buttonDel + // + buttonDel.BackgroundImage = Properties.Resources.Button_Delete; + buttonDel.BackgroundImageLayout = ImageLayout.Stretch; + buttonDel.Location = new Point(18, 241); + buttonDel.Margin = new Padding(3, 2, 3, 2); + buttonDel.Name = "buttonDel"; + buttonDel.Size = new Size(99, 75); + buttonDel.TabIndex = 3; + buttonDel.UseVisualStyleBackColor = true; + buttonDel.Click += ButtonDel_Click; + // // FormSupplies // AutoScaleDimensions = new SizeF(7F, 15F); @@ -95,5 +109,6 @@ private Panel panelButtons; private Button buttonAdd; private DataGridView dataGridViewSupplies; + private Button buttonDel; } } \ No newline at end of file diff --git a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormSupplies.cs b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormSupplies.cs index 3701d1d..b49b261 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormSupplies.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormSupplies.cs @@ -45,4 +45,41 @@ public partial class FormSupplies : Form // Загрузка списка поставок в DataGridView dataGridViewSupplies.DataSource = _supplyRepository.ReadSupplies().ToList(); } + + private void ButtonDel_Click(object sender, EventArgs e) + { + if (!TryGetIdentifierFromSelectedRow(out var orderId)) + { + return; + } + + if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes) + { + return; + } + + try + { + _supplyRepository.DeleteSupply(orderId); + LoadList(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private bool TryGetIdentifierFromSelectedRow(out int id) + { + id = 0; + if (dataGridViewSupplies.SelectedRows.Count < 1) + { + MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return false; + } + + // Получение идентификатора выбранного магазина + id = Convert.ToInt32(dataGridViewSupplies.SelectedRows[0].Cells["Id"].Value); + return true; + } } diff --git a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormSupplyDistributionReport.Designer.cs b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormSupplyDistributionReport.Designer.cs new file mode 100644 index 0000000..468de24 --- /dev/null +++ b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormSupplyDistributionReport.Designer.cs @@ -0,0 +1,108 @@ +namespace ProjectOpticsStore.Forms +{ + partial class FormSupplyDistributionReport + { + /// + /// 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() + { + buttonSelectFileName = new Button(); + buttonCreate = new Button(); + dateTimePicker = new DateTimePicker(); + labelFileName = new Label(); + label2 = new Label(); + SuspendLayout(); + // + // buttonSelectFileName + // + buttonSelectFileName.Location = new Point(29, 36); + buttonSelectFileName.Name = "buttonSelectFileName"; + buttonSelectFileName.Size = new Size(75, 23); + buttonSelectFileName.TabIndex = 0; + buttonSelectFileName.Text = "Выбрать"; + buttonSelectFileName.UseVisualStyleBackColor = true; + buttonSelectFileName.Click += ButtonSelectFileName_Click; + // + // buttonCreate + // + buttonCreate.Location = new Point(110, 176); + buttonCreate.Name = "buttonCreate"; + buttonCreate.Size = new Size(112, 23); + buttonCreate.TabIndex = 1; + buttonCreate.Text = "Сформировать"; + buttonCreate.UseVisualStyleBackColor = true; + buttonCreate.Click += ButtonCreate_Click; + // + // dateTimePicker + // + dateTimePicker.Location = new Point(100, 81); + dateTimePicker.Name = "dateTimePicker"; + dateTimePicker.Size = new Size(200, 23); + dateTimePicker.TabIndex = 2; + // + // labelFileName + // + labelFileName.AutoSize = true; + labelFileName.Location = new Point(138, 40); + labelFileName.Name = "labelFileName"; + labelFileName.Size = new Size(36, 15); + labelFileName.TabIndex = 3; + labelFileName.Text = "Файл"; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(29, 87); + label2.Name = "label2"; + label2.Size = new Size(35, 15); + label2.TabIndex = 4; + label2.Text = "Дата:"; + // + // FormSupplyDistributionReport + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(332, 233); + Controls.Add(label2); + Controls.Add(labelFileName); + Controls.Add(dateTimePicker); + Controls.Add(buttonCreate); + Controls.Add(buttonSelectFileName); + Name = "FormSupplyDistributionReport"; + StartPosition = FormStartPosition.CenterParent; + Text = "Поставки товара"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Button buttonSelectFileName; + private Button buttonCreate; + private DateTimePicker dateTimePicker; + private Label labelFileName; + private Label label2; + } +} \ No newline at end of file diff --git a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormSupplyDistributionReport.cs b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormSupplyDistributionReport.cs new file mode 100644 index 0000000..13fcb04 --- /dev/null +++ b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormSupplyDistributionReport.cs @@ -0,0 +1,64 @@ +using ProjectOpticsStore.Reports; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using Unity; + +namespace ProjectOpticsStore.Forms; + +public partial class FormSupplyDistributionReport : Form +{ + private string _fileName = string.Empty; + + private readonly IUnityContainer _container; + public FormSupplyDistributionReport(IUnityContainer container) + { + InitializeComponent(); + _container = container ?? throw new ArgumentNullException(nameof(container)); + } + + private void ButtonCreate_Click(object sender, EventArgs e) + { + try + { + if (string.IsNullOrWhiteSpace(_fileName)) + { + throw new Exception("Отсутствует имя файла для отчета"); + } + if + (_container.Resolve().CreateChart(_fileName, dateTimePicker.Value)) + { + MessageBox.Show("Документ сформирован", "Формирование документа", + MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах", + "Формирование документа", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при создании очета", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonSelectFileName_Click(object sender, EventArgs e) + { + var sfd = new SaveFileDialog() + { + Filter = "Pdf Files | *.pdf" + }; + if (sfd.ShowDialog() == DialogResult.OK) + { + _fileName = sfd.FileName; + labelFileName.Text = Path.GetFileName(_fileName); + } + } +} diff --git a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormSupplyDistributionReport.resx b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormSupplyDistributionReport.resx new file mode 100644 index 0000000..8b2ff64 --- /dev/null +++ b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormSupplyDistributionReport.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/ProjectOpticsStore/ProjectOpticsStore/ProjectOpticsStore.csproj b/ProjectOpticsStore/ProjectOpticsStore/ProjectOpticsStore.csproj index ac8876e..e5c4465 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/ProjectOpticsStore.csproj +++ b/ProjectOpticsStore/ProjectOpticsStore/ProjectOpticsStore.csproj @@ -14,12 +14,14 @@ + + diff --git a/ProjectOpticsStore/ProjectOpticsStore/Reports/ChartReport.cs b/ProjectOpticsStore/ProjectOpticsStore/Reports/ChartReport.cs new file mode 100644 index 0000000..eee703f --- /dev/null +++ b/ProjectOpticsStore/ProjectOpticsStore/Reports/ChartReport.cs @@ -0,0 +1,48 @@ +using Microsoft.Extensions.Logging; +using ProjectOpticsStore.Repositories; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectOpticsStore.Reports; + +public class ChartReport +{ + private readonly ISupplyRepository _supplyRepository; // Изменение типа репозитория + private readonly ILogger _logger; + + public ChartReport(ISupplyRepository supplyRepository, ILogger logger) // Изменение параметра конструктора + { + _supplyRepository = supplyRepository ?? throw new ArgumentNullException(nameof(supplyRepository)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public bool CreateChart(string filePath, DateTime dateTime) + { + try + { + new PdfBuilder(filePath) + .AddHeader("Распределение поставок по товарам") // Изменено заголовок для соответствия Supply + .AddPieChart("Поставки", GetData(dateTime)) // Изменено название графика + .Build(); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + } + + private List<(string Caption, double Value)> GetData(DateTime dateTime) + { + return _supplyRepository + .ReadSupplies() // Изменено на метод, который читает поставки + .Where(x => x.OperationDate.Date == dateTime.Date) // Используем OperationDate вместо DateCreated + .GroupBy(x => x.ProductId, (key, group) => new { ID = key, TotalQuantity = group.Sum(y => y.Quantity) }) // Группировка по ProductId + .Select(x => (x.ID.ToString(), (double)x.TotalQuantity)) // Изменено на TotalQuantity + .ToList(); + } +} diff --git a/ProjectOpticsStore/ProjectOpticsStore/Reports/DocReport.cs b/ProjectOpticsStore/ProjectOpticsStore/Reports/DocReport.cs new file mode 100644 index 0000000..1de3d8e --- /dev/null +++ b/ProjectOpticsStore/ProjectOpticsStore/Reports/DocReport.cs @@ -0,0 +1,77 @@ +using Microsoft.Extensions.Logging; +using ProjectOpticsStore.Repositories; +namespace ProjectOpticsStore.Reports; + +public class DocReport +{ + private readonly ICustomerRepository _customerRepository; + private readonly IStoreRepository _storeRepository; + private readonly IProductRepository _productRepository; + private readonly ILogger _logger; + + public DocReport(ICustomerRepository customerRepository, IStoreRepository storeRepository, + IProductRepository productRepository, ILogger logger) + { + _customerRepository = customerRepository ?? throw new ArgumentNullException(nameof(customerRepository)); + _storeRepository = storeRepository ?? throw new ArgumentNullException(nameof(storeRepository)); + _productRepository = productRepository ?? throw new ArgumentNullException(nameof(productRepository)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); ; + } + + public bool CreateDoc(string filePath, bool includeCustomers, bool includeStores, bool includeProducts) + { + try + { + var builder = new WordBuilder(filePath).AddHeader("Документ со справочниками"); + if (includeCustomers) + { + builder.AddParagraph("Заказчики").AddTable([2400], GetCustomers()); + } + if (includeStores) + { + builder.AddParagraph("Магазины").AddTable([2400], GetStores()); + } + if (includeProducts) + { + builder.AddParagraph("Товары").AddTable([2400, 2400, 2400, 2400, 2400, 2400], GetProducts()); + } + builder.Build(); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + } + + private List GetCustomers() + { + return [ + ["ФИО Заказчика"], + .. _customerRepository + .ReadCustomers() + .Select(x => new string[] { x.FullName}), + ]; + } + + private List GetStores() + { + return [ + ["Адрес магазина"], + .. _storeRepository + .ReadStores() + .Select(x => new string[] { x.Address}), + ]; + } + + private List GetProducts() + { + return [ + ["Тип", "Мощность", "Цена", "Магазин","Толщина", "Болезнь"], + .. _productRepository + .ReadProducts() + .Select(x => new string[] {x.Type.ToString(), x.Power.ToString(), x.Price.ToString(), x.Store.ToString(), x.Thickness.ToString(), x.Disease}), + ]; + } +} \ No newline at end of file diff --git a/ProjectOpticsStore/ProjectOpticsStore/Reports/ExcelBuilder.cs b/ProjectOpticsStore/ProjectOpticsStore/Reports/ExcelBuilder.cs new file mode 100644 index 0000000..39a83a5 --- /dev/null +++ b/ProjectOpticsStore/ProjectOpticsStore/Reports/ExcelBuilder.cs @@ -0,0 +1,311 @@ +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Spreadsheet; +using DocumentFormat.OpenXml; + +namespace ProjectOpticsStore.Reports; + +public class ExcelBuilder +{ + private readonly string _filePath; + private readonly SheetData _sheetData; + private readonly MergeCells _mergeCells; + private readonly Columns _columns; + private uint _rowIndex = 0; + + public ExcelBuilder(string filePath) + { + if (string.IsNullOrWhiteSpace(filePath)) + { + throw new ArgumentNullException(nameof(filePath)); + } + if (File.Exists(filePath)) + { + File.Delete(filePath); + } + _filePath = filePath; + _sheetData = new SheetData(); + _mergeCells = new MergeCells(); + _columns = new Columns(); + _rowIndex = 1; + } + + public ExcelBuilder AddHeader(string header, int startIndex, int count) + { + CreateCell(startIndex, _rowIndex, header, StyleIndex.BoldTextWithBorder); + for (int i = startIndex + 1; i < startIndex + count; ++i) + { + CreateCell(i, _rowIndex, "", StyleIndex.BoldTextWithBorder); + } + _mergeCells.Append(new MergeCell() + { + Reference = new StringValue($"{GetExcelColumnName(startIndex)}{_rowIndex}:{GetExcelColumnName(startIndex + count - 1)}{_rowIndex}") + }); + _rowIndex++; + return this; + } + + public ExcelBuilder AddParagraph(string text, int columnIndex) + { + CreateCell(columnIndex, _rowIndex++, text, StyleIndex.SimpleTextWithoutBorder); + return this; + } + public ExcelBuilder AddTable(int[] columnsWidths, List data) + { + if (columnsWidths == null || columnsWidths.Length == 0) + { + throw new ArgumentNullException(nameof(columnsWidths)); + } + if (data == null || data.Count == 0) + { + throw new ArgumentNullException(nameof(data)); + } + if (data.Any(x => x.Length != columnsWidths.Length)) + { + throw new InvalidOperationException("widths.Length != data.Length"); + } + uint counter = 1; + int coef = 2; + _columns.Append(columnsWidths.Select(x => new Column + { + Min = counter, + Max = counter++, + Width = x * coef, + CustomWidth = true + })); + for (var j = 0; j < data.First().Length; ++j) + { + CreateCell(j, _rowIndex, data.First()[j], StyleIndex.BoldTextWithBorder); + } + _rowIndex++; + for (var i = 1; i < data.Count - 1; ++i) + { + for (var j = 0; j < data[i].Length; ++j) + { + CreateCell(j, _rowIndex, data[i][j], StyleIndex.SimpleTextWithBorder); + } + _rowIndex++; + } + for (var j = 0; j < data.Last().Length; ++j) + { + CreateCell(j, _rowIndex, data.Last()[j], StyleIndex.BoldTextWithBorder); + } + _rowIndex++; + return this; + } + + public void Build() + { + using var spreadsheetDocument = SpreadsheetDocument.Create(_filePath, SpreadsheetDocumentType.Workbook); + var workbookpart = spreadsheetDocument.AddWorkbookPart(); + GenerateStyle(workbookpart); + workbookpart.Workbook = new Workbook(); + var worksheetPart = workbookpart.AddNewPart(); + worksheetPart.Worksheet = new Worksheet(); + if (_columns.HasChildren) + { + worksheetPart.Worksheet.Append(_columns); + } + worksheetPart.Worksheet.Append(_sheetData); + var sheets = spreadsheetDocument.WorkbookPart!.Workbook.AppendChild(new Sheets()); + var sheet = new Sheet() + { + Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), + SheetId = 1, + Name = "Лист 1" + }; + sheets.Append(sheet); + if (_mergeCells.HasChildren) + { + worksheetPart.Worksheet.InsertAfter(_mergeCells, worksheetPart.Worksheet.Elements().First()); + } + } + + private static void GenerateStyle(WorkbookPart workbookPart) + { + //Создаем объект для хранения стилей т.н. Open XML SDK + var workbookStylesPart = workbookPart.AddNewPart(); + workbookStylesPart.Stylesheet = new Stylesheet(); + + var fonts = new Fonts() + { + Count = 2, + KnownFonts = BooleanValue.FromBoolean(true) + }; + fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font + { + FontSize = new FontSize() { Val = 11 }, + FontName = new FontName() { Val = "Calibri" }, + FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 }, + FontScheme = new FontScheme() + { + Val = new EnumValue(FontSchemeValues.Minor) + } + }); + + fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font + { + FontSize = new FontSize() { Val = 11 }, + FontName = new FontName() { Val = "Calibri" }, + Bold = new Bold(), + FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 }, + FontScheme = new FontScheme() + { + Val = new EnumValue(FontSchemeValues.Minor) + } + }); + workbookStylesPart.Stylesheet.Append(fonts); + // Default Fill + var fills = new Fills() { Count = 1 }; + fills.Append(new Fill + { + PatternFill = new PatternFill() + { + PatternType = new EnumValue(PatternValues.None) + } + }); + workbookStylesPart.Stylesheet.Append(fills); + // Default Border + var borders = new Borders() { Count = 2 }; + borders.Append(new Border + { + LeftBorder = new LeftBorder(), + RightBorder = new RightBorder(), + TopBorder = new TopBorder(), + BottomBorder = new BottomBorder(), + DiagonalBorder = new DiagonalBorder() + }); + + borders.Append(new Border + { + LeftBorder = new LeftBorder() { Style = BorderStyleValues.Medium }, + RightBorder = new RightBorder() { Style = BorderStyleValues.Medium }, + TopBorder = new TopBorder() { Style = BorderStyleValues.Medium }, + BottomBorder = new BottomBorder() { Style = BorderStyleValues.Medium }, + DiagonalBorder = new DiagonalBorder() { Style = BorderStyleValues.Medium }, + }); + workbookStylesPart.Stylesheet.Append(borders); + // Default cell format and a date cell format (коллекцмя формата ячеек) + var cellFormats = new CellFormats() { Count = 4 }; + // Обычный формат + cellFormats.Append(new CellFormat + { + NumberFormatId = 0, + FormatId = 0, + FontId = 0, + BorderId = 0, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Left, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + + // Формат с границей + cellFormats.Append(new CellFormat + { + NumberFormatId = 1, + FormatId = 0, + FontId = 0, + BorderId = 1, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Left, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + + // Жирный шрифт без границы + cellFormats.Append(new CellFormat + { + NumberFormatId = 2, + FormatId = 0, + FontId = 1, + BorderId = 0, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Left, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + + // Жирный шрифт с границей + cellFormats.Append(new CellFormat + { + NumberFormatId = 3, + FormatId = 0, + FontId = 1, + BorderId = 1, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Left, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + workbookStylesPart.Stylesheet.Append(cellFormats); + } + + private enum StyleIndex + { + SimpleTextWithoutBorder = 0, + SimpleTextWithBorder = 1, + BoldTextWithoutBorder = 2, + BoldTextWithBorder = 3, + } + + private void CreateCell(int columnIndex, uint rowIndex, string text, StyleIndex styleIndex) + { + var columnName = GetExcelColumnName(columnIndex); + var cellReference = columnName + rowIndex; + var row = _sheetData.Elements().FirstOrDefault(r => r.RowIndex! == rowIndex); + if (row == null) + { + row = new Row() { RowIndex = rowIndex }; + _sheetData.Append(row); + } + var newCell = row.Elements().FirstOrDefault(c => c.CellReference != null && c.CellReference.Value == columnName + rowIndex); + if (newCell == null) + { + Cell? refCell = null; + foreach (Cell cell in row.Elements()) + { + if (cell.CellReference?.Value != null && cell.CellReference.Value.Length == cellReference.Length) + { + if (string.Compare(cell.CellReference.Value, cellReference, true) > 0) + { + refCell = cell; + break; + } + } + } + newCell = new Cell() { CellReference = cellReference }; + row.InsertBefore(newCell, refCell); + } + newCell.CellValue = new CellValue(text); + newCell.DataType = CellValues.String; + newCell.StyleIndex = (uint)styleIndex; + } + + private static string GetExcelColumnName(int columnNumber) + { + columnNumber += 1; + int dividend = columnNumber; + string columnName = string.Empty; + int modulo; + while (dividend > 0) + { + modulo = (dividend - 1) % 26; + columnName = Convert.ToChar(65 + modulo).ToString() + + columnName; + dividend = (dividend - modulo) / 26; + } + return columnName; + } +} diff --git a/ProjectOpticsStore/ProjectOpticsStore/Reports/PdfBuilder.cs b/ProjectOpticsStore/ProjectOpticsStore/Reports/PdfBuilder.cs new file mode 100644 index 0000000..e451203 --- /dev/null +++ b/ProjectOpticsStore/ProjectOpticsStore/Reports/PdfBuilder.cs @@ -0,0 +1,90 @@ +using MigraDoc.DocumentObjectModel; +using MigraDoc.DocumentObjectModel.Shapes.Charts; +using MigraDoc.Rendering; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Color = MigraDoc.DocumentObjectModel.Color; + + +namespace ProjectOpticsStore.Reports; + +public class PdfBuilder +{ + private readonly string _filePath; + private readonly Document _document; + public PdfBuilder(string filePath) + { + if (string.IsNullOrWhiteSpace(filePath)) + { + throw new ArgumentNullException(nameof(filePath)); + } + if (File.Exists(filePath)) + { + File.Delete(filePath); + } + _filePath = filePath; + _document = new Document(); + DefineStyles(); + } + public PdfBuilder AddHeader(string header) + { + _document.AddSection().AddParagraph(header, "NormalBold"); + return this; + } + + public PdfBuilder AddPieChart(string title, List<(string Caption, double Value)> data) + { + if (data == null || data.Count == 0) + { + return this; + } + var chart = new Chart(ChartType.Pie2D); + var series = chart.SeriesCollection.AddSeries(); + series.Add(data.Select(x => x.Value).ToArray()); + + var xseries = chart.XValues.AddXSeries(); + xseries.Add(data.Select(x => x.Caption).ToArray()); + + chart.DataLabel.Type = DataLabelType.Percent; + chart.DataLabel.Position = DataLabelPosition.OutsideEnd; + + chart.Width = Unit.FromCentimeter(16); + chart.Height = Unit.FromCentimeter(12); + + chart.TopArea.AddParagraph(title); + + chart.XAxis.MajorTickMark = TickMarkType.Outside; + + chart.YAxis.MajorTickMark = TickMarkType.Outside; + chart.YAxis.HasMajorGridlines = true; + + chart.PlotArea.LineFormat.Width = 1; + chart.PlotArea.LineFormat.Visible = true; + + chart.TopArea.AddLegend(); + + _document.LastSection.Add(chart); + return this; + } + + public void Build() + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + var renderer = new PdfDocumentRenderer(true) + { + Document = _document + }; + renderer.RenderDocument(); + renderer.PdfDocument.Save(_filePath); + } + private void DefineStyles() + { + var headerStyle = _document.AddStyle("NormalBold", "Normal"); + headerStyle.Font.Bold = true; + headerStyle.Font.Size = 14; + headerStyle.Font.Color = Colors.DeepPink; + } +} diff --git a/ProjectOpticsStore/ProjectOpticsStore/Reports/TableReport.cs b/ProjectOpticsStore/ProjectOpticsStore/Reports/TableReport.cs new file mode 100644 index 0000000..397c4a8 --- /dev/null +++ b/ProjectOpticsStore/ProjectOpticsStore/Reports/TableReport.cs @@ -0,0 +1,81 @@ +using Microsoft.Extensions.Logging; +using ProjectOpticsStore.Repositories; + +namespace ProjectOpticsStore.Reports; + +public class TableReport +{ + private readonly IOrderRepository _orderRepository; + private readonly ISupplyRepository _supplyRepository; + private readonly ILogger _logger; + internal static readonly string[] item = ["Продукт", "Дата", "Количество пришло", "Количество ушло"]; + + public TableReport(IOrderRepository orderRepository, ISupplyRepository supplyRepository, + ILogger logger) + { + _orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository)); + _supplyRepository = supplyRepository ?? throw new ArgumentNullException(nameof(supplyRepository)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + public bool CreateTable(string filePath, int productID, DateTime startDate, DateTime endDate) + { + try + { + new ExcelBuilder(filePath) + .AddHeader("Сводка по движению товара", 0, 4) + .AddParagraph("за период", 0) + .AddTable([10, 10, 15, 15], GetData(productID, startDate, endDate)) + .Build(); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + } + + private List GetData(int productID, DateTime startDate, DateTime endDate) + { + var data = _orderRepository + .ReadOrders() + .Where(x => x.DateCreated >= startDate && x.DateCreated <= endDate && x.OrderProducts.Any(y => y.ProductId == productID)) + .Select(x => new + { + ProductID = x.OrderProducts.First(y => y.ProductId == productID).ProductId, + Date = x.DateCreated, + CountIn = (int?)null, + CountOut = (int?)x.OrderProducts.FirstOrDefault(y => y.ProductId == productID)?.Quantity + }) + .Union( + _supplyRepository + .ReadSupplies() + .Where(x => x.OperationDate >= startDate && x.OperationDate <= endDate && x.ProductId == productID) + .Select(x => new + { + ProductID = x.ProductId, + Date = x.OperationDate, + CountIn = (int?)x.Quantity, + CountOut = (int?)null + })) + .OrderBy(x => x.Date); + + return + new List { TableReport.item } + .Union( + data.Select(x => new string[] + { + x.ProductID.ToString(), + x.Date.ToString(), + x.CountIn?.ToString() ?? string.Empty, + x.CountOut?.ToString() ?? string.Empty + })) + .Union(new[] { + new[] { "Всего", "", data.Sum(x => x.CountIn ?? 0).ToString(), data.Sum(x => x.CountOut ?? 0).ToString() } + }) + .ToList(); + } +} + + + diff --git a/ProjectOpticsStore/ProjectOpticsStore/Reports/WordBuilder.cs b/ProjectOpticsStore/ProjectOpticsStore/Reports/WordBuilder.cs new file mode 100644 index 0000000..c1f801c --- /dev/null +++ b/ProjectOpticsStore/ProjectOpticsStore/Reports/WordBuilder.cs @@ -0,0 +1,88 @@ +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Wordprocessing; +using DocumentFormat.OpenXml; + +namespace ProjectOpticsStore.Reports; + +public class WordBuilder +{ + private readonly string _filePath; + private readonly Document _document; + private readonly Body _body; + public WordBuilder(string filePath) + { + if (string.IsNullOrWhiteSpace(filePath)) + { + throw new ArgumentNullException(nameof(filePath)); + } + if (File.Exists(filePath)) + { + File.Delete(filePath); + } + _filePath = filePath; + _document = new Document(); + _body = _document.AppendChild(new Body()); + } + + public WordBuilder AddHeader(string header) + { + var paragraph = _body.AppendChild(new Paragraph()); + var run = paragraph.AppendChild(new Run()); + run.PrependChild(new RunProperties()); + run.RunProperties.AddChild(new Bold()); + run.AppendChild(new Text(header)); + return this; + } + public WordBuilder AddParagraph(string text) + { + var paragraph = _body.AppendChild(new Paragraph()); + var run = paragraph.AppendChild(new Run()); + run.AppendChild(new Text(text)); + return this; + } + + public WordBuilder AddTable(int[] widths, List data) + { + if (widths == null || widths.Length == 0) + { + throw new ArgumentNullException(nameof(widths)); + } + if (data == null || data.Count == 0) + { + throw new ArgumentNullException(nameof(data)); + } + if (data.Any(x => x.Length != widths.Length)) + { + throw new InvalidOperationException("widths.Length != data.Length"); + } + var table = new Table(); + table.AppendChild(new TableProperties( + new TableBorders( + new TopBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, + new BottomBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, + new LeftBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, + new RightBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, + new InsideHorizontalBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, + new InsideVerticalBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }))); + + // Заголовок + var tr = new TableRow(); + for (var j = 0; j < widths.Length; ++j) + { + tr.Append(new TableCell(new TableCellProperties(new TableCellWidth() { Width = widths[j].ToString() }), + new Paragraph(new Run(new RunProperties(new Bold()), new Text(data.First()[j]))))); + } + table.Append(tr); + // Данные + table.Append(data.Skip(1).Select(x => new TableRow(x.Select(y => new TableCell(new Paragraph(new Run(new Text(y)))))))); + _body.Append(table); + return this; + } + public void Build() + { + using var wordDocument = WordprocessingDocument.Create(_filePath, + WordprocessingDocumentType.Document); + var mainPart = wordDocument.AddMainDocumentPart(); + mainPart.Document = _document; + } +} \ No newline at end of file diff --git a/ProjectOpticsStore/ProjectOpticsStore/Repositories/IOrderRepository.cs b/ProjectOpticsStore/ProjectOpticsStore/Repositories/IOrderRepository.cs index 0b0da2c..033960c 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Repositories/IOrderRepository.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/Repositories/IOrderRepository.cs @@ -8,5 +8,4 @@ public interface IOrderRepository int? customerId = null ); void CreateOrder(Order order); - void DeleteOrder(int id); } diff --git a/ProjectOpticsStore/ProjectOpticsStore/Repositories/ISupplyRepository.cs b/ProjectOpticsStore/ProjectOpticsStore/Repositories/ISupplyRepository.cs index 16be7fa..8f35b2b 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Repositories/ISupplyRepository.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/Repositories/ISupplyRepository.cs @@ -10,4 +10,6 @@ public interface ISupplyRepository ); void CreateSupply(Supply supply); + + void DeleteSupply(int id); } diff --git a/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/OrderRepository.cs b/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/OrderRepository.cs index f2deeac..37e3a94 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/OrderRepository.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/OrderRepository.cs @@ -3,6 +3,7 @@ using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Npgsql; using ProjectOpticsStore.Entities; +using Unity; namespace ProjectOpticsStore.Repositories.Implementations; @@ -50,43 +51,37 @@ internal class OrderRepository : IOrderRepository } } - - public void DeleteOrder(int id) + public IEnumerable ReadOrders(DateTime? dateFrom = null, DateTime? dateTo = null, int? productId = null) { - _logger.LogInformation("Удаление объекта"); - _logger.LogDebug("Объект: {id}", id); + _logger.LogInformation("Получение всех объектов"); try { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - var queryDelete = @" - DELETE FROM Orders - WHERE Id=@id"; - connection.Execute(queryDelete, new { id }); + + var querySelect = @"SELECT o.*, op.OrderId, op.ProductId, op.Quantity + FROM Orders o + INNER JOIN Orders_Products op ON op.OrderId = o.Id"; + + _logger.LogDebug("Выполняется SQL-запрос: {Query}", querySelect); + + var orderProducts = connection.Query(querySelect); + + _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(orderProducts)); + + return orderProducts + .GroupBy( + x => x.Id, + y => y, + (key, value) => Order.CreateOperation( + value.First(), + value.Select(z => Order_Product.CreateElement(z.OrderId, z.ProductId, z.Quantity)) + ) + ).ToList(); } catch (Exception ex) { - _logger.LogError(ex, "Ошибка при удалении объекта"); + _logger.LogError(ex, "Ошибка при чтении объектов"); throw; } } - - public IEnumerable ReadOrders(DateTime? dateFrom = null, DateTime? dateTo = null, int? customerId = null) - { - { - _logger.LogInformation("Получение всех объектов"); - try - { - using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - var querySelect = "SELECT * FROM Orders"; - var orders = connection.Query(querySelect); - _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(orders)); - return orders; - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка при чтении объектов"); - throw; - } - } - } } \ No newline at end of file diff --git a/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/SupplyRepository.cs b/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/SupplyRepository.cs index f741e9e..0857614 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/SupplyRepository.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/SupplyRepository.cs @@ -1,4 +1,5 @@ using Dapper; +using DocumentFormat.OpenXml.Office2010.Excel; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Npgsql; @@ -37,6 +38,25 @@ internal class SupplyRepository : ISupplyRepository } } + public void DeleteSupply(int id) + { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" + DELETE FROM Supplies + WHERE Id=@id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } + } + public IEnumerable ReadSupplies(DateTime? dateFrom = null, DateTime? dateTo = null, int? storeId = null, int? productId = null) { _logger.LogInformation("Получение всех объектов");