From 7b9bda47142abd71f2c7c22ebf2a834f25382941 Mon Sep 17 00:00:00 2001 From: SVETLANA_8 Date: Fri, 6 Dec 2024 11:39:51 +0300 Subject: [PATCH] =?UTF-8?q?=D0=BF=D1=80=D0=B0=D0=B2=D0=BA=D0=B8=20=D0=BF?= =?UTF-8?q?=D0=BE=202?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ProjectAtelier/Entities/ProductMaterial.cs | 6 +-- .../Forms/FormProductMaterial.Designer.cs | 11 +---- ProjectAtelier/Forms/FormProductMaterial.cs | 48 +++++++++---------- ProjectAtelier/Forms/FormProductMaterial.resx | 3 -- .../Forms/FormProductOrder.Designer.cs | 1 - ProjectAtelier/Forms/FormProductOrder.cs | 19 ++++---- .../Implementations/OrderRepository.cs | 17 +++---- .../ProductMaterialRepository.cs | 2 +- 8 files changed, 49 insertions(+), 58 deletions(-) diff --git a/ProjectAtelier/Entities/ProductMaterial.cs b/ProjectAtelier/Entities/ProductMaterial.cs index 491bbaf..1fe1c77 100644 --- a/ProjectAtelier/Entities/ProductMaterial.cs +++ b/ProjectAtelier/Entities/ProductMaterial.cs @@ -9,16 +9,16 @@ namespace ProjectAtelier.Entities; public class ProductMaterial { public int Id { get; private set; } - public int ProductId { get; private set; } + //public int ProductId { get; private set; } public int MaterialId { get; set; } public int Count { get; set; } - public static ProductMaterial CreateOperation(int id, int productId, int materialid, int count) + public static ProductMaterial CreateOperation(int id, /*int productId*/ int materialid, int count) { return new ProductMaterial { Id = id, - ProductId = productId, + //ProductId = productId, MaterialId = materialid, Count = count }; diff --git a/ProjectAtelier/Forms/FormProductMaterial.Designer.cs b/ProjectAtelier/Forms/FormProductMaterial.Designer.cs index 6d6bae7..e2f080f 100644 --- a/ProjectAtelier/Forms/FormProductMaterial.Designer.cs +++ b/ProjectAtelier/Forms/FormProductMaterial.Designer.cs @@ -32,7 +32,6 @@ dataGridView = new DataGridView(); ColumnMaterial = new DataGridViewComboBoxColumn(); ColumnCount = new DataGridViewTextBoxColumn(); - ColumProduct = new DataGridViewTextBoxColumn(); buttonAdd = new Button(); buttonCancel = new Button(); labelName = new Label(); @@ -61,7 +60,7 @@ // dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnMaterial, ColumnCount, ColumProduct }); + dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnMaterial, ColumnCount }); dataGridView.Dock = DockStyle.Fill; dataGridView.Location = new Point(3, 24); dataGridView.Margin = new Padding(3, 4, 3, 4); @@ -71,6 +70,7 @@ dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; dataGridView.Size = new Size(642, 328); dataGridView.TabIndex = 0; + // // ColumnMaterial // @@ -86,12 +86,6 @@ ColumnCount.MinimumWidth = 6; ColumnCount.Name = "ColumnCount"; // - // ColumProduct - // - ColumProduct.HeaderText = "ColumnName"; - ColumProduct.MinimumWidth = 6; - ColumProduct.Name = "ColumProduct"; - // // buttonAdd // buttonAdd.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; @@ -207,6 +201,5 @@ private NumericUpDown numericUpDownCount; private DataGridViewComboBoxColumn ColumnMaterial; private DataGridViewTextBoxColumn ColumnCount; - private DataGridViewTextBoxColumn ColumProduct; } } \ No newline at end of file diff --git a/ProjectAtelier/Forms/FormProductMaterial.cs b/ProjectAtelier/Forms/FormProductMaterial.cs index 76bba16..337755b 100644 --- a/ProjectAtelier/Forms/FormProductMaterial.cs +++ b/ProjectAtelier/Forms/FormProductMaterial.cs @@ -16,7 +16,7 @@ namespace ProjectAtelier.Forms public partial class FormProductMaterial : Form { private readonly IProductRepository _productRepository; - private readonly IProductMaterialRepository _feedReplenishmentRepository; + private readonly IMaterialRepository _materialRepository; private int? _productId; public int Id { @@ -34,39 +34,47 @@ namespace ProjectAtelier.Forms numericUpDownCount.Value = product.CountMaterial; _productId = value; - // Заполняем DataGridView данными из product.ProductMaterial dataGridView.Rows.Clear(); - foreach (var material in product.ProductMaterial) + var rows = new List(); + foreach (var productMaterial in product.ProductMaterial) { - dataGridView.Rows.Add(material.MaterialId, material.Count); + var material = _materialRepository.ReadMaterialById(productMaterial.MaterialId); + if (material != null) + { + var row = new DataGridViewRow(); + row.CreateCells(dataGridView, material.Id, productMaterial.Count); + rows.Add(row); + } } + dataGridView.Rows.AddRange(rows.ToArray()); } catch (Exception ex) { - MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Ошибка при полученииданных", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } } - public FormProductMaterial(IProductMaterialRepository materialConsumptionRepository, IProductRepository productRepository, IMaterialRepository materialRepository) + public FormProductMaterial(IProductRepository productRepository, IMaterialRepository materialRepository) { InitializeComponent(); - _feedReplenishmentRepository = materialConsumptionRepository ?? throw new ArgumentNullException(nameof(materialConsumptionRepository)); _productRepository = productRepository ?? throw new ArgumentNullException(nameof(productRepository)); - + _materialRepository = materialRepository ?? throw new ArgumentNullException(nameof(materialRepository)); comboBoxProduct.DataSource = Enum.GetValues(typeof(ProductView)); - + + ColumnMaterial.DataSource = materialRepository.ReadMaterials(); + ColumnMaterial.DisplayMember = "Name"; + ColumnMaterial.ValueMember = "Id"; } private void buttonAdd_Click(object sender, EventArgs e) { if (dataGridView.RowCount < 1) { - MessageBox.Show("Имеются незаполненные поля", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; + throw new Exception("Имеются незаполненны поля"); } try { - if (string.IsNullOrWhiteSpace(textBoxName.Text) || comboBoxProduct.SelectedIndex < 0) + if (string.IsNullOrWhiteSpace(textBoxName.Text) || comboBoxProduct.SelectedIndex < 1) { throw new Exception("Имеются незаполненные поля"); } @@ -95,21 +103,11 @@ namespace ProjectAtelier.Forms { continue; } - list.Add(new ProductMaterial - { - MaterialId = Convert.ToInt32(row.Cells["ColumnMaterial"].Value), - Count = Convert.ToInt32(row.Cells["ColumnCount"].Value) - }); + list.Add(ProductMaterial.CreateOperation(0, Convert.ToInt32(row.Cells["ColumnMaterial"].Value), Convert.ToInt32(row.Cells["ColumnCount"].Value))); } return list; } - private Product CreateProduct(int id) => new Product - { - Id = id, - Name = textBoxName.Text, - View = (ProductView)comboBoxProduct.SelectedItem, - CountMaterial = Convert.ToInt32(numericUpDownCount.Value), - ProductMaterial = CreateListMaterialFromDataGrid() - }; + private Product CreateProduct(int id) => Product.CreateEntity(id, textBoxName.Text, (ProductView)comboBoxProduct.SelectedItem!, Convert.ToInt32(numericUpDownCount.Value), CreateListMaterialFromDataGrid()); + } } \ No newline at end of file diff --git a/ProjectAtelier/Forms/FormProductMaterial.resx b/ProjectAtelier/Forms/FormProductMaterial.resx index 605ec60..8b2ff64 100644 --- a/ProjectAtelier/Forms/FormProductMaterial.resx +++ b/ProjectAtelier/Forms/FormProductMaterial.resx @@ -117,7 +117,4 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - True - \ No newline at end of file diff --git a/ProjectAtelier/Forms/FormProductOrder.Designer.cs b/ProjectAtelier/Forms/FormProductOrder.Designer.cs index 4a9c1eb..de3bdb1 100644 --- a/ProjectAtelier/Forms/FormProductOrder.Designer.cs +++ b/ProjectAtelier/Forms/FormProductOrder.Designer.cs @@ -171,7 +171,6 @@ ColumProduct.HeaderText = "Изделие"; ColumProduct.MinimumWidth = 6; ColumProduct.Name = "ColumProduct"; - ColumProduct.ReadOnly = true; // // ColumnCount // diff --git a/ProjectAtelier/Forms/FormProductOrder.cs b/ProjectAtelier/Forms/FormProductOrder.cs index 44b36cc..ba7844a 100644 --- a/ProjectAtelier/Forms/FormProductOrder.cs +++ b/ProjectAtelier/Forms/FormProductOrder.cs @@ -2,6 +2,7 @@ using ProjectAtelier.Repositories; using System; using System.Collections.Generic; +using System.Reflection; using System.Windows.Forms; namespace ProjectAtelier.Forms @@ -20,20 +21,21 @@ namespace ProjectAtelier.Forms _clientRepository = clientRepository ?? throw new ArgumentNullException(nameof(clientRepository)); comboBoxStatus.DataSource = Enum.GetValues(typeof(OrderStatus)); - - ColumProduct.DataSource = productRepository.ReadProducts(); - ColumProduct.DisplayMember = "Name"; - ColumProduct.ValueMember = "Id"; - // Заполняем ComboBox для выбора клиента comboBoxClient.DataSource = clientRepository.ReadClients(); comboBoxClient.DisplayMember = "Name"; comboBoxClient.ValueMember = "Id"; + ColumProduct.DataSource = productRepository.ReadProducts(); + ColumProduct.DisplayMember = "View"; + ColumProduct.ValueMember = "Id"; + // Инициализация DateTimePicker dateTimePicker.Format = DateTimePickerFormat.Custom; dateTimePicker.CustomFormat = "yyyy-MM-dd HH:mm:ss"; dateTimePicker.Value = DateTime.Now; // Устанавливаем текущую дату и время по умолчанию + + } private void ButtonAdd_Click(object sender, EventArgs e) @@ -56,19 +58,20 @@ namespace ProjectAtelier.Forms } private void ButtonCancel_Click(object sender, EventArgs e) => Close(); - private List CreateListProductFromDataGrid() { var list = new List(); foreach (DataGridViewRow row in dataGridView.Rows) { - if (row.Cells["ColumProduct"].Value == null || row.Cells["ColumMaterials"].Value == null || row.Cells["ColumnCount"].Value == null) + if (row.Cells["ColumProduct"].Value == null || + row.Cells["ColumnCount"].Value == null) { continue; } - list.Add(OrderProduct.CreateOperation(0, Convert.ToInt32(row.Cells["ColumnProduct"].Value), Convert.ToInt32(row.Cells["ColumnCount"].Value))); + list.Add(OrderProduct.CreateOperation(0,Convert.ToInt32(row.Cells["ColumProduct"].Value), Convert.ToInt32(row.Cells["ColumnCount"].Value))); } return list; } + } } \ No newline at end of file diff --git a/ProjectAtelier/Repositories/Implementations/OrderRepository.cs b/ProjectAtelier/Repositories/Implementations/OrderRepository.cs index cf4f0cf..dca53c1 100644 --- a/ProjectAtelier/Repositories/Implementations/OrderRepository.cs +++ b/ProjectAtelier/Repositories/Implementations/OrderRepository.cs @@ -26,16 +26,17 @@ public class OrderRepository : IOrderRepository _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(order)); try { - using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - connection.Open(); - using var transaction = connection.BeginTransaction(); - var queryInsert = @" + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); ///Создается объект NpgsqlConnection с использованием строки подключения из _connectionString. + connection.Open(); ////открытие соединения + using var transaction = connection.BeginTransaction(); ///начинаем транзакцию + ///Выполнение запросов в рамках транзакции: + var queryInsert = @" INSERT INTO Orders (DataTime, Status, Characteristic, IdClient) VALUES (@DataTime, @Status, @Characteristic, @IdClient); SELECT MAX(Id) FROM Orders"; var orderId = connection.QueryFirst(queryInsert, order, transaction); var querySubInsert = @" - INSERT INTO Orders_Products (OrderId, ProductId, Count) + INSERT INTO Order_Products (OrderId, ProductId, Count) VALUES (@OrderId, @ProductId, @Count)"; foreach (var elem in order.OrderProduct) { @@ -44,11 +45,11 @@ public class OrderRepository : IOrderRepository orderId, elem.ProductId, elem.Count - }, transaction); + }, transaction);///добавляем в транзакцию зпросы } - transaction.Commit(); + transaction.Commit(); ///Если все запросы выполнены успешно, транзакция фиксируется с помощью метода } - catch (Exception ex) + catch (Exception ex)/// исключение логируется. { _logger.LogError(ex, "Ошибка при добавлении объекта"); throw; diff --git a/ProjectAtelier/Repositories/Implementations/ProductMaterialRepository.cs b/ProjectAtelier/Repositories/Implementations/ProductMaterialRepository.cs index 88a3042..3692f9a 100644 --- a/ProjectAtelier/Repositories/Implementations/ProductMaterialRepository.cs +++ b/ProjectAtelier/Repositories/Implementations/ProductMaterialRepository.cs @@ -20,6 +20,6 @@ public class ProductMaterialRepository : IProductMaterialRepository public ProductMaterial ReadMaterialConsumptionById(int id) { - return ProductMaterial.CreateOperation(id, 0, 0, 0); + return ProductMaterial.CreateOperation(id, 0, 0); } }