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 class ProductMaterial
{ {
public int Id { get; private set; } 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 MaterialId { get; set; }
public int Count { 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 return new ProductMaterial
{ {
Id = id, Id = id,
ProductId = productId, //ProductId = productId,
MaterialId = materialid, MaterialId = materialid,
Count = count Count = count
}; };

View File

@ -32,7 +32,6 @@
dataGridView = new DataGridView(); dataGridView = new DataGridView();
ColumnMaterial = new DataGridViewComboBoxColumn(); ColumnMaterial = new DataGridViewComboBoxColumn();
ColumnCount = new DataGridViewTextBoxColumn(); ColumnCount = new DataGridViewTextBoxColumn();
ColumProduct = new DataGridViewTextBoxColumn();
buttonAdd = new Button(); buttonAdd = new Button();
buttonCancel = new Button(); buttonCancel = new Button();
labelName = new Label(); labelName = new Label();
@ -61,7 +60,7 @@
// //
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnMaterial, ColumnCount, ColumProduct }); dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnMaterial, ColumnCount });
dataGridView.Dock = DockStyle.Fill; dataGridView.Dock = DockStyle.Fill;
dataGridView.Location = new Point(3, 24); dataGridView.Location = new Point(3, 24);
dataGridView.Margin = new Padding(3, 4, 3, 4); dataGridView.Margin = new Padding(3, 4, 3, 4);
@ -71,6 +70,7 @@
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(642, 328); dataGridView.Size = new Size(642, 328);
dataGridView.TabIndex = 0; dataGridView.TabIndex = 0;
// //
// ColumnMaterial // ColumnMaterial
// //
@ -86,12 +86,6 @@
ColumnCount.MinimumWidth = 6; ColumnCount.MinimumWidth = 6;
ColumnCount.Name = "ColumnCount"; ColumnCount.Name = "ColumnCount";
// //
// ColumProduct
//
ColumProduct.HeaderText = "ColumnName";
ColumProduct.MinimumWidth = 6;
ColumProduct.Name = "ColumProduct";
//
// buttonAdd // buttonAdd
// //
buttonAdd.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; buttonAdd.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
@ -207,6 +201,5 @@
private NumericUpDown numericUpDownCount; private NumericUpDown numericUpDownCount;
private DataGridViewComboBoxColumn ColumnMaterial; private DataGridViewComboBoxColumn ColumnMaterial;
private DataGridViewTextBoxColumn ColumnCount; private DataGridViewTextBoxColumn ColumnCount;
private DataGridViewTextBoxColumn ColumProduct;
} }
} }

View File

@ -16,7 +16,7 @@ namespace ProjectAtelier.Forms
public partial class FormProductMaterial : Form public partial class FormProductMaterial : Form
{ {
private readonly IProductRepository _productRepository; private readonly IProductRepository _productRepository;
private readonly IProductMaterialRepository _feedReplenishmentRepository; private readonly IMaterialRepository _materialRepository;
private int? _productId; private int? _productId;
public int Id public int Id
{ {
@ -34,39 +34,47 @@ namespace ProjectAtelier.Forms
numericUpDownCount.Value = product.CountMaterial; numericUpDownCount.Value = product.CountMaterial;
_productId = value; _productId = value;
// Заполняем DataGridView данными из product.ProductMaterial
dataGridView.Rows.Clear(); 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) catch (Exception ex)
{ {
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Ошибка при полученииданных", MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
} }
} }
public FormProductMaterial(IProductMaterialRepository materialConsumptionRepository, IProductRepository productRepository, IMaterialRepository materialRepository) public FormProductMaterial(IProductRepository productRepository, IMaterialRepository materialRepository)
{ {
InitializeComponent(); InitializeComponent();
_feedReplenishmentRepository = materialConsumptionRepository ?? throw new ArgumentNullException(nameof(materialConsumptionRepository));
_productRepository = productRepository ?? throw new ArgumentNullException(nameof(productRepository)); _productRepository = productRepository ?? throw new ArgumentNullException(nameof(productRepository));
_materialRepository = materialRepository ?? throw new ArgumentNullException(nameof(materialRepository));
comboBoxProduct.DataSource = Enum.GetValues(typeof(ProductView)); comboBoxProduct.DataSource = Enum.GetValues(typeof(ProductView));
ColumnMaterial.DataSource = materialRepository.ReadMaterials();
ColumnMaterial.DisplayMember = "Name";
ColumnMaterial.ValueMember = "Id";
} }
private void buttonAdd_Click(object sender, EventArgs e) private void buttonAdd_Click(object sender, EventArgs e)
{ {
if (dataGridView.RowCount < 1) if (dataGridView.RowCount < 1)
{ {
MessageBox.Show("Имеются незаполненные поля", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); throw new Exception("Имеются незаполненны поля");
return;
} }
try try
{ {
if (string.IsNullOrWhiteSpace(textBoxName.Text) || comboBoxProduct.SelectedIndex < 0) if (string.IsNullOrWhiteSpace(textBoxName.Text) || comboBoxProduct.SelectedIndex < 1)
{ {
throw new Exception("Имеются незаполненные поля"); throw new Exception("Имеются незаполненные поля");
} }
@ -95,21 +103,11 @@ namespace ProjectAtelier.Forms
{ {
continue; continue;
} }
list.Add(new ProductMaterial list.Add(ProductMaterial.CreateOperation(0, Convert.ToInt32(row.Cells["ColumnMaterial"].Value), Convert.ToInt32(row.Cells["ColumnCount"].Value)));
{
MaterialId = Convert.ToInt32(row.Cells["ColumnMaterial"].Value),
Count = Convert.ToInt32(row.Cells["ColumnCount"].Value)
});
} }
return list; return list;
} }
private Product CreateProduct(int id) => new Product private Product CreateProduct(int id) => Product.CreateEntity(id, textBoxName.Text, (ProductView)comboBoxProduct.SelectedItem!, Convert.ToInt32(numericUpDownCount.Value), CreateListMaterialFromDataGrid());
{
Id = id,
Name = textBoxName.Text,
View = (ProductView)comboBoxProduct.SelectedItem,
CountMaterial = Convert.ToInt32(numericUpDownCount.Value),
ProductMaterial = CreateListMaterialFromDataGrid()
};
} }
} }

View File

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

View File

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

View File

@ -2,6 +2,7 @@
using ProjectAtelier.Repositories; using ProjectAtelier.Repositories;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Reflection;
using System.Windows.Forms; using System.Windows.Forms;
namespace ProjectAtelier.Forms namespace ProjectAtelier.Forms
@ -20,20 +21,21 @@ namespace ProjectAtelier.Forms
_clientRepository = clientRepository ?? throw new ArgumentNullException(nameof(clientRepository)); _clientRepository = clientRepository ?? throw new ArgumentNullException(nameof(clientRepository));
comboBoxStatus.DataSource = Enum.GetValues(typeof(OrderStatus)); comboBoxStatus.DataSource = Enum.GetValues(typeof(OrderStatus));
ColumProduct.DataSource = productRepository.ReadProducts();
ColumProduct.DisplayMember = "Name";
ColumProduct.ValueMember = "Id";
// Заполняем ComboBox для выбора клиента // Заполняем ComboBox для выбора клиента
comboBoxClient.DataSource = clientRepository.ReadClients(); comboBoxClient.DataSource = clientRepository.ReadClients();
comboBoxClient.DisplayMember = "Name"; comboBoxClient.DisplayMember = "Name";
comboBoxClient.ValueMember = "Id"; comboBoxClient.ValueMember = "Id";
ColumProduct.DataSource = productRepository.ReadProducts();
ColumProduct.DisplayMember = "View";
ColumProduct.ValueMember = "Id";
// Инициализация DateTimePicker // Инициализация DateTimePicker
dateTimePicker.Format = DateTimePickerFormat.Custom; dateTimePicker.Format = DateTimePickerFormat.Custom;
dateTimePicker.CustomFormat = "yyyy-MM-dd HH:mm:ss"; dateTimePicker.CustomFormat = "yyyy-MM-dd HH:mm:ss";
dateTimePicker.Value = DateTime.Now; // Устанавливаем текущую дату и время по умолчанию dateTimePicker.Value = DateTime.Now; // Устанавливаем текущую дату и время по умолчанию
} }
private void ButtonAdd_Click(object sender, EventArgs e) 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 void ButtonCancel_Click(object sender, EventArgs e) => Close();
private List<OrderProduct> CreateListProductFromDataGrid() private List<OrderProduct> CreateListProductFromDataGrid()
{ {
var list = new List<OrderProduct>(); var list = new List<OrderProduct>();
foreach (DataGridViewRow row in dataGridView.Rows) 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; 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; return list;
} }
} }
} }

View File

@ -26,16 +26,17 @@ public class OrderRepository : IOrderRepository
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(order)); _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(order));
try try
{ {
using var connection = new NpgsqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString); ///Создается объект NpgsqlConnection с использованием строки подключения из _connectionString.
connection.Open(); connection.Open(); ////открытие соединения
using var transaction = connection.BeginTransaction(); using var transaction = connection.BeginTransaction(); ///начинаем транзакцию
var queryInsert = @" ///Выполнение запросов в рамках транзакции:
var queryInsert = @"
INSERT INTO Orders (DataTime, Status, Characteristic, IdClient) INSERT INTO Orders (DataTime, Status, Characteristic, IdClient)
VALUES (@DataTime, @Status, @Characteristic, @IdClient); VALUES (@DataTime, @Status, @Characteristic, @IdClient);
SELECT MAX(Id) FROM Orders"; SELECT MAX(Id) FROM Orders";
var orderId = connection.QueryFirst<int>(queryInsert, order, transaction); var orderId = connection.QueryFirst<int>(queryInsert, order, transaction);
var querySubInsert = @" var querySubInsert = @"
INSERT INTO Orders_Products (OrderId, ProductId, Count) INSERT INTO Order_Products (OrderId, ProductId, Count)
VALUES (@OrderId, @ProductId, @Count)"; VALUES (@OrderId, @ProductId, @Count)";
foreach (var elem in order.OrderProduct) foreach (var elem in order.OrderProduct)
{ {
@ -44,11 +45,11 @@ public class OrderRepository : IOrderRepository
orderId, orderId,
elem.ProductId, elem.ProductId,
elem.Count elem.Count
}, transaction); }, transaction);///добавляем в транзакцию зпросы
} }
transaction.Commit(); transaction.Commit(); ///Если все запросы выполнены успешно, транзакция фиксируется с помощью метода
} }
catch (Exception ex) catch (Exception ex)/// исключение логируется.
{ {
_logger.LogError(ex, "Ошибка при добавлении объекта"); _logger.LogError(ex, "Ошибка при добавлении объекта");
throw; throw;

View File

@ -20,6 +20,6 @@ public class ProductMaterialRepository : IProductMaterialRepository
public ProductMaterial ReadMaterialConsumptionById(int id) public ProductMaterial ReadMaterialConsumptionById(int id)
{ {
return ProductMaterial.CreateOperation(id, 0, 0, 0); return ProductMaterial.CreateOperation(id, 0, 0);
} }
} }