Merge branch 'LabWork_2' into LabWork_3

This commit is contained in:
SVETLANA_8 2024-12-06 11:40:14 +03:00
commit cccd753680
8 changed files with 49 additions and 58 deletions

View File

@ -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
};

View File

@ -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;
}
}

View File

@ -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,13 +34,20 @@ 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<DataGridViewRow>();
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);
@ -48,25 +55,26 @@ namespace ProjectAtelier.Forms
}
}
}
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());
}
}

View File

@ -117,7 +117,4 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="ColumProduct.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -171,7 +171,6 @@
ColumProduct.HeaderText = "Изделие";
ColumProduct.MinimumWidth = 6;
ColumProduct.Name = "ColumProduct";
ColumProduct.ReadOnly = true;
//
// ColumnCount
//

View File

@ -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<OrderProduct> CreateListProductFromDataGrid()
{
var list = new List<OrderProduct>();
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;
}
}
}

View File

@ -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();
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<int>(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;

View File

@ -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);
}
}